]> git.cworth.org Git - turbot/blob - turbot/events.py
Make the puzzle's name a link to the sheet
[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 puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
188     """Creates sheet and invites user for a newly-created puzzle channel"""
189
190     hunt_id = puzzle_channel_name.split('-')[0]
191
192     # First see if we can find an entry for this puzzle in the database.
193     # If not, simply return an error and let Slack retry
194     puzzle_table = turb.db.Table(hunt_id)
195     response = puzzle_table.get_item(
196         Key={'channel_id': puzzle_channel_id},
197         ConsistentRead=True
198     )
199     if 'Item' not in response:
200         print("Warning: Cannot find channel_id {} in {} table. "
201               .format(puzzle_channel_id, hunt_id)
202               + "Letting Slack retry this event")
203         return lambda_error
204
205     item = response['Item']
206
207     if 'sheet_url' in item:
208         print("Info: channel_id {} already has sheet_url {}. Exiting."
209               .format(puzzle_channel_id, item['sheet_url']))
210         return lambda_success
211
212     # Remove any None items from our item before updating
213     if not item['url']:
214         del item['url']
215
216     # Before launching into sheet creation, indicate that we're doing this
217     # in the database. This way, if we take too long to create the sheet
218     # and Slack retries the event, that next event will see this 'pending'
219     # string and cleanly return (eliminating all future retries).
220     item['sheet_url'] = 'pending'
221     puzzle_table.put_item(Item=item)
222
223     # Create a sheet for the puzzle
224     sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
225
226     # Update the database with the URL of the sheet
227     item['sheet_url'] = sheet['url']
228     puzzle_table.put_item(Item=item)
229
230     # Message the channel with the URL of the puzzle's sheet
231     turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
232                                        text="Sheet created for this puzzle: {}"
233                                        .format(sheet['url']))
234
235     hunts_table = turb.db.Table('hunts')
236     response = hunts_table.scan(
237         FilterExpression='hunt_id = :hunt_id',
238         ExpressionAttributeValues={':hunt_id': hunt_id}
239     )
240
241     if 'Items' in response:
242
243         hunt_channel_id = response['Items'][0]['channel_id']
244
245         # Find all members of the hunt channel
246         members = turbot.slack.slack_channel_members(turb.slack_client,
247                                                      hunt_channel_id)
248
249         # Filter out Turbot's own ID to avoid inviting itself
250         members = [m for m in members if m != TURBOT_USER_ID]
251
252         turb.slack_client.chat_postMessage(
253             channel=puzzle_channel_id,
254             text="Inviting all members from the hunt channel:  {}"
255             .format(hunt_id))
256
257         # Invite those members to the puzzle channel (in chunks of 500)
258         cursor = 0
259         while cursor < len(members):
260             turb.slack_client.conversations_invite(
261                 channel=puzzle_channel_id,
262                 users=members[cursor:cursor + 500])
263             cursor += 500
264
265     return lambda_success
266
267 def channel_created(turb, event):
268     print("In channel_created with event: {}".format(str(event)))
269
270     channel = event['channel']
271     channel_id = channel['id']
272     channel_name = channel['name']
273     creator = channel['creator']
274
275     # Ignore any channels that turbot didn't create
276     if creator != TURBOT_USER_ID:
277         print("channel_created: Not a turbot-created channel. Exiting.")
278         return lambda_success
279
280     # The presence of a hyphen determines whether this is a puzzle
281     # channel or a hunt channel.
282     if '-' in channel_name:
283         return puzzle_channel_created(turb, channel_name, channel_id)
284     else:
285         return hunt_channel_created(turb, channel_name, channel_id)
286
287 events['channel_created'] = channel_created