]> git.cworth.org Git - turbot/blob - turbot/events.py
508e8d95da15caa666cac268bb25efc14660945d
[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 moment 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         + "Type `/new` to create a puzzle for the hunt and `/help` for help.")
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     # We need hunt from the database to know which folder to create
195     # the sheet in.
196     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
197
198     # Before launching into sheet creation, indicate that we're doing this
199     # in the database. This way, if we take too long to create the sheet
200     # and Slack retries the event, that next event will see this 'pending'
201     # string and cleanly return (eliminating all future retries).
202     puzzle['sheet_url'] = 'pending'
203     puzzle['channel_url'] = channel_url(channel_id)
204     turb.table.put_item(Item=puzzle)
205
206     # Create a sheet for the puzzle
207     sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
208
209     # Update the database with the URL of the sheet
210     puzzle['sheet_url'] = sheet['url']
211     turb.table.put_item(Item=puzzle)
212
213     # Get the new sheet_url into the channel description
214     set_channel_description(turb, puzzle)
215
216     # And finally, give a welcome message with some documentation
217     # on how to update the state of the puzzle in the database.
218     welcome_msg = (
219         "Welcome! This channel is the primary place to "
220         + "discuss things as the team works together to solve the "
221         + "puzzle \"{}\". ".format(puzzle['name'])
222     )
223
224     if 'url' in puzzle:
225         welcome_msg += (
226             "See the <{}|puzzle itself> ".format(puzzle['url'])
227             + "for what was originally presented to us. "
228         )
229
230     welcome_msg += (
231         "Actual puzzle solving work will take place within the following " +
232         "<{}|shared spreadsheet> ".format(puzzle['sheet_url']) +
233         "\n\n"
234         "Common commands for updating the puzzle are `/state NEW STATE`, " +
235         "`/tag NEW_TAG`, and `/solved SOLUTION` . See `/help` for details " +
236         "and for additional commands."
237     )
238
239     turb.slack_client.chat_postMessage(channel=channel_id, text=welcome_msg)
240
241     # Finally, finally, notify the hunt channel about the new puzzle
242     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
243     slack_send_message(
244         turb.slack_client, hunt['channel_id'],
245         "New puzzle available: <{}|{}>".format(
246             puzzle['channel_url'],
247             puzzle['name'])
248     )
249
250     return lambda_success
251
252 def channel_created(turb, event):
253
254     channel = event['channel']
255     channel_id = channel['id']
256     channel_name = channel['name']
257     creator = channel['creator']
258
259     # Ignore any channels that turbot didn't create
260     if creator != TURBOT_USER_ID:
261         print("channel_created: Not a turbot-created channel. Exiting.")
262         return lambda_success
263
264     # The presence of a hyphen determines whether this is a puzzle
265     # channel or a hunt channel.
266     if '-' in channel_name:
267         return puzzle_channel_created(turb, channel_name, channel_id)
268     else:
269         return hunt_channel_created(turb, channel_name, channel_id)
270
271 events['channel_created'] = channel_created