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