]> git.cworth.org Git - turbot/blob - turbot/events.py
25c83233865fee9063d91dc205e23f8fc761440a
[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.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.append(hunt_link_block(turb, hunt))
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.append([
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 moment or two while I create some backend resources.")
127
128     # Create a new folder within Google drive for the hunt in two parts:
129
130     # ... first, a top-level folder named for the hunt
131     hunt_folder = sheets_create_folder(turb, hunt['hunt_id'])
132
133     # ... second, a folder within that named "turbot"
134     #
135     # The concept here is that non-turbot related content could
136     # be placed adjacent to the turbot folder.
137     hunt['folder_id'] = sheets_create_folder(turb, "turbot",
138                                              parents = [hunt_folder])
139
140     # Create a sheet for the hunt
141     sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
142     hunt['sheet_url'] = sheet['url']
143
144     # Message the channel with the URL of the sheet
145     slack_send_message(turb.slack_client, channel_id,
146                        "Sheet created for this hunt: {}".format(sheet['url']))
147
148     # Mark the hunt as active now
149     hunt['active'] = True
150
151     # Update the database with all the changes we have made to the hunt
152     turb.table.put_item(Item=hunt)
153
154     # Message the hunt channel that the database is ready
155     slack_send_message(
156         turb.slack_client, channel_id,
157         "Thank you for waiting. This hunt is now ready to begin! "
158         + "Type `/new` to create a puzzle for the hunt and `/help` for help.")
159
160     return lambda_success
161
162 def set_channel_description(turb, puzzle):
163     channel_id = puzzle['channel_id']
164     description = puzzle['name']
165     url = puzzle.get('url', None)
166     sheet_url = puzzle.get('sheet_url', None)
167
168     links = []
169     if url:
170         links.append("<{}|Puzzle>".format(url))
171     if sheet_url:
172         links.append("<{}|Sheet>".format(sheet_url))
173
174     if len(links):
175         description += "({})".format(', '.join(links))
176
177     turb.slack_client.conversations_setPurpose(channel=channel_id,
178                                                purpose=description)
179     turb.slack_client.conversations_setTopic(channel=channel_id,
180                                              topic=description)
181
182 def puzzle_channel_created(turb, channel_name, channel_id):
183     """Creates sheet and invites user for a newly-created puzzle channel"""
184
185     # First see if we can find an entry for this puzzle in the database.
186     # If not, simply return an error and let Slack retry
187     response = turb.table.query(
188         IndexName="channel_id_index",
189         KeyConditionExpression=Key("channel_id").eq(channel_id),
190     )
191     if 'Items' not in response:
192         print("Warning: Cannot find channel_id {} in turbot table. "
193               .format(channel_id) + "Letting Slack retry this event")
194         return lambda_error
195
196     puzzle = response['Items'][0]
197
198     if 'sheet_url' in puzzle:
199         print("Info: channel_id {} already has sheet_url {}. Exiting."
200               .format(channel_id, puzzle['sheet_url']))
201         return lambda_success
202
203     # We need hunt from the database to know which folder to create
204     # the sheet in.
205     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
206
207     # Before launching into sheet creation, indicate that we're doing this
208     # in the database. This way, if we take too long to create the sheet
209     # and Slack retries the event, that next event will see this 'pending'
210     # string and cleanly return (eliminating all future retries).
211     puzzle['sheet_url'] = 'pending'
212     puzzle['channel_url'] = channel_url(channel_id)
213     turb.table.put_item(Item=puzzle)
214
215     # Create a sheet for the puzzle
216     sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
217
218     # Update the database with the URL of the sheet
219     puzzle['sheet_url'] = sheet['url']
220     turb.table.put_item(Item=puzzle)
221
222     # Get the new sheet_url into the channel description
223     set_channel_description(turb, puzzle)
224
225     # And finally, give a welcome message with some documentation
226     # on how to update the state of the puzzle in the database.
227     welcome_msg = (
228         "Welcome! This channel is the primary place to "
229         + "discuss things as the team works together to solve the "
230         + "puzzle \"{}\". ".format(puzzle['name'])
231     )
232
233     if 'url' in puzzle:
234         welcome_msg += (
235             "See the <{}|puzzle itself> ".format(puzzle['url'])
236             + "for what was originally presented to us. "
237         )
238
239     welcome_msg += (
240         "Actual puzzle solving work will take place within the following " +
241         "<{}|shared spreadsheet> ".format(puzzle['sheet_url']) +
242         "\n\n"
243         "Common commands for updating the puzzle are `/state NEW STATE`, " +
244         "`/tag NEW_TAG`, and `/solved SOLUTION` . See `/help` for details " +
245         "and for additional commands."
246     )
247
248     turb.slack_client.chat_postMessage(channel=channel_id, text=welcome_msg)
249
250     # Finally, finally, notify the hunt channel about the new puzzle
251     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
252     slack_send_message(
253         turb.slack_client, hunt['channel_id'],
254         "New puzzle available: <{}|{}>".format(
255             puzzle['channel_url'],
256             puzzle['name'])
257     )
258
259     return lambda_success
260
261 def channel_created(turb, event):
262
263     channel = event['channel']
264     channel_id = channel['id']
265     channel_name = channel['name']
266     creator = channel['creator']
267
268     # Ignore any channels that turbot didn't create
269     if creator != TURBOT_USER_ID:
270         print("channel_created: Not a turbot-created channel. Exiting.")
271         return lambda_success
272
273     # The presence of a hyphen determines whether this is a puzzle
274     # channel or a hunt channel.
275     if '-' in channel_name:
276         return puzzle_channel_created(turb, channel_name, channel_id)
277     else:
278         return hunt_channel_created(turb, channel_name, channel_id)
279
280 events['channel_created'] = channel_created