Class: Messenger::Bot::Api

Inherits:
Object
  • Object
show all
Includes:
HTTMultiParty
Defined in:
lib/messenger/bot/api.rb

Constant Summary collapse

ENDPOINTS =
%w(
  messages
).freeze
POOL_SIZE =
ENV.fetch('MESSENGER_BOT_POOL_SIZE', 1).to_i.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(token) ⇒ Api

Returns a new instance of Api.



17
18
19
# File 'lib/messenger/bot/api.rb', line 17

def initialize(token)
  @token = token
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



21
22
23
24
25
26
# File 'lib/messenger/bot/api.rb', line 21

def method_missing(method_name, *args, &block)
  endpoint = method_name.to_s
  endpoint = camelize(endpoint) if endpoint.include?('_')

  ENDPOINTS.include?(endpoint) ? call(endpoint, *args) : super
end

Instance Attribute Details

#tokenObject (readonly)

Returns the value of attribute token.



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

def token
  @token
end

Instance Method Details

#call(endpoint, raw_params = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/messenger/bot/api.rb', line 45

def call(endpoint, raw_params = {})
  params = build_params(raw_params)
  response = self.class.post("/me/#{endpoint}?access_token=#{token}", query: params)
  if response.code == 200
    response.to_hash
  else
    fail Exceptions::ResponseError.new(response),
         'Messenger API has returned the error.'
  end
end

#respond_to_missing?(*args) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
# File 'lib/messenger/bot/api.rb', line 28

def respond_to_missing?(*args)
  method_name = args[0].to_s
  method_name = camelize(method_name) if method_name.include?('_')

  ENDPOINTS.include?(method_name) || super
end

#user_profile(user_id) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/messenger/bot/api.rb', line 35

def (user_id)
  response = self.class.get("#{user_id}?fields=first_name,last_name,profile_pic&access_token=#{token}")
  if response.code == 200
    response.to_hash
  else
    fail Exceptions::ResponseError.new(response),
         'Messenger API has returned the error.'
  end
end