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