Class: Messenger::Bot::Client

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

Constant Summary collapse

TIMEOUT_EXCEPTIONS =
[Timeout::Error]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token, h = {}) ⇒ Client

Returns a new instance of Client.



14
15
16
17
18
19
20
# File 'lib/messenger/bot/client.rb', line 14

def initialize(token, h = {})
  options = default_options.merge(h)
  @api = Api.new(token)
  @offset = options[:offset]
  @timeout = options[:timeout]
  @logger = options[:logger]
end

Instance Attribute Details

#apiObject (readonly)

Returns the value of attribute api.



7
8
9
# File 'lib/messenger/bot/client.rb', line 7

def api
  @api
end

#loggerObject

Returns the value of attribute logger.



8
9
10
# File 'lib/messenger/bot/client.rb', line 8

def logger
  @logger
end

#offsetObject (readonly)

Returns the value of attribute offset.



7
8
9
# File 'lib/messenger/bot/client.rb', line 7

def offset
  @offset
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



7
8
9
# File 'lib/messenger/bot/client.rb', line 7

def timeout
  @timeout
end

Class Method Details

.run(*args, &block) ⇒ Object



10
11
12
# File 'lib/messenger/bot/client.rb', line 10

def self.run(*args, &block)
  new(*args).run(&block)
end

Instance Method Details

#fetch_updatesObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/messenger/bot/client.rb', line 34

def fetch_updates
  response = api.getUpdates(offset: offset, timeout: timeout)
  return unless response['ok']

  response['result'].each do |data|
    update = Types::Update.new(data)
    @offset = update.update_id.next
    message = extract_message(update)
    log_incoming_message(message)
    yield message
  end
rescue *TIMEOUT_EXCEPTIONS
  retry
end

#listen(&block) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/messenger/bot/client.rb', line 26

def listen(&block)
  logger.info('Starting bot')
  running = true
  Signal.trap('INT') { running = false }
  fetch_updates(&block) while running
  exit
end

#run {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



22
23
24
# File 'lib/messenger/bot/client.rb', line 22

def run
  yield self
end