Class: Botkit::Telegram::Bot

Inherits:
Bot
  • Object
show all
Defined in:
lib/botkit/telegram/bot.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_token:) ⇒ Bot

Returns a new instance of Bot.



9
10
11
12
13
14
# File 'lib/botkit/telegram/bot.rb', line 9

def initialize(api_token:)
  super()
  @api_token = api_token
  @booted_at = Time.now.utc.to_i
  @offset = 0
end

Instance Attribute Details

#api_tokenObject (readonly)

Returns the value of attribute api_token.



6
7
8
# File 'lib/botkit/telegram/bot.rb', line 6

def api_token
  @api_token
end

#booted_atObject (readonly)

Returns the value of attribute booted_at.



6
7
8
# File 'lib/botkit/telegram/bot.rb', line 6

def booted_at
  @booted_at
end

#offsetObject

Returns the value of attribute offset.



7
8
9
# File 'lib/botkit/telegram/bot.rb', line 7

def offset
  @offset
end

Instance Method Details

#callObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/botkit/telegram/bot.rb', line 16

def call
  context = self

  response = Aitch.post do
    url "https://api.telegram.org/bot#{context.api_token}/getUpdates"
    params offset: context.offset,
           allowed_updates: "message"
    options expect: 200
  end

  messages = response.data["result"]
  return if messages.empty?

  self.offset = messages.last["update_id"] + 1
  messages
    .reject {|message| message.key?("edited_message") }
    .select {|message| message.dig("message", "date") >= booted_at }
    .map(&method(:prepare_message))
    .each(&method(:handle_incoming_message))
end

#prepare_message(message) ⇒ Object



37
38
39
40
41
42
43
# File 'lib/botkit/telegram/bot.rb', line 37

def prepare_message(message)
  params = parse_message(message.dig("message", "text"))
  params = params.merge(raw: message,
                        channel_id: message.dig("message", "chat", "id"),
                        id: message.dig("message", "message_id"))
  Message.new(**params)
end

#reply_message(message, reply, options = {}) ⇒ Object



60
61
62
# File 'lib/botkit/telegram/bot.rb', line 60

def reply_message(message, reply, options = {})
  send_message(reply, options.merge(reply_to_message_id: message.id))
end

#send_message(message, options = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/botkit/telegram/bot.rb', line 45

def send_message(message, options = {})
  context = self

  message_params = {
    text: message.text,
    chat_id: message.channel_id
  }.merge(options)

  Aitch.post do
    url "https://api.telegram.org/bot#{context.api_token}/sendMessage"
    params message_params
    options expect: 200
  end
end