]> git.cworth.org Git - turbot/blob - turbot/events.py
Add some debugging of the turbot home app
[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         print("Generating turbot home view for hunt '" + hunt['hunt_id'] + "'")
47         if not hunt['active']:
48             print("Never mind, that hunt is not active.")
49             continue
50         print("Hunt '" + hunt['hunt_id'] + "' is active, moving forward.")
51         if user_id in slack_channel_members(turb.slack_client,
52                                             hunt['channel_id']):
53             my_hunt_blocks.append(hunt_link_block(turb, hunt))
54         else:
55             available_hunt_blocks.append(hunt_link_block(turb, hunt))
56
57     if len(my_hunt_blocks):
58         my_hunt_blocks = [
59             section_block(text_block("*Hunts you belong to:*")),
60             divider_block(),
61             * my_hunt_blocks
62         ]
63     else:
64         my_hunt_blocks.append([
65             section_block(text_block("You do not belong to any hunts"))
66         ])
67
68     if len(available_hunt_blocks):
69         available_hunt_blocks = [
70             section_block(text_block("*Hunts you can join:*")),
71             divider_block(),
72             * available_hunt_blocks
73         ]
74
75     return {
76         "type": "home",
77         "blocks": [
78             * my_hunt_blocks,
79             * available_hunt_blocks,
80             actions_block(button_block("New hunt", "new_hunt"))
81         ]
82     }
83
84 def app_home_opened(turb, event):
85     """Handler for the app_home_opened event
86
87     This event occurs when a user visits the home tab for the turbot app.
88     In response to this event we need to publish a view for the user."""
89
90     user_id = event['user']
91     view = home(turb, user_id)
92     turb.slack_client.views_publish(user_id=user_id, view=view)
93     return lambda_success
94
95 events['app_home_opened'] = app_home_opened
96
97 def hunt_channel_created(turb, channel_name, channel_id):
98     """Creates a Google sheet for a newly-created hunt channel"""
99
100     # First see if we can find an entry for this hunt in the database.
101     # If not, simply return an error and let Slack retry
102     response = turb.table.query(
103         IndexName='channel_id_index',
104         KeyConditionExpression=Key("channel_id").eq(channel_id)
105     )
106     if 'Items' not in response:
107         print("Warning: Cannot find channel_id {} in turbot table. "
108               .format(channel_id) + "Letting Slack retry this event")
109         return lambda_error
110
111     hunt = response['Items'][0]
112
113     if 'sheet_url' in hunt:
114         print("Info: channel_id {} already has sheet_url {}. Exiting."
115               .format(channel_id, hunt['sheet_url']))
116         return lambda_success
117
118     # Before launching into sheet creation, indicate that we're doing this
119     # in the database. This way, if we take too long to create the sheet
120     # and Slack retries the event, that next event will see this 'pending'
121     # string and cleanly return (eliminating all future retries).
122     hunt['sheet_url'] = 'pending'
123     turb.table.put_item(Item=hunt)
124
125     # Also, let the channel users know what we are up to
126     slack_send_message(
127         turb.slack_client, channel_id,
128         "Welcome to the channel for the {} hunt! ".format(hunt['name'])
129         + "Please wait a moment or two while I create some backend resources.")
130
131     # Create a new folder within Google drive for the hunt
132     hunt['folder_id'] = sheets_create_folder(turb, hunt['hunt_id'])
133
134     # Create a sheet for the hunt
135     sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
136     hunt['sheet_url'] = sheet['url']
137
138     # Message the channel with the URL of the sheet
139     slack_send_message(turb.slack_client, channel_id,
140                        "Sheet created for this hunt: {}".format(sheet['url']))
141
142     # Mark the hunt as active now
143     hunt['active'] = True
144
145     # Update the database with all the changes we have made to the hunt
146     turb.table.put_item(Item=hunt)
147
148     # Message the hunt channel that the database is ready
149     slack_send_message(
150         turb.slack_client, channel_id,
151         "Thank you for waiting. This hunt is now ready to begin! "
152         + "Type `/new` to create a puzzle for the hunt and `/help` for help.")
153
154     return lambda_success
155
156 def set_channel_description(turb, puzzle):
157     channel_id = puzzle['channel_id']
158     description = puzzle['name']
159     url = puzzle.get('url', None)
160     sheet_url = puzzle.get('sheet_url', None)
161
162     links = []
163     if url:
164         links.append("<{}|Puzzle>".format(url))
165     if sheet_url:
166         links.append("<{}|Sheet>".format(sheet_url))
167
168     if len(links):
169         description += "({})".format(', '.join(links))
170
171     turb.slack_client.conversations_setPurpose(channel=channel_id,
172                                                purpose=description)
173     turb.slack_client.conversations_setTopic(channel=channel_id,
174                                              topic=description)
175
176 def puzzle_channel_created(turb, channel_name, channel_id):
177     """Creates sheet and invites user for a newly-created puzzle channel"""
178
179     # First see if we can find an entry for this puzzle in the database.
180     # If not, simply return an error and let Slack retry
181     response = turb.table.query(
182         IndexName="channel_id_index",
183         KeyConditionExpression=Key("channel_id").eq(channel_id),
184     )
185     if 'Items' not in response:
186         print("Warning: Cannot find channel_id {} in turbot table. "
187               .format(channel_id) + "Letting Slack retry this event")
188         return lambda_error
189
190     puzzle = response['Items'][0]
191
192     if 'sheet_url' in puzzle:
193         print("Info: channel_id {} already has sheet_url {}. Exiting."
194               .format(channel_id, puzzle['sheet_url']))
195         return lambda_success
196
197     # We need hunt from the database to know which folder to create
198     # the sheet in.
199     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
200
201     # Before launching into sheet creation, indicate that we're doing this
202     # in the database. This way, if we take too long to create the sheet
203     # and Slack retries the event, that next event will see this 'pending'
204     # string and cleanly return (eliminating all future retries).
205     puzzle['sheet_url'] = 'pending'
206     puzzle['channel_url'] = channel_url(channel_id)
207     turb.table.put_item(Item=puzzle)
208
209     # Create a sheet for the puzzle
210     sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
211
212     # Update the database with the URL of the sheet
213     puzzle['sheet_url'] = sheet['url']
214     turb.table.put_item(Item=puzzle)
215
216     # Get the new sheet_url into the channel description
217     set_channel_description(turb, puzzle)
218
219     # And finally, give a welcome message with some documentation
220     # on how to update the state of the puzzle in the database.
221     welcome_msg = (
222         "Welcome! This channel is the primary place to "
223         + "discuss things as the team works together to solve the "
224         + "puzzle \"{}\". ".format(puzzle['name'])
225     )
226
227     if 'url' in puzzle:
228         welcome_msg += (
229             "See the <{}|puzzle itself> ".format(puzzle['url'])
230             + "for what was originally presented to us. "
231         )
232
233     welcome_msg += (
234         "Actual puzzle solving work will take place within the following " +
235         "<{}|shared spreadsheet> ".format(puzzle['sheet_url']) +
236         "\n\n"
237         "Common commands for updating the puzzle are `/state NEW STATE`, " +
238         "`/tag NEW_TAG`, and `/solved SOLUTION` . See `/help` for details " +
239         "and for additional commands."
240     )
241
242     turb.slack_client.chat_postMessage(channel=channel_id, text=welcome_msg)
243
244     # Finally, finally, notify the hunt channel about the new puzzle
245     hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
246     slack_send_message(
247         turb.slack_client, hunt['channel_id'],
248         "New puzzle available: <{}|{}>".format(
249             puzzle['channel_url'],
250             puzzle['name'])
251     )
252
253     return lambda_success
254
255 def channel_created(turb, event):
256
257     channel = event['channel']
258     channel_id = channel['id']
259     channel_name = channel['name']
260     creator = channel['creator']
261
262     # Ignore any channels that turbot didn't create
263     if creator != TURBOT_USER_ID:
264         print("channel_created: Not a turbot-created channel. Exiting.")
265         return lambda_success
266
267     # The presence of a hyphen determines whether this is a puzzle
268     # channel or a hunt channel.
269     if '-' in channel_name:
270         return puzzle_channel_created(turb, channel_name, channel_id)
271     else:
272         return hunt_channel_created(turb, channel_name, channel_id)
273
274 events['channel_created'] = channel_created