-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.rb
More file actions
127 lines (109 loc) · 2.58 KB
/
bot.rb
File metadata and controls
127 lines (109 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
require 'bundler/setup'
require 'sinatra'
require 'twilio-ruby'
require 'dialog-api'
require 'active_support/core_ext/hash'
# Load environment variables from .env
require 'dotenv'
Dotenv.load
# Helpers to handle tracking with Dialog
class DialogTwilio
def initialize(client)
@client = client
end
# @param params [Hash]
def incoming(params)
payload = {
message: {
sent_at: Time.now.to_f,
properties: {
text: params['Body']
},
},
creator: {
distinct_id: params['From'],
type: 'interlocutor',
phone: params['From']
}
}.deep_merge(dialog_attributes(params))
@client.track(payload)
end
# @param params [Hash]
# @param message [String]
def outgoing(params, message)
payload = {
message: {
sent_at: Time.now.to_f,
properties: {
text: message
}
},
creator: {
distinct_id: 'bot_id',
type: 'bot'
}
}.deep_merge(dialog_attributes(params))
@client.track(payload)
end
private
# @param params [Hash]
def dialog_attributes(params)
{
message: {
platform: 'twilio-sms',
provider: 'dialog-ruby',
mtype: 'text'
},
conversation: {
distinct_id: (params['From'] + params['To']).strip
}
}
end
end
# Create a Dialog API client
client = Dialog.new({
api_token: ENV.fetch('DIALOG_API_TOKEN'),
bot_id: ENV.fetch('DIALOG_BOT_ID'),
on_error: Proc.new do |status, message, detail|
p [status, message, detail]
end
})
# Create a Dialog tracking helper
dialog = DialogTwilio.new(client)
# Receive a SMS
#
# Twilio payload:
#
# {
# "ToCountry"=>"CA",
# "ToState" => "Québec",
# "SmsMessageSid" => "SM031adc20211f6bdc0533cb93c53ac57f",
# "NumMedia" => "0",
# "ToCity" => "",
# "FromZip" => "",
# "SmsSid" => "SM031adc20211f6bdc0533cb93c53ac57f",
# "FromState" => "QC",
# "SmsStatus" => "received",
# "FromCity" => "QUEBEC",
# "Body" => "Hugh",
# "FromCountry" => "CA",
# "To"=>"+1 58 17004296",
# "ToZip" => "",
# "NumSegments" => "1",
# "MessageSid" => "SM031adc20211f6bdc0533cb93c53ac57f",
# "AccountSid" => "ACaf464a215129ea7cd739c2a948672250",
# "From" => "+14185800893",
# "ApiVersion" => "2010-04-01"
# }
post '/sms' do
content_type 'text/xml'
# Track incoming message
dialog.incoming(params)
response = Twilio::TwiML::Response.new do |res|
message = "Gotcha!"
# Track outgoing message
dialog.outgoing(params, message)
res.message message
end
response.to_xml
end