1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
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
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
12 TURBOT_USER_ID = 'U01B9QM4P9R'
16 lambda_success = {'statusCode': 200}
17 lambda_error = {'statusCode': 400}
19 def hunt_link_block(turb, hunt):
22 channel_id = hunt['channel_id']
24 hunt_link = "*<{}|{}>*".format(channel_url(channel_id), name)
26 return section_block(text_block(hunt_link))
28 def home(turb, user_id):
29 """Returns a view to be published as the turbot home tab for user_id
31 The return value is a dictionary suitable to be published to the
32 Slack views_publish API."""
34 # Behave cleanly if there is no "turbot" table at all yet.
36 response = turb.table.scan(
37 IndexName="is_hunt_index",
39 hunts = response['Items']
44 available_hunt_blocks = []
46 if not hunt['active']:
48 if user_id in slack_channel_members(turb.slack_client,
50 my_hunt_blocks += hunt_blocks(turb, hunt, puzzle_status='all')
52 available_hunt_blocks.append(hunt_link_block(turb, hunt))
54 if len(my_hunt_blocks):
56 section_block(text_block("*Hunts you belong to:*")),
62 section_block(text_block("You do not belong to any hunts"))
65 if len(available_hunt_blocks):
66 available_hunt_blocks = [
67 section_block(text_block("*Hunts you can join:*")),
69 * available_hunt_blocks
76 * available_hunt_blocks,
77 actions_block(button_block("New hunt", "new_hunt"))
81 def app_home_opened(turb, event):
82 """Handler for the app_home_opened event
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."""
87 user_id = event['user']
88 view = home(turb, user_id)
89 turb.slack_client.views_publish(user_id=user_id, view=view)
92 events['app_home_opened'] = app_home_opened
94 def hunt_channel_created(turb, channel_name, channel_id):
95 """Creates a Google sheet for a newly-created hunt channel"""
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)
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")
108 hunt = response['Items'][0]
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
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)
122 # Also, let the channel users know what we are up to
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.")
128 # Create a new folder within Google drive for the hunt
129 hunt['folder_id'] = sheets_create_folder(turb, hunt['hunt_id'])
131 # Create a sheet for the hunt
132 sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
133 hunt['sheet_url'] = sheet['url']
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']))
139 # Mark the hunt as active now
140 hunt['active'] = True
142 # Update the database with all the changes we have made to the hunt
143 turb.table.put_item(Item=hunt)
145 # Message the hunt channel that the database is ready
147 turb.slack_client, channel_id,
148 "Thank you for waiting. This hunt is now ready to begin! "
149 + "Type `/puzzle new` to create puzzles for the hunt.")
151 return lambda_success
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)
161 links.append("<{}|Puzzle>".format(url))
163 links.append("<{}|Sheet>".format(sheet_url))
166 description += "({})".format(', '.join(links))
168 turb.slack_client.conversations_setPurpose(channel=channel_id,
170 turb.slack_client.conversations_setTopic(channel=channel_id,
173 def puzzle_channel_created(turb, channel_name, channel_id):
174 """Creates sheet and invites user for a newly-created puzzle channel"""
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),
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")
187 puzzle = response['Items'][0]
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
194 # We need hunt from the database to know which folder to create
196 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
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)
206 # Create a sheet for the puzzle
207 sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
209 # Update the database with the URL of the sheet
210 puzzle['sheet_url'] = sheet['url']
211 turb.table.put_item(Item=puzzle)
213 # Get the new sheet_url into the channel description
214 set_channel_description(turb, puzzle)
216 # And finally, give a welcome message with some documentation
217 # on how to update the state of the puzzle in the database.
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'])
226 "See the <{}|puzzle itself> ".format(puzzle['url'])
227 + "for what was originally presented to us."
231 "Actual puzzle solving work will take place within the following "
232 + "<{}|shared spreadsheet> ".format(puzzle['sheet_url'])
236 "Whenever the status of the puzzle progress changes "
237 + "significantly, please type `/state` with a brief message "
238 + "explaining where things stand. This could be something "
239 + "like `/state Grid is filled. Need insight for extraction.` "
240 + "or `/state Nathan has printed this and is cutting/assembling`. "
241 + "It's especially important to put information in `/state` "
242 + "when you step away from a puzzle so the next team members "
243 + "to arrive will know what is going on."
247 "When a puzzle has been solved, submitted, and the solution is "
248 + "confirmed, please type `/solved THE PUZZLE ANSWER HERE`. All "
249 + "information given in `/state` and `/solved` will be presented "
250 + "in this channel's topic as well as in the hunt overview "
251 + "(which is available by selecting \"Turbot\" from the Slack "
252 + "list of members)."
255 turb.slack_client.chat_postMessage(
257 text="New puzzle: {}".format(['name']),
259 section_block(text_block(welcome_msg)),
260 section_block(text_block(sheet_msg)),
261 section_block(text_block(state_msg)),
262 section_block(text_block(solved_msg))
265 # Finally, finally, notify the hunt channel about the new puzzle
266 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
268 turb.slack_client, hunt['channel_id'],
269 "New puzzle available: <{}|{}>".format(
270 puzzle['channel_url'],
274 return lambda_success
276 def channel_created(turb, event):
278 channel = event['channel']
279 channel_id = channel['id']
280 channel_name = channel['name']
281 creator = channel['creator']
283 # Ignore any channels that turbot didn't create
284 if creator != TURBOT_USER_ID:
285 print("channel_created: Not a turbot-created channel. Exiting.")
286 return lambda_success
288 # The presence of a hyphen determines whether this is a puzzle
289 # channel or a hunt channel.
290 if '-' in channel_name:
291 return puzzle_channel_created(turb, channel_name, channel_id)
293 return hunt_channel_created(turb, channel_name, channel_id)
295 events['channel_created'] = channel_created