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