Module: Facebook::Messenger::Bot

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

Overview

The Bot module sends and receives messages.

Defined Under Namespace

Classes: AccessTokenError, AccountLinkingError, BadParameterError, ErrorParser, InternalError, LimitError, PermissionError, SendError

Constant Summary collapse

EVENTS =
%i[
  message
  delivery
  postback
  optin
  read
  account_linking
  referral
  message_echo
].freeze

Class Method Summary collapse

Class Method Details

.default_optionsObject

Default HTTParty options.



91
92
93
94
95
96
97
98
# File 'lib/facebook/messenger/bot.rb', line 91

def default_options
  super.merge(
    read_timeout: 300,
    headers: {
      'Content-Type' => 'application/json'
    }
  )
end

.deliver(message, access_token:) ⇒ 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.



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

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

  Facebook::Messenger::Bot::ErrorParser.raise_errors_from(response)

  response.body
end

.hooksObject

Return a Hash of hooks.



81
82
83
# File 'lib/facebook/messenger/bot.rb', line 81

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.



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

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

.receive(payload) ⇒ Object

Receive a given message from Messenger.

payload - A Hash describing the message.



64
65
66
67
68
# File 'lib/facebook/messenger/bot.rb', line 64

def receive(payload)
  callback = Facebook::Messenger::Incoming.parse(payload)
  event = Facebook::Messenger::Incoming::EVENTS.invert[callback.class]
  trigger(event.to_sym, callback)
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.



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

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

.unhookObject

Deregister all hooks.



86
87
88
# File 'lib/facebook/messenger/bot.rb', line 86

def unhook
  @hooks = {}
end