Module: Facebook::Messenger::Bot

Includes:
HTTParty
Defined in:
lib/facebook/messenger/bot.rb

Overview

The Bot module sends and receives messages.

Defined Under Namespace

Classes: InternalError, PermissionDenied, RecipientNotFound

Constant Summary collapse

EVENTS =
[:message, :delivery, :postback, :optin].freeze

Class Method Summary collapse

Class Method Details

.default_optionsObject

Default HTTParty options.


107
108
109
110
111
112
113
114
115
116
# File 'lib/facebook/messenger/bot.rb', line 107

def default_options
  super.merge(
    query: {
      access_token: Facebook::Messenger.config.access_token
    },
    headers: {
      'Content-Type' => 'application/json'
    }
  )
end

.deliver(message) ⇒ Object

Deliver a message with the given payload.

message - A Hash describing the recipient and the message*.

Returns a String describing the message ID if the message was sent, or raises an exception if it was not.


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

def deliver(message)
  response = post '/messages', body: JSON.dump(message), format: :json

  raise_errors_from(response)

  response['message_id']
end

.error_class_from_error_code(error_code) ⇒ Object

Find the appropriate error class for the given error code.

error_code - An Integer describing an error code.

Returns an error class, or raises KeyError if none was found.


88
89
90
91
92
93
94
# File 'lib/facebook/messenger/bot.rb', line 88

def error_class_from_error_code(error_code)
  {
    100 => RecipientNotFound,
    10 => PermissionDenied,
    2 => InternalError
  }[error_code] || Facebook::Messenger::Error
end

.hooksObject

Return a Hash of hooks.


97
98
99
# File 'lib/facebook/messenger/bot.rb', line 97

def hooks
  @hooks ||= {}
end

.on(event, &block) ⇒ Object

Register a hook for the given event.

event - A String describing a Messenger event. block - A code block to run upon the event.


32
33
34
35
36
37
38
39
40
# File 'lib/facebook/messenger/bot.rb', line 32

def on(event, &block)
  unless EVENTS.include? event
    raise ArgumentError,
          "#{event} is not a valid event; " \
          "available events are #{EVENTS.join(',')}"
  end

  hooks[event] = block
end

.raise_errors_from(response) ⇒ Object

Raise any errors in the given response.

response - A HTTParty::Response object.

Returns nil if no errors were found, otherwises raises appropriately.

Raises:


73
74
75
76
77
78
79
80
81
# File 'lib/facebook/messenger/bot.rb', line 73

def raise_errors_from(response)
  return unless response.key? 'error'
  error = response['error']

  raise(
    error_class_from_error_code(error['code']),
    (error['error_data'] || error['message'])
  )
end

.receive(payload) ⇒ Object

Receive a given message from Messenger.

payload - A Hash describing the message.


47
48
49
50
51
52
53
54
55
56
# File 'lib/facebook/messenger/bot.rb', line 47

def receive(payload)
  klass = Facebook::Messenger::Incoming.parse(payload)

  case klass
  when Incoming::Message then trigger(:message, klass)
  when Incoming::Delivery then trigger(:delivery, klass)
  when Incoming::Postback then trigger(:postback, klass)
  when Incoming::Optin then trigger(:optin, klass)
  end
end

.trigger(event, *args) ⇒ Object

Trigger the hook for the given event.

event - A String describing a Messenger event. args - Arguments to pass to the hook.


62
63
64
65
66
# File 'lib/facebook/messenger/bot.rb', line 62

def trigger(event, *args)
  hooks.fetch(event).call(*args)
rescue KeyError
  $stderr.puts "Ignoring #{event} (no hook registered)"
end

.unhookObject

Deregister all hooks.


102
103
104
# File 'lib/facebook/messenger/bot.rb', line 102

def unhook
  @hooks = {}
end