]> git.cworth.org Git - turbot/blob - turbot/events.py
Add list of available hunts to the Turbot home view
[turbot] / turbot / events.py
1 from turbot.blocks import (
2     section_block, text_block, button_block, actions_block, divider_block
3 )
4 from turbot.sheets import sheets_create, sheets_create_for_puzzle
5 from turbot.slack import slack_send_message, slack_channel_members
6 from turbot.hunt import find_hunt_for_hunt_id
7 from boto3.dynamodb.conditions import Key
8
9 TURBOT_USER_ID = 'U01B9QM4P9R'
10
11 events = {}
12
13 lambda_success = {'statusCode': 200}
14 lambda_error = {'statusCode': 400}
15
16 def channel_url(channel_id):
17     return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
18
19 def puzzle_block(puzzle):
20     name = puzzle['name']
21     status = puzzle['status']
22     solution = puzzle['solution']
23     channel_id = puzzle['channel_id']
24     url = puzzle.get('url', None)
25     sheet_url = puzzle.get('sheet_url', None)
26     state = puzzle.get('state', None)
27     status_emoji = ''
28     solution_str = ''
29
30     if status == 'solved':
31         status_emoji = ":ballot_box_with_check:"
32     else:
33         status_emoji = ":white_square:"
34
35     if len(solution):
36         solution_str = "*`" + '`, `'.join(solution) + "`*"
37
38     links = []
39     if url:
40         links.append("<{}|Puzzle>".format(url))
41     if sheet_url:
42         links.append("<{}|Sheet>".format(sheet_url))
43
44     state_str = ''
45     if state:
46         state_str = "\n{}".format(state)
47
48     puzzle_text = "{}{} <{}|{}> ({}){}".format(
49         status_emoji, solution_str,
50         channel_url(channel_id), name,
51         ', '.join(links), state_str
52     )
53
54     return section_block(text_block(puzzle_text))
55
56 def hunt_details_block(turb, hunt):
57     name = hunt['name']
58     hunt_id = hunt['hunt_id']
59     channel_id = hunt['channel_id']
60
61     response = turb.table.query(
62         KeyConditionExpression=(
63             Key('hunt_id').eq(hunt_id) &
64             Key('SK').begins_with('puzzle-')
65         )
66     )
67     puzzles = response['Items']
68
69     hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
70
71     return [
72         section_block(text_block(hunt_text)),
73         *[puzzle_block(puzzle) for puzzle in puzzles],
74         divider_block()
75     ]
76
77 def available_hunt_block(turb, hunt):
78
79     name = hunt['name']
80     channel_id = hunt['channel_id']
81
82     hunt_link = "*<{}|{}>*".format(channel_url(channel_id), name)
83
84     return [
85         section_block(text_block(hunt_link)),
86     ]
87
88 def home(turb, user_id):
89     """Returns a view to be published as the turbot home tab for user_id
90
91     The return value is a dictionary suitable to be published to the
92     Slack views_publish API."""
93
94     # Behave cleanly if there is no "turbot" table at all yet.
95     try:
96         response = turb.table.scan(
97             IndexName="is_hunt_index",
98         )
99         hunts = response['Items']
100     except Exception:
101         hunts = []
102
103     my_hunt_blocks = []
104     available_hunt_blocks = []
105     for hunt in hunts:
106         if not hunt['active']:
107             continue
108         if user_id in slack_channel_members(turb.slack_client,
109                                             hunt['channel_id']):
110             my_hunt_blocks += hunt_details_block(turb, hunt)
111         else:
112             available_hunt_blocks += available_hunt_block(turb, hunt)
113
114     if len(my_hunt_blocks):
115         my_hunt_blocks = [
116             section_block(text_block("*Hunts you belong to:*")),
117             divider_block(),
118             * my_hunt_blocks
119         ]
120     else:
121         my_hunt_blocks = [
122             section_block(text_block("You do not belong to any hunts"))
123         ]
124
125     if len(available_hunt_blocks):
126         available_hunt_blocks = [
127             section_block(text_block("*Hunts you can join:*")),
128             divider_block(),
129             * available_hunt_blocks
130         ]
131
132     return {
133         "type": "home",
134         "blocks": [
135             * my_hunt_blocks,
136             * available_hunt_blocks,
137             actions_block(button_block("New hunt", "new_hunt"))
138         ]
139     }
140
141 def app_home_opened(turb, event):
142     """Handler for the app_home_opened event
143
144     This event occurs when a user visits the home tab for the turbot app.
145     In response to this event we need to publish a view for the user."""
146
147     user_id = event['user']
148     view = home(turb, user_id)
149     turb.slack_client.views_publish(user_id=user_id, view=view)
150     return lambda_success
151
152 events['app_home_opened'] = app_home_opened
153
154 def hunt_channel_created(turb, channel_name, channel_id):
155     """Creates a Google sheet for a newly-created hunt channel"""
156
157     # First see if we can find an entry for this hunt in the database.
158     # If not, simply return an error and let Slack retry
159     response = turb.table.query(
160         IndexName='channel_id_index',
161         KeyConditionExpression=Key("channel_id").eq(channel_id)
162     )
163     if 'Items' not in response:
164         print("Warning: Cannot find channel_id {} in turbot table. "
165               .format(channel_id) + "Letting Slack retry this event")
166         return lambda_error
167
168     item = response['Items'][0]
169
170     if 'sheet_url' in item:
171         print("Info: channel_id {} already has sheet_url {}. Exiting."
172               .format(channel_id, item['sheet_url']))
173         return lambda_success
174
175     # Before launching into sheet creation, indicate that we're doing this
176     # in the database. This way, if we take too long to create the sheet
177     # and Slack retries the event, that next event will see this 'pending'
178     # string and cleanly return (eliminating all future retries).
179     item['sheet_url'] = 'pending'
180     turb.table.put_item(Item=item)
181
182     # Also, let the channel users know what we are up to
183     slack_send_message(
184         turb.slack_client, channel_id,
185         "Welcome to the channel for the {} hunt! ".format(item['name'])
186         + "Please wait a minute or two while I create some backend resources.")
187
188     # Create a sheet for the hunt
189     sheet = sheets_create(turb, item['name'])
190
191     # Update the database with the URL of the sheet
192     item['sheet_url'] = sheet['url']
193     turb.table.put_item(Item=item)
194
195     # Message the channel with the URL of the sheet
196     slack_send_message(turb.slack_client, channel_id,
197                        "Sheet created for this hunt: {}".format(sheet['url']))
198
199     # Mark the hunt as active in the database
200     item['active'] = True
201     turb.table.put_item(Item=item)
202
203     # Message the hunt channel that the database is ready
204     slack_send_message(
205         turb.slack_client, channel_id,
206         "Thank you for waiting. This hunt is now ready to begin! "
207         + "Use `/puzzle` to create puzzles for the hunt.")
208
209     return lambda_success
210
211 def set_channel_description(turb, puzzle):
212     channel_id = puzzle['channel_id']
213     description = puzzle['name']
214     url = puzzle.get('url', None)
215     sheet_url = puzzle.get('sheet_url', None)
216
217     links = []
218     if url:
219         links.append("<{}|Puzzle>".format(url))
220     if sheet_url:
221         links.append("<{}|Sheet>".format(sheet_url))
222
223     if len(links):
224         description += "({})".format(', '.join(links))
225
226     turb.slack_client.conversations_setPurpose(channel=channel_id,
227                                                purpose=description)
228     turb.slack_client.conversations_setTopic(channel=channel_id,
229                                              topic=description)
230
231 def puzzle_channel_created(turb, channel_name, channel_id):
232     """Creates sheet and invites user for a newly-created puzzle channel"""
233
234     # First see if we can find an entry for this puzzle in the database.
235     # If not, simply return an error and let Slack retry
236     response = turb.table.query(
237         IndexName="channel_id_index",
238         KeyConditionExpression=Key("channel_id").eq(channel_id),
239     )
240     if 'Items' not in response:
241         print("Warning: Cannot find channel_id {} in turbot table. "
242               .format(channel_id) + "Letting Slack retry this event")
243         return lambda_error
244
245     puzzle = response['Items'][0]
246
247     if 'sheet_url' in puzzle:
248         print("Info: channel_id {} already has sheet_url {}. Exiting."
249               .format(channel_id, puzzle['sheet_url']))
250         return lambda_success
251
252     # Before launching into sheet creation, indicate that we're doing this
253     # in the database. This way, if we take too long to create the sheet
254     # and Slack retries the event, that next event will see this 'pending'
255     # string and cleanly return (eliminating all future retries).
256     puzzle['sheet_url'] = 'pending'
257     puzzle['channel_url'] = channel_url(channel_id)
258     turb.table.put_item(Item=puzzle)
259
260     # Create a sheet for the puzzle
261     sheet = sheets_create_for_puzzle(turb, puzzle)
262
263     # Update the database with the URL of the sheet
264     puzzle['sheet_url'] = sheet['url']
265     turb.table.put_item(Item=puzzle)
266
267     # Get the new sheet_url into the channel description
268     set_channel_description(turb, puzzle)
269
270     # And finally, give a welcome message with some documentation
271     # on how to update the state of the puzzle in the database.
272     welcome_msg = (
273         "Welcome! This channel is the primary place to "
274         + "discuss things as the team works together to solve the "
275         + "puzzle '{}'. ".format(puzzle['name'])
276     )
277
278     if 'url' in puzzle:
279         welcome_msg += (
280             "See the <{}|puzzle itself> ".format(puzzle['url'])
281             + "for what was originally presented to us."
282         )
283
284     sheet_msg = (
285         "Actual puzzle solving work will take place within the following "
286         + "<{}|shared spreadsheet> ".format(puzzle['sheet_url'])
287     )
288
289     state_msg = (
290         "Whenever the status of the puzzle progress changes "
291         + "significantly, please type `/state` with a brief message "
292         + "explaining where things stand. This could be something "
293         + "like `/state Grid is filled. Need insight for extraction.` "
294         + "or `/state Nathan has printed this and is cutting/assembling`. "
295         + "It's especially important to put information in `/state` "
296         + "when you step away from a puzzle so the next team members "
297         + "to arrive will know what is going on."
298     )
299
300     solved_msg = (
301         "When a puzzle has been solved, submitted, and the solution is "
302         + "confirmed, please type `/solved THE PUZZLE ANSWER HERE`. All "
303         + "information given in `/state` and `/solved` will be presented "
304         + "in this channel's topic as well as in the hunt overview "
305         + "(which is available by selecting \"Turbot\" from the Slack "
306         + "list of members)."
307     )
308
309     turb.slack_client.chat_postMessage(
310         channel=channel_id,
311         text="New puzzle: {}".format(['name']),
312         blocks=[
313             section_block(text_block(welcome_msg)),
314             section_block(text_block(sheet_msg)),
315             section_block(text_block(state_msg)),
316             section_block(text_block(solved_msg))
317         ])
318
319     # Finally, finally, notify the hunt channel about the new puzzle
320     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
321     slack_send_message(
322         turb.slack_client, hunt['channel_id'],
323         "New puzzle available: <{}|{}>".format(
324             puzzle['channel_url'],
325             puzzle['name'])
326     )
327
328     return lambda_success
329
330 def channel_created(turb, event):
331
332     channel = event['channel']
333     channel_id = channel['id']
334     channel_name = channel['name']
335     creator = channel['creator']
336
337     # Ignore any channels that turbot didn't create
338     if creator != TURBOT_USER_ID:
339         print("channel_created: Not a turbot-created channel. Exiting.")
340         return lambda_success
341
342     # The presence of a hyphen determines whether this is a puzzle
343     # channel or a hunt channel.
344     if '-' in channel_name:
345         return puzzle_channel_created(turb, channel_name, channel_id)
346     else:
347         return hunt_channel_created(turb, channel_name, channel_id)
348
349 events['channel_created'] = channel_created