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