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