]> git.cworth.org Git - turbot/blob - turbot/events.py
At channel creation time, lodge Puzzle and Sheet URLs into channel topic
[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
7 TURBOT_USER_ID = 'U01B9QM4P9R'
8
9 events = {}
10
11 lambda_success = {'statusCode': 200}
12 lambda_error = {'statusCode': 400}
13
14 def channel_url(channel_id):
15     return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
16
17 def puzzle_block(puzzle):
18     name = puzzle['name']
19     status = puzzle['status']
20     solution = puzzle['solution']
21     channel_id = puzzle['channel_id']
22     url = puzzle.get('url', None)
23     sheet_url = puzzle.get('sheet_url', None)
24     status_emoji = ''
25     solution_str = ''
26
27     if status == 'solved':
28         status_emoji = ":ballot_box_with_check:"
29     else:
30         status_emoji = ":white_square:"
31
32     if len(solution):
33         solution_str = "*`" + '`, `'.join(solution) + "`*"
34
35     links = []
36     if url:
37         links.append("<{}|Puzzle>".format(url))
38     if sheet_url:
39         links.append("<{}|Sheet>".format(sheet_url))
40
41     puzzle_text = "{}{} <{}|{}> ({})".format(
42         status_emoji, solution_str,
43         channel_url(channel_id), name,
44         ', '.join(links)
45     )
46
47     return section_block(text_block(puzzle_text))
48
49 def hunt_block(turb, hunt):
50     name = hunt['name']
51     hunt_id = hunt['hunt_id']
52     channel_id = hunt['channel_id']
53
54     response = turb.db.Table(hunt_id).scan()
55     puzzles = response['Items']
56
57     hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
58
59     return [
60         section_block(text_block(hunt_text)),
61         *[puzzle_block(puzzle) for puzzle in puzzles],
62         divider_block()
63     ]
64
65 def home(turb, user_id):
66     """Returns a view to be published as the turbot home tab for user_id
67
68     The return value is a dictionary suitable to be published to the
69     Slack views_publish API."""
70
71     # Behave cleanly if there is no hunts table at all yet.
72     try:
73         response = turb.db.Table("hunts").scan()
74         hunts = response['Items']
75     except Exception:
76         hunts = []
77
78     hunt_blocks = []
79     for hunt in hunts:
80         if hunt['active']:
81             hunt_blocks += hunt_block(turb, hunt)
82
83     return {
84         "type": "home",
85         "blocks": [
86             section_block(text_block("*Active hunts*")),
87             divider_block(),
88             * hunt_blocks,
89             actions_block(button_block("New hunt", "new_hunt"))
90         ]
91     }
92
93 def app_home_opened(turb, event):
94     """Handler for the app_home_opened event
95
96     This event occurs when a user visits the home tab for the turbot app.
97     In response to this event we need to publish a view for the user."""
98
99     user_id = event['user']
100     view = home(turb, user_id)
101     turb.slack_client.views_publish(user_id=user_id, view=view)
102     return lambda_success
103
104 events['app_home_opened'] = app_home_opened
105
106 def hunt_channel_created(turb, channel_name, channel_id):
107     """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
108
109     # First see if we can find an entry for this hunt in the database.
110     # If not, simply return an error and let Slack retry
111     hunts_table = turb.db.Table("hunts")
112     response = hunts_table.get_item(
113         Key={'channel_id': channel_id},
114         ConsistentRead=True
115     )
116     if 'Item' not in response:
117         print("Warning: Cannot find channel_id {} in hunts table. "
118               .format(channel_id) + "Letting Slack retry this event")
119         return lambda_error
120
121     item = response['Item']
122
123     if 'sheet_url' in item:
124         print("Info: channel_id {} already has sheet_url {}. Exiting."
125               .format(channel_id, item['sheet_url']))
126         return lambda_success
127
128     # Remove any None items from our item before updating
129     if not item['url']:
130         del item['url']
131
132     # Before launching into sheet creation, indicate that we're doing this
133     # in the database. This way, if we take too long to create the sheet
134     # and Slack retries the event, that next event will see this 'pending'
135     # string and cleanly return (eliminating all future retries).
136     item['sheet_url'] = 'pending'
137     hunts_table.put_item(Item=item)
138
139     # Also, let the channel users know what we are up to
140     turb.slack_client.chat_postMessage(
141         channel=channel_id,
142         text="Welcome to the channel for the {} hunt! ".format(item['name'])
143         + "Please wait a minute or two while I create some backend resources.")
144
145     # Create a sheet for the channel
146     sheet = turbot.sheets.sheets_create(turb, channel_name)
147
148     # Update the database with the URL of the sheet
149     item['sheet_url'] = sheet['url']
150     hunts_table.put_item(Item=item)
151
152     # Message the channel with the URL of the sheet
153     turb.slack_client.chat_postMessage(channel=channel_id,
154                                        text="Sheet created for this hunt: {}"
155                                        .format(sheet['url']))
156
157     # Create a database table for this hunt's puzzles
158     table = turb.db.create_table(
159         TableName=channel_name,
160         KeySchema=[
161             {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
162         ],
163         AttributeDefinitions=[
164             {'AttributeName': 'channel_id', 'AttributeType': 'S'}
165         ],
166         ProvisionedThroughput={
167             'ReadCapacityUnits': 5,
168             'WriteCapacityUnits': 5
169         }
170     )
171
172     # Wait until the table exists
173     table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
174
175     # Mark the hunt as active in the database
176     item['active'] = True
177     hunts_table.put_item(Item=item)
178
179     # Message the hunt channel that the database is ready
180     turb.slack_client.chat_postMessage(
181         channel=channel_id,
182         text="Thank you for waiting. This hunt is now ready to begin! "
183         + "Use `/puzzle` to create puzzles for the hunt.")
184
185     return lambda_success
186
187 def set_channel_description(turb, puzzle):
188     channel_id = puzzle['channel_id']
189     description = puzzle['name']
190     url = puzzle.get('url', None)
191     sheet_url = puzzle.get('sheet_url', None)
192
193     links = []
194     if url:
195         links.append("<{}|Puzzle>".format(url))
196     if sheet_url:
197         links.append("<{}|Sheet>".format(sheet_url))
198
199     if len(links):
200         description += "({})".format(', '.join(links))
201
202     turb.slack_client.conversations_setPurpose(channel=channel_id,
203                                                purpose=description)
204     turb.slack_client.conversations_setTopic(channel=channel_id,
205                                              topic=description)
206
207 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
208     """Creates sheet and invites user for a newly-created puzzle channel"""
209
210     hunt_id = puzzle_channel_name.split('-')[0]
211
212     # First see if we can find an entry for this puzzle in the database.
213     # If not, simply return an error and let Slack retry
214     puzzle_table = turb.db.Table(hunt_id)
215     response = puzzle_table.get_item(
216         Key={'channel_id': puzzle_channel_id},
217         ConsistentRead=True
218     )
219     if 'Item' not in response:
220         print("Warning: Cannot find channel_id {} in {} table. "
221               .format(puzzle_channel_id, hunt_id)
222               + "Letting Slack retry this event")
223         return lambda_error
224
225     item = response['Item']
226
227     if 'sheet_url' in item:
228         print("Info: channel_id {} already has sheet_url {}. Exiting."
229               .format(puzzle_channel_id, item['sheet_url']))
230         return lambda_success
231
232     # Remove any None items from our item before updating
233     if not item['url']:
234         del item['url']
235
236     # Get the puzzle's name into the channel description
237     set_channel_description(turb, item)
238
239     # Before launching into sheet creation, indicate that we're doing this
240     # in the database. This way, if we take too long to create the sheet
241     # and Slack retries the event, that next event will see this 'pending'
242     # string and cleanly return (eliminating all future retries).
243     item['sheet_url'] = 'pending'
244     puzzle_table.put_item(Item=item)
245
246     # Create a sheet for the puzzle
247     sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
248
249     # Update the database with the URL of the sheet
250     item['sheet_url'] = sheet['url']
251     puzzle_table.put_item(Item=item)
252
253     # Message the channel with the URL of the puzzle's sheet
254     turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
255                                        text="Sheet created for this puzzle: {}"
256                                        .format(sheet['url']))
257
258     # Get the new sheet_url into the channel description
259     set_channel_description(turb, item)
260
261     hunts_table = turb.db.Table('hunts')
262     response = hunts_table.scan(
263         FilterExpression='hunt_id = :hunt_id',
264         ExpressionAttributeValues={':hunt_id': hunt_id}
265     )
266
267     if 'Items' in response:
268
269         hunt_channel_id = response['Items'][0]['channel_id']
270
271         # Find all members of the hunt channel
272         members = turbot.slack.slack_channel_members(turb.slack_client,
273                                                      hunt_channel_id)
274
275         # Filter out Turbot's own ID to avoid inviting itself
276         members = [m for m in members if m != TURBOT_USER_ID]
277
278         turb.slack_client.chat_postMessage(
279             channel=puzzle_channel_id,
280             text="Inviting all members from the hunt channel:  {}"
281             .format(hunt_id))
282
283         # Invite those members to the puzzle channel (in chunks of 500)
284         cursor = 0
285         while cursor < len(members):
286             turb.slack_client.conversations_invite(
287                 channel=puzzle_channel_id,
288                 users=members[cursor:cursor + 500])
289             cursor += 500
290
291     return lambda_success
292
293 def channel_created(turb, event):
294     print("In channel_created with event: {}".format(str(event)))
295
296     channel = event['channel']
297     channel_id = channel['id']
298     channel_name = channel['name']
299     creator = channel['creator']
300
301     # Ignore any channels that turbot didn't create
302     if creator != TURBOT_USER_ID:
303         print("channel_created: Not a turbot-created channel. Exiting.")
304         return lambda_success
305
306     # The presence of a hyphen determines whether this is a puzzle
307     # channel or a hunt channel.
308     if '-' in channel_name:
309         return puzzle_channel_created(turb, channel_name, channel_id)
310     else:
311         return hunt_channel_created(turb, channel_name, channel_id)
312
313 events['channel_created'] = channel_created