Module: Bobot::Commander

Includes:
GraphFacebook
Defined in:
lib/bobot/commander.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

EVENTS =
%i[
  message
  delivery
  postback
  optin
  read
  account_linking
  referral
  message_echo
  message_request
  policy-enforcement
  pass_thread_control
  take_thread_control
].freeze

Constants included from GraphFacebook

GraphFacebook::GRAPH_FB_URL, GraphFacebook::GRAPH_HEADERS

Class Method Summary collapse

Methods included from GraphFacebook

included

Class Method Details

.deliver(endpoint: '/me/messages', body:, query:) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/bobot/commander.rb', line 23

def deliver(endpoint: '/me/messages', body:, query:)
  graph_post(
    endpoint,
    body: body,
    query: {
      access_token: query.fetch(:access_token),
    },
  )
end

.hooksObject



71
72
73
# File 'lib/bobot/commander.rb', line 71

def hooks
  @hooks ||= {}
end

.on(event, &block) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/bobot/commander.rb', line 33

def on(event, &block)
  if EVENTS.include? event
    hooks[event] = block
  else
    warn "[bobot trigger] Ignoring #{event.class} (not available in [#{EVENTS.join(', ')}])"
  end
end

.receive(payload, standby) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/bobot/commander.rb', line 49

def receive(payload, standby)
  event = Bobot::Event.parse(payload)
  event.mark_as_seen if event.page.present? && !standby && [Bobot::Event::MessageEcho, Bobot::Event::PassThreadControl, Bobot::Event::TakeThreadControl].none? { |c| event.is_a?(c) }
  hooks.fetch(Bobot::Event::EVENTS.invert[event.class].to_sym)
  Bobot::CommanderJob.send(
    Bobot.config.async ? :perform_later : :perform_now,
    { payload: payload },
  )
rescue KeyError
  warn "[bobot trigger] Ignoring #{event.class} (no hook registered)"
end

.receive_message(payload) ⇒ Object



41
42
43
# File 'lib/bobot/commander.rb', line 41

def receive_message(payload)
  receive(payload, false)
end

.receive_standby(payload) ⇒ Object



45
46
47
# File 'lib/bobot/commander.rb', line 45

def receive_standby(payload)
  receive(payload, true)
end

.trigger(payload) ⇒ Object



61
62
63
64
65
66
67
68
69
# File 'lib/bobot/commander.rb', line 61

def trigger(payload)
  event = Bobot::Event.parse(payload)
  return if !event.page.present?

  hook = hooks.fetch(Bobot::Event::EVENTS.invert[event.class].to_sym)
  hook.call(event)
rescue KeyError
  warn "[bobot trigger] Ignoring #{event.class} (no hook registered)"
end

.unhookObject



75
76
77
# File 'lib/bobot/commander.rb', line 75

def unhook
  @hooks = {}
end