]> git.cworth.org Git - turbot/blob - turbot/events.py
Use the Google drive API to create a hunt's sheet within a folder
[turbot] / turbot / events.py
1 from turbot.blocks import (
2     section_block, text_block, button_block, actions_block, divider_block
3 )
4 from turbot.hunt import hunt_blocks, find_hunt_for_hunt_id
5 from turbot.sheets import (
6     sheets_create, sheets_create_for_puzzle, sheets_create_folder
7 )
8 from turbot.slack import slack_send_message, slack_channel_members
9 from turbot.channel import channel_url
10 from boto3.dynamodb.conditions import Key
11
12 TURBOT_USER_ID = 'U01B9QM4P9R'
13
14 events = {}
15
16 lambda_success = {'statusCode': 200}
17 lambda_error = {'statusCode': 400}
18
19 def hunt_link_block(turb, hunt):
20
21     name = hunt['name']
22     channel_id = hunt['channel_id']
23
24     hunt_link = "*<{}|{}>*".format(channel_url(channel_id), name)
25
26     return section_block(text_block(hunt_link))
27
28 def home(turb, user_id):
29     """Returns a view to be published as the turbot home tab for user_id
30
31     The return value is a dictionary suitable to be published to the
32     Slack views_publish API."""
33
34     # Behave cleanly if there is no "turbot" table at all yet.
35     try:
36         response = turb.table.scan(
37             IndexName="is_hunt_index",
38         )
39         hunts = response['Items']
40     except Exception:
41         hunts = []
42
43     my_hunt_blocks = []
44     available_hunt_blocks = []
45     for hunt in hunts:
46         if not hunt['active']:
47             continue
48         if user_id in slack_channel_members(turb.slack_client,
49                                             hunt['channel_id']):
50             my_hunt_blocks += hunt_blocks(turb, hunt, puzzle_status='all')
51         else:
52             available_hunt_blocks.append(hunt_link_block(turb, hunt))
53
54     if len(my_hunt_blocks):
55         my_hunt_blocks = [
56             section_block(text_block("*Hunts you belong to:*")),
57             divider_block(),
58             * my_hunt_blocks
59         ]
60     else:
61         my_hunt_blocks = [
62             section_block(text_block("You do not belong to any hunts"))
63         ]
64
65     if len(available_hunt_blocks):
66         available_hunt_blocks = [
67             section_block(text_block("*Hunts you can join:*")),
68             divider_block(),
69             * available_hunt_blocks
70         ]
71
72     return {
73         "type": "home",
74         "blocks": [
75             * my_hunt_blocks,
76             * available_hunt_blocks,
77             actions_block(button_block("New hunt", "new_hunt"))
78         ]
79     }
80
81 def app_home_opened(turb, event):
82     """Handler for the app_home_opened event
83
84     This event occurs when a user visits the home tab for the turbot app.
85     In response to this event we need to publish a view for the user."""
86
87     user_id = event['user']
88     view = home(turb, user_id)
89     turb.slack_client.views_publish(user_id=user_id, view=view)
90     return lambda_success
91
92 events['app_home_opened'] = app_home_opened
93
94 def hunt_channel_created(turb, channel_name, channel_id):
95     """Creates a Google sheet for a newly-created hunt channel"""
96
97     # First see if we can find an entry for this hunt in the database.
98     # If not, simply return an error and let Slack retry
99     response = turb.table.query(
100         IndexName='channel_id_index',
101         KeyConditionExpression=Key("channel_id").eq(channel_id)
102     )
103     if 'Items' not in response:
104         print("Warning: Cannot find channel_id {} in turbot table. "
105               .format(channel_id) + "Letting Slack retry this event")
106         return lambda_error
107
108     hunt = response['Items'][0]
109
110     if 'sheet_url' in hunt:
111         print("Info: channel_id {} already has sheet_url {}. Exiting."
112               .format(channel_id, hunt['sheet_url']))
113         return lambda_success
114
115     # Before launching into sheet creation, indicate that we're doing this
116     # in the database. This way, if we take too long to create the sheet
117     # and Slack retries the event, that next event will see this 'pending'
118     # string and cleanly return (eliminating all future retries).
119     hunt['sheet_url'] = 'pending'
120     turb.table.put_item(Item=hunt)
121
122     # Also, let the channel users know what we are up to
123     slack_send_message(
124         turb.slack_client, channel_id,
125         "Welcome to the channel for the {} hunt! ".format(hunt['name'])
126         + "Please wait a minute or two while I create some backend resources.")
127
128     # Create a new folder within Google drive for the hunt
129     hunt['folder_id'] = sheets_create_folder(turb, hunt['hunt_id'])
130
131     # Create a sheet for the hunt
132     sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
133     hunt['sheet_url'] = sheet['url']
134
135     # Message the channel with the URL of the sheet
136     slack_send_message(turb.slack_client, channel_id,
137                        "Sheet created for this hunt: {}".format(sheet['url']))
138
139     # Mark the hunt as active now
140     hunt['active'] = True
141
142     # Update the database with all the changes we have made to the hunt
143     turb.table.put_item(Item=hunt)
144
145     # Message the hunt channel that the database is ready
146     slack_send_message(
147         turb.slack_client, channel_id,
148         "Thank you for waiting. This hunt is now ready to begin! "
149         + "Use `/puzzle` to create puzzles for the hunt.")
150
151     return lambda_success
152
153 def set_channel_description(turb, puzzle):
154     channel_id = puzzle['channel_id']
155     description = puzzle['name']
156     url = puzzle.get('url', None)
157     sheet_url = puzzle.get('sheet_url', None)
158
159     links = []
160     if url:
161         links.append("<{}|Puzzle>".format(url))
162     if sheet_url:
163         links.append("<{}|Sheet>".format(sheet_url))
164
165     if len(links):
166         description += "({})".format(', '.join(links))
167
168     turb.slack_client.conversations_setPurpose(channel=channel_id,
169                                                purpose=description)
170     turb.slack_client.conversations_setTopic(channel=channel_id,
171                                              topic=description)
172
173 def puzzle_channel_created(turb, channel_name, channel_id):
174     """Creates sheet and invites user for a newly-created puzzle channel"""
175
176     # First see if we can find an entry for this puzzle in the database.
177     # If not, simply return an error and let Slack retry
178     response = turb.table.query(
179         IndexName="channel_id_index",
180         KeyConditionExpression=Key("channel_id").eq(channel_id),
181     )
182     if 'Items' not in response:
183         print("Warning: Cannot find channel_id {} in turbot table. "
184               .format(channel_id) + "Letting Slack retry this event")
185         return lambda_error
186
187     puzzle = response['Items'][0]
188
189     if 'sheet_url' in puzzle:
190         print("Info: channel_id {} already has sheet_url {}. Exiting."
191               .format(channel_id, puzzle['sheet_url']))
192         return lambda_success
193
194     # Before launching into sheet creation, indicate that we're doing this
195     # in the database. This way, if we take too long to create the sheet
196     # and Slack retries the event, that next event will see this 'pending'
197     # string and cleanly return (eliminating all future retries).
198     puzzle['sheet_url'] = 'pending'
199     puzzle['channel_url'] = channel_url(channel_id)
200     turb.table.put_item(Item=puzzle)
201
202     # Create a sheet for the puzzle
203     sheet = sheets_create_for_puzzle(turb, puzzle)
204
205     # Update the database with the URL of the sheet
206     puzzle['sheet_url'] = sheet['url']
207     turb.table.put_item(Item=puzzle)
208
209     # Get the new sheet_url into the channel description
210     set_channel_description(turb, puzzle)
211
212     # And finally, give a welcome message with some documentation
213     # on how to update the state of the puzzle in the database.
214     welcome_msg = (
215         "Welcome! This channel is the primary place to "
216         + "discuss things as the team works together to solve the "
217         + "puzzle '{}'. ".format(puzzle['name'])
218     )
219
220     if 'url' in puzzle:
221         welcome_msg += (
222             "See the <{}|puzzle itself> ".format(puzzle['url'])
223             + "for what was originally presented to us."
224         )
225
226     sheet_msg = (
227         "Actual puzzle solving work will take place within the following "
228         + "<{}|shared spreadsheet> ".format(puzzle['sheet_url'])
229     )
230
231     state_msg = (
232         "Whenever the status of the puzzle progress changes "
233         + "significantly, please type `/state` with a brief message "
234         + "explaining where things stand. This could be something "
235         + "like `/state Grid is filled. Need insight for extraction.` "
236         + "or `/state Nathan has printed this and is cutting/assembling`. "
237         + "It's especially important to put information in `/state` "
238         + "when you step away from a puzzle so the next team members "
239         + "to arrive will know what is going on."
240     )
241
242     solved_msg = (
243         "When a puzzle has been solved, submitted, and the solution is "
244         + "confirmed, please type `/solved THE PUZZLE ANSWER HERE`. All "
245         + "information given in `/state` and `/solved` will be presented "
246         + "in this channel's topic as well as in the hunt overview "
247         + "(which is available by selecting \"Turbot\" from the Slack "
248         + "list of members)."
249     )
250
251     turb.slack_client.chat_postMessage(
252         channel=channel_id,
253         text="New puzzle: {}".format(['name']),
254         blocks=[
255             section_block(text_block(welcome_msg)),
256             section_block(text_block(sheet_msg)),
257             section_block(text_block(state_msg)),
258             section_block(text_block(solved_msg))
259         ])
260
261     # Finally, finally, notify the hunt channel about the new puzzle
262     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
263     slack_send_message(
264         turb.slack_client, hunt['channel_id'],
265         "New puzzle available: <{}|{}>".format(
266             puzzle['channel_url'],
267             puzzle['name'])
268     )
269
270     return lambda_success
271
272 def channel_created(turb, event):
273
274     channel = event['channel']
275     channel_id = channel['id']
276     channel_name = channel['name']
277     creator = channel['creator']
278
279     # Ignore any channels that turbot didn't create
280     if creator != TURBOT_USER_ID:
281         print("channel_created: Not a turbot-created channel. Exiting.")
282         return lambda_success
283
284     # The presence of a hyphen determines whether this is a puzzle
285     # channel or a hunt channel.
286     if '-' in channel_name:
287         return puzzle_channel_created(turb, channel_name, channel_id)
288     else:
289         return hunt_channel_created(turb, channel_name, channel_id)
290
291 events['channel_created'] = channel_created