class Telepost

Telepost is a simple gateway to Telegram, which can post messages and respond to primitive requests:

require 'telepost'
tp = Telepost.new('... secret token ...')
tp.run do |chat, msg|
  # Reply to the message via tp.post(msg, chat)
end

For more information read README file.

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright © 2018-2019 Yegor Bugayenko

License

MIT

Attributes

client[R]

To make it possible to get the client.

Public Class Methods

new(token, chats: []) click to toggle source

Makes a new object. To obtain a token you should talk to the @BotFather in Telegram.

# File lib/telepost.rb, line 71
def initialize(token, chats: [])
  @token = token
  @client = Telebot::Client.new(token)
  @chats = chats
end

Public Instance Methods

post(chat, *lines) click to toggle source

Post a single message to the designated chat room. The chat argument can either me an integer, if you know the chat ID, or the name of the channel (your bot has to be the admin there). The lines provided will be concatenated with a space between them.

# File lib/telepost.rb, line 111
def post(chat, *lines)
  msg = lines.join(' ')
  @client.send_message(
    chat_id: chat,
    parse_mode: 'Markdown',
    disable_web_page_preview: true,
    text: msg
  )
rescue Telebot::Error => e
  raise CantPost, "#{e.message}: \"#{msg}\""
end
run() { |chat, message| ... } click to toggle source

You can run a chat bot to listen to the messages coming to it, in a separate thread.

# File lib/telepost.rb, line 79
def run
  Telebot::Bot.new(@token).run do |chat, message|
    if block_given?
      yield(chat, message)
    elsif !chat.nil?
      id = message.chat.id
      if id.positive?
        post(
          message.chat.id,
          "This is your chat ID: `#{message.chat.id}`."
        )
      end
    end
  end
rescue Net::OpenTimeout
  retry
end
spam(*lines) click to toggle source

Send the message (lines will be concatenated with a space between them) to the chats provided in the constructor and encapsulated.

# File lib/telepost.rb, line 100
def spam(*lines)
  @chats.each do |chat|
    post(chat, lines)
  end
end