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