Module: Rubotnik::Helpers

Included in:
MessageDispatch, PostbackDispatch
Defined in:
lib/rubotnik/helpers.rb

Constant Summary collapse

GRAPH_URL =
'https://graph.facebook.com/v2.8/'.freeze

Class Method Summary collapse

Class Method Details

.call_graph_api(url) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rubotnik/helpers.rb', line 60

def call_graph_api(url)
  @message.typing_on
  response = HTTParty.get(url)
  @message.typing_off
  case response.code
  when 200
    Rubotnik.logger.info "Data received from Graph API: #{response.body}" # logging
    return JSON.parse(response.body, symbolize_names: true)
  else
    Rubotnik.logger.info "Request failed: #{response.body}"
    return false
  end
end

.get_user_info(*fields) ⇒ Object

Get user info from Graph API. Takes names of required fields as symbols developers.facebook.com/docs/graph-api/reference/v2.2/user



49
50
51
52
53
54
55
56
57
58
# File 'lib/rubotnik/helpers.rb', line 49

def (*fields)
  str_fields = fields.map(&:to_s).join(',')
  url = GRAPH_URL + @user.id + '?fields=' + str_fields + '&access_token=' +
        ENV['ACCESS_TOKEN']
  begin
    return call_graph_api(url)
  rescue => e
    return false
  end
end

.message_contains_location?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/rubotnik/helpers.rb', line 43

def message_contains_location?
  !@message.attachments.nil? && @message.attachments.first['type'] == 'location'
end

.next_command(command) ⇒ Object



31
32
33
# File 'lib/rubotnik/helpers.rb', line 31

def next_command(command)
  @user.assign_command(command)
end

.say(text, quick_replies: [], user: @user) ⇒ Object

abstraction over Bot.deliver to send messages declaratively and directly



12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/rubotnik/helpers.rb', line 12

def say(text, quick_replies: [], user: @user)
  message_options = {
    recipient: { id: user.id },
    message: { text: text }
  }
  if quick_replies && !quick_replies.empty?
    message_options[:message][:quick_replies] = UI::QuickReplies
                                                  .build(*quick_replies)
  end

  send_message(message_options)
end

.send_message(payload) ⇒ Object



74
75
76
# File 'lib/rubotnik/helpers.rb', line 74

def send_message(payload)
  Bot.deliver(payload, access_token: ENV['ACCESS_TOKEN'])
end

.show(ui_element, user: @user) ⇒ Object



25
26
27
28
29
# File 'lib/rubotnik/helpers.rb', line 25

def show(ui_element, user: @user)
  payload = ui_element.build(user)

  send_message(payload)
end

.stop_threadObject



35
36
37
# File 'lib/rubotnik/helpers.rb', line 35

def stop_thread
  @user.reset_command
end

.text_message?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/rubotnik/helpers.rb', line 39

def text_message?
  @message.respond_to?(:text) && !@message.text.nil?
end