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