Class: TelegramBot::Bot

Inherits:
Object
  • Object
show all
Defined in:
lib/telegram_bot/bot.rb

Constant Summary collapse

ENDPOINT =
'https://api.telegram.org/'

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Bot

Returns a new instance of Bot.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/telegram_bot/bot.rb', line 5

def initialize(opts = {})
  # compatibility with just passing a token
  if opts.is_a?(String)
    opts = { token: opts }
  end

  @token = opts.fetch(:token)
  @timeout = opts[:timeout] || 50
  @offset = opts[:offset] || 0
  @logger = opts[:logger] || NullLogger.new
  @connection = Excon.new(ENDPOINT, persistent: true)
end

Instance Method Details

#get_meObject Also known as: me



18
19
20
21
22
23
# File 'lib/telegram_bot/bot.rb', line 18

def get_me
  @me ||= begin
            response = request(:getMe)
            User.new(response.result)
          end
end

#get_updates(opts = {}, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/telegram_bot/bot.rb', line 27

def get_updates(opts = {}, &block)
  return get_last_messages(opts) unless block_given?

  logger.info "starting get_updates loop"
  loop do
    messages = get_last_messages(opts)
    messages.each do |message|
      logger.info "message from @#{message.chat.friendly_name}: #{message.text.inspect}"
      yield message
    end
  end
end

#send_message(out_message) ⇒ Object



40
41
42
43
44
# File 'lib/telegram_bot/bot.rb', line 40

def send_message(out_message)
  response = request(:sendMessage, out_message.to_h)
  logger.info "sending message: #{out_message.text.inspect} to #{out_message.chat_friendly_name}"
  Message.new(response.result)
end