1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
6 from turbot.slack import slack_send_message, slack_channel_members
8 TURBOT_USER_ID = 'U01B9QM4P9R'
12 lambda_success = {'statusCode': 200}
13 lambda_error = {'statusCode': 400}
15 def channel_url(channel_id):
16 return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
18 def puzzle_block(puzzle):
20 status = puzzle['status']
21 solution = puzzle['solution']
22 channel_id = puzzle['channel_id']
23 url = puzzle.get('url', None)
24 sheet_url = puzzle.get('sheet_url', None)
25 state = puzzle.get('state', None)
29 if status == 'solved':
30 status_emoji = ":ballot_box_with_check:"
32 status_emoji = ":white_square:"
35 solution_str = "*`" + '`, `'.join(solution) + "`*"
39 links.append("<{}|Puzzle>".format(url))
41 links.append("<{}|Sheet>".format(sheet_url))
45 state_str = "\n{}".format(state)
47 puzzle_text = "{}{} <{}|{}> ({}){}".format(
48 status_emoji, solution_str,
49 channel_url(channel_id), name,
50 ', '.join(links), state_str
53 return section_block(text_block(puzzle_text))
55 def hunt_block(turb, hunt):
57 hunt_id = hunt['hunt_id']
58 channel_id = hunt['channel_id']
60 response = turb.db.Table(hunt_id).scan()
61 puzzles = response['Items']
63 hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
66 section_block(text_block(hunt_text)),
67 *[puzzle_block(puzzle) for puzzle in puzzles],
71 def home(turb, user_id):
72 """Returns a view to be published as the turbot home tab for user_id
74 The return value is a dictionary suitable to be published to the
75 Slack views_publish API."""
77 # Behave cleanly if there is no hunts table at all yet.
79 response = turb.db.Table("hunts").scan()
80 hunts = response['Items']
86 if not hunt['active']:
88 if user_id not in slack_channel_members(turb.slack_client,
91 hunt_blocks += hunt_block(turb, hunt)
96 section_block(text_block("*Hunts you belong to*")),
99 actions_block(button_block("New hunt", "new_hunt"))
103 def app_home_opened(turb, event):
104 """Handler for the app_home_opened event
106 This event occurs when a user visits the home tab for the turbot app.
107 In response to this event we need to publish a view for the user."""
109 user_id = event['user']
110 view = home(turb, user_id)
111 turb.slack_client.views_publish(user_id=user_id, view=view)
112 return lambda_success
114 events['app_home_opened'] = app_home_opened
116 def hunt_channel_created(turb, channel_name, channel_id):
117 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
119 # First see if we can find an entry for this hunt in the database.
120 # If not, simply return an error and let Slack retry
121 hunts_table = turb.db.Table("hunts")
122 response = hunts_table.get_item(
123 Key={'channel_id': channel_id},
126 if 'Item' not in response:
127 print("Warning: Cannot find channel_id {} in hunts table. "
128 .format(channel_id) + "Letting Slack retry this event")
131 item = response['Item']
133 if 'sheet_url' in item:
134 print("Info: channel_id {} already has sheet_url {}. Exiting."
135 .format(channel_id, item['sheet_url']))
136 return lambda_success
138 # Remove any None items from our item before updating
142 # Before launching into sheet creation, indicate that we're doing this
143 # in the database. This way, if we take too long to create the sheet
144 # and Slack retries the event, that next event will see this 'pending'
145 # string and cleanly return (eliminating all future retries).
146 item['sheet_url'] = 'pending'
147 hunts_table.put_item(Item=item)
149 # Also, let the channel users know what we are up to
151 turb.slack_client, channel_id,
152 "Welcome to the channel for the {} hunt! ".format(item['name'])
153 + "Please wait a minute or two while I create some backend resources.")
155 # Create a sheet for the hunt
156 sheet = turbot.sheets.sheets_create(turb, item['name'])
158 # Update the database with the URL of the sheet
159 item['sheet_url'] = sheet['url']
160 hunts_table.put_item(Item=item)
162 # Message the channel with the URL of the sheet
163 slack_send_message(turb.slack_client, channel_id,
164 "Sheet created for this hunt: {}".format(sheet['url']))
166 # Create a database table for this hunt's puzzles
167 table = turb.db.create_table(
168 TableName=channel_name,
170 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
172 AttributeDefinitions=[
173 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
175 ProvisionedThroughput={
176 'ReadCapacityUnits': 5,
177 'WriteCapacityUnits': 5
181 # Wait until the table exists
182 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
184 # Mark the hunt as active in the database
185 item['active'] = True
186 hunts_table.put_item(Item=item)
188 # Message the hunt channel that the database is ready
190 turb.slack_client, channel_id,
191 "Thank you for waiting. This hunt is now ready to begin! "
192 + "Use `/puzzle` to create puzzles for the hunt.")
194 return lambda_success
196 def set_channel_description(turb, puzzle):
197 channel_id = puzzle['channel_id']
198 description = puzzle['name']
199 url = puzzle.get('url', None)
200 sheet_url = puzzle.get('sheet_url', None)
204 links.append("<{}|Puzzle>".format(url))
206 links.append("<{}|Sheet>".format(sheet_url))
209 description += "({})".format(', '.join(links))
211 turb.slack_client.conversations_setPurpose(channel=channel_id,
213 turb.slack_client.conversations_setTopic(channel=channel_id,
216 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
217 """Creates sheet and invites user for a newly-created puzzle channel"""
219 hunt_id = puzzle_channel_name.split('-')[0]
221 # First see if we can find an entry for this puzzle in the database.
222 # If not, simply return an error and let Slack retry
223 puzzle_table = turb.db.Table(hunt_id)
224 response = puzzle_table.get_item(
225 Key={'channel_id': puzzle_channel_id},
228 if 'Item' not in response:
229 print("Warning: Cannot find channel_id {} in {} table. "
230 .format(puzzle_channel_id, hunt_id)
231 + "Letting Slack retry this event")
234 item = response['Item']
236 if 'sheet_url' in item:
237 print("Info: channel_id {} already has sheet_url {}. Exiting."
238 .format(puzzle_channel_id, item['sheet_url']))
239 return lambda_success
241 # Remove any None items from our item before updating
245 # Before launching into sheet creation, indicate that we're doing this
246 # in the database. This way, if we take too long to create the sheet
247 # and Slack retries the event, that next event will see this 'pending'
248 # string and cleanly return (eliminating all future retries).
249 item['sheet_url'] = 'pending'
250 item['channel_url'] = channel_url(puzzle_channel_id)
251 puzzle_table.put_item(Item=item)
253 # Create a sheet for the puzzle
254 sheet = turbot.sheets.sheets_create_for_puzzle(turb, item)
256 # Update the database with the URL of the sheet
257 item['sheet_url'] = sheet['url']
258 puzzle_table.put_item(Item=item)
260 # Get the new sheet_url into the channel description
261 set_channel_description(turb, item)
263 # Lookup and invite all users from this hunt to this new puzzle
264 hunts_table = turb.db.Table('hunts')
265 response = hunts_table.scan(
266 FilterExpression='hunt_id = :hunt_id',
267 ExpressionAttributeValues={':hunt_id': hunt_id}
270 if 'Items' in response:
272 hunt_channel_id = response['Items'][0]['channel_id']
274 # Find all members of the hunt channel
275 members = turbot.slack.slack_channel_members(turb.slack_client,
278 # Filter out Turbot's own ID to avoid inviting itself
279 members = [m for m in members if m != TURBOT_USER_ID]
282 turb.slack_client, puzzle_channel_id,
283 "Inviting all members from the hunt channel: "
284 + "<#{}>".format(hunt_channel_id))
286 # Invite those members to the puzzle channel (in chunks of 500)
288 while cursor < len(members):
289 turb.slack_client.conversations_invite(
290 channel=puzzle_channel_id,
291 users=members[cursor:cursor + 500])
294 # And finally, give a welcome message with some documentation
295 # on how to update the state of the puzzle in the database.
297 "Welcome! This channel is the primary place to "
298 + "discuss things as the team works together to solve the "
299 + "puzzle '{}'. ".format(item['name'])
304 "See the <{}|puzzle itself> ".format(item['url'])
305 + "for what was originally presented to us."
309 "Actual puzzle solving work will take place within the following "
310 + "<{}|shared spreadsheet> ".format(item['sheet_url'])
314 "Whenever the status of the puzzle progress changes "
315 + "significantly, please type `/state` with a brief message "
316 + "explaining where things stand. This could be something "
317 + "like `/state Grid is filled. Need insight for extraction.` "
318 + "or `/state Nathan has printed this and is cutting/assembling`. "
319 + "It's especially important to put information in `/state` "
320 + "when you step away from a puzzle so the next team members "
321 + "to arrive will know what is going on."
325 "When a puzzle has been solved, submitted, and the solution is "
326 + "confirmed, please type `/solved THE PUZZLE ANSWER HERE`. All "
327 + "information given in `/state` and `/solved` will be presented "
328 + "in this channel's topic as well as in the hunt overview "
329 + "(which is available by selecting \"Turbot\" from the Slack "
330 + "list of members)."
333 turb.slack_client.chat_postMessage(
334 channel=puzzle_channel_id,
335 text="New puzzle: {}".format(item['name']),
337 section_block(text_block(welcome_msg)),
338 section_block(text_block(sheet_msg)),
339 section_block(text_block(state_msg)),
340 section_block(text_block(solved_msg))
343 return lambda_success
345 def channel_created(turb, event):
346 print("In channel_created with event: {}".format(str(event)))
348 channel = event['channel']
349 channel_id = channel['id']
350 channel_name = channel['name']
351 creator = channel['creator']
353 # Ignore any channels that turbot didn't create
354 if creator != TURBOT_USER_ID:
355 print("channel_created: Not a turbot-created channel. Exiting.")
356 return lambda_success
358 # The presence of a hyphen determines whether this is a puzzle
359 # channel or a hunt channel.
360 if '-' in channel_name:
361 return puzzle_channel_created(turb, channel_name, channel_id)
363 return hunt_channel_created(turb, channel_name, channel_id)
365 events['channel_created'] = channel_created