This repository has been archived by the owner on Sep 9, 2021. It is now read-only.
/
bot.rb
362 lines (319 loc) · 10.2 KB
/
bot.rb
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
require 'sinatra/base'
require 'dotenv/load'
require 'slack-ruby-client'
require 'json'
require 'uri'
require 'net/http'
require_relative 'Menu'
Slack.configure do |config|
config.token = ENV['SLACK_BOT_TOKEN']
fail 'Missing API token' unless config.token
end
# Slack Ruby client
$client = Slack::Web::Client.new
# Orders object
$orders = {}
# Menu class imported from Menu.rb
Menu.new
class API < Sinatra::Base
# Send response of message to response_url
def self.send_response(response_url, msg)
url = URI.parse(response_url)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['content-type'] = 'application/json'
request.body = JSON[msg]
response = http.request(request)
end
post '/slack/events' do
request_data = JSON.parse(request.body.read)
case request_data['type']
when 'url_verification'
# URL Verification event with challenge parameter
request_data['challenge']
when 'event_callback'
# Verify requests
if request_data['token'] != ENV['SLACK_VERIFICATION_TOKEN']
return
end
team_id = request_data['team_id']
event_data = request_data['event']
case event_data['type']
# Team Join event
when 'team_join'
Events.user_join(team_id, event_data)
# Message IM event
when 'message'
if event_data['subtype'] == 'bot_message' || event_data['subtype'] == 'message_changed'
return
end
Events.message(team_id, event_data)
else
puts "Unexpected events\n"
end
status 200
end
end
post '/slack/attachments' do
request.body.rewind
request_data = request.body.read
# Convert
request_data = URI.decode_www_form_component(request_data, enc=Encoding::UTF_8)
# Parse and remove "payload=" from beginning of string
request_data = JSON.parse(request_data.sub!('payload=', ''))
url = request_data['response_url']
case request_data['callback_id']
# Start order callback
when 'order:start'
# Modify message to acknowledge
msg = request_data['original_message']
msg['text'] = ':white_check_mark: I\'m getting an order started for you.'
msg['attachments'] = []
API.send_response(url, msg)
Bot.start_order(request_data['user']['id'], request_data['original_message'], url)
# Select type callback
when 'order:select_type'
selected = Bot.find_selected_option(
request_data['original_message'],
'order:select_type',
request_data['actions'][0]['selected_options'][0]['value']
)
updated = Bot.acknowledge_action_from_message(
request_data['original_message'],
'order:select_type',
"You chose a #{selected["text"].downcase}"
)
url = request_data['response_url']
API.send_response(url, updated)
attach = Bot.select_type_for_order(request_data['user']['id'], selected['value'])
order = Bot.summarize_order($orders[request_data['user']['id']])
updated['attachments'].push(attach)
updated['text'] = "Working on your #{order}"
API.send_response(url, updated)
# Select option callback
when 'order:select_option'
option_name = request_data['actions'][0]['name']
selected = Bot.find_selected_option(
request_data['original_message'],
'order:select_option',
request_data['actions'][0]['selected_options'][0]['value']
)
updated = Bot.acknowledge_action_from_message(
request_data['original_message'],
'order:select_option',
"You chose #{selected["text"].downcase}"
)
attach = Bot.select_option_for_order(
request_data['user']['id'],
option_name,
selected['value']
)
order_text = Bot.summarize_order($orders[request_data['user']['id']])
if !Bot.order_is_complete($orders[request_data['user']['id']])
updated['text'] = "Working on your #{order_text}"
updated['attachments'].push(attach)
else
updated['text'] = attach
end
API.send_response(request_data['response_url'], updated)
else
end
status 200
end
end
class Events
# Handle user join event
def self.user_join(team_id, event_data)
if event_data['user']['id']
user_id = event_data['user']['id']
# Sent intro message via DM
Bot.intro(user_id)
end
end
# Handle message IM event
def self.message(team_id, event_data)
if event_data['user']
user_id = event_data['user']
# Handle direct message
Bot.handle_direct_message(event_data)
end
# Handle direct messages
end
end
class Bot
# Send intro message to start order
def self.intro(user_id)
# Open IM
res = $client.im_open(user: user_id)
# Attachment with order:start callback ID
attachments = [{
color: '#5A352D',
title: 'How can I help you?',
callback_id: 'order:start',
actions: [
{
name: 'start',
text: 'Start a coffee order',
type: 'button',
value: 'order:start',
}]}]
if !res.channel.id.nil?
# Send message
$client.chat_postMessage(
channel: res.channel.id,
text: 'I am coffeebot, and I\'m here to help bring you fresh coffee :coffee:, made to order.',
attachments: attachments.to_json
)
end
end
def self.start_order(user_id, msg, url)
# Check if order already exists
if $orders[user_id].nil?
# Starts new order
options_list = Menu.list_of_types
$orders[user_id] = {
options: {}
}
# Sends menu with order:select_type callback
msg = {
text: 'Great! What can I get started for you?',
attachments: [{
color: '#5A352D',
callback_id: 'order:select_type',
text: '',
actions: [{
name: 'select_type',
type: 'select',
options: options_list
}]
}]
}
else
# Order already exists, don't start new one
msg = {
text: "I\'m already working on an order for you, please be patient",
replace_original: false
}
end
# Send message
API.send_response(url, msg)
end
# Find next option for order item
def self.next_option_for_order(order)
item = Menu.items.find { |i| i[:id] == order['type']}
if item.nil?
return
end
return item[:options].find {|o| !order[:options].key?(o) }
end
# Send user options to select from
def self.option_selection_for_order(user_id)
order = $orders[user_id]
option_id = self.next_option_for_order(order)
type_list = Menu.list_of_choices_for_option(option_id)
attach = {
color: '#5A352D',
callback_id: 'order:select_option',
text: "Which #{option_id} would you like?",
actions: [{
name: option_id,
type: 'select',
options: type_list
}]
}
return attach
end
# Determine whether option is done or needs option selection
def self.select_type_for_order(user_id, item_id)
order = $orders[user_id]
if order.nil?
return
end
order['type'] = item_id
if !order_is_complete(order)
return self.option_selection_for_order(user_id)
end
return self.finish_order(order)
end
# Select option for user_id order
def self.select_option_for_order(user_id, option_id, option_value)
order = $orders[user_id]
if order.nil?
return
end
order[:options][option_id] = option_value
if !order_is_complete(order)
return self.option_selection_for_order(user_id)
end
return self.finish_order(user_id)
end
# Finish order for user_id
def self.finish_order(user_id)
order = $orders[user_id]
order_item = Menu.items.find { |i| i[:id] == order['type']}[:name]
msg_fields = [{
title: 'Drink',
value: "#{order_item}"
}]
order[:options].map { |c, n|
choice_name = Menu.choice_name_for_id(c, n)
msg_fields.push({ title: c.capitalize, value: choice_name })
}
order_str = summarize_order($orders[user_id])
final_order = {
text: "<@#{user_id}> has submitted a new coffee order.",
attachments: [{
color: '#5A352D',
title: 'Order details',
text: "#{order_str}",
fields: msg_fields
}]
}
API.send_response(ENV['SLACK_WEBHOOK_URL'], final_order)
return "Your order of #{order_str} is coming right up!"
end
# Find attachment with action_callback_id
def self.find_attachment(message, action_callback_id)
message['attachments'].find { |a| a['callback_id'] == action_callback_id}
end
# Find option that was selected
def self.find_selected_option(original_message, action_callback_id, selected_value)
attachment = self.find_attachment(original_message, action_callback_id)
return attachment['actions'][0]['options'].find { |o| o['value'] == selected_value}
end
# Check if user has order to handle dm
def self.handle_direct_message(msg)
user = msg['user']
if $orders[user].nil?
self.intro(user)
else
$client.chat_postMessage(
channel: msg['channel'],
text: 'Let\'s keep working on the open order'
)
end
end
# Check if order is complete
def self.order_is_complete(order)
!next_option_for_order(order)
end
# Update attachment with acknowledgement
def self.acknowledge_action_from_message(original_message, action_callback_id, ack_text)
msg = original_message
attachment = self.find_attachment(msg, action_callback_id)
attachment['actions'] = ''
attachment['text'] = ":white_check_mark: #{ack_text}"
return msg
end
# Create string summary of order
def self.summarize_order(order)
item = Menu.items.find { |i| i[:id] == order['type'] }
summary = item[:name].to_s
options_text = order[:options].map { |c, n| "#{n} #{c}" }
if !options_text.empty?
summary.concat(" with #{options_text.join(" and ")}")
end
return summary.downcase
end
end