1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
5 from turbot.sheets import sheets_create, sheets_create_for_puzzle
6 from turbot.slack import slack_send_message, slack_channel_members
7 from boto3.dynamodb.conditions import Key
9 TURBOT_USER_ID = 'U01B9QM4P9R'
13 lambda_success = {'statusCode': 200}
14 lambda_error = {'statusCode': 400}
16 def channel_url(channel_id):
17 return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
19 def puzzle_block(puzzle):
21 status = puzzle['status']
22 solution = puzzle['solution']
23 channel_id = puzzle['channel_id']
24 url = puzzle.get('url', None)
25 sheet_url = puzzle.get('sheet_url', None)
26 state = puzzle.get('state', None)
30 if status == 'solved':
31 status_emoji = ":ballot_box_with_check:"
33 status_emoji = ":white_square:"
36 solution_str = "*`" + '`, `'.join(solution) + "`*"
40 links.append("<{}|Puzzle>".format(url))
42 links.append("<{}|Sheet>".format(sheet_url))
46 state_str = "\n{}".format(state)
48 puzzle_text = "{}{} <{}|{}> ({}){}".format(
49 status_emoji, solution_str,
50 channel_url(channel_id), name,
51 ', '.join(links), state_str
54 return section_block(text_block(puzzle_text))
56 def hunt_block(turb, hunt):
58 hunt_id = hunt['hunt_id']
59 channel_id = hunt['channel_id']
61 response = turb.db.Table(hunt_id).scan()
62 puzzles = response['Items']
64 hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
67 section_block(text_block(hunt_text)),
68 *[puzzle_block(puzzle) for puzzle in puzzles],
72 def home(turb, user_id):
73 """Returns a view to be published as the turbot home tab for user_id
75 The return value is a dictionary suitable to be published to the
76 Slack views_publish API."""
78 # Behave cleanly if there is no "turbot" table at all yet.
80 response = turb.table.scan()
81 hunts = response['Items']
87 if not hunt['active']:
89 if user_id not in slack_channel_members(turb.slack_client,
92 hunt_blocks += hunt_block(turb, hunt)
96 section_block(text_block("*Hunts you belong to*")),
102 section_block(text_block("You do not belong to any hunts"))
109 actions_block(button_block("New hunt", "new_hunt"))
113 def app_home_opened(turb, event):
114 """Handler for the app_home_opened event
116 This event occurs when a user visits the home tab for the turbot app.
117 In response to this event we need to publish a view for the user."""
119 user_id = event['user']
120 view = home(turb, user_id)
121 turb.slack_client.views_publish(user_id=user_id, view=view)
122 return lambda_success
124 events['app_home_opened'] = app_home_opened
126 def hunt_channel_created(turb, channel_name, channel_id):
127 """Creates a Google sheet for a newly-created hunt channel"""
129 # First see if we can find an entry for this hunt in the database.
130 # If not, simply return an error and let Slack retry
131 response = turb.table.query(
132 IndexName='channel_id_index',
133 KeyConditionExpression=Key("channel_id").eq(channel_id)
135 if 'Items' not in response:
136 print("Warning: Cannot find channel_id {} in hunts table. "
137 .format(channel_id) + "Letting Slack retry this event")
140 item = response['Items'][0]
142 if 'sheet_url' in item:
143 print("Info: channel_id {} already has sheet_url {}. Exiting."
144 .format(channel_id, item['sheet_url']))
145 return lambda_success
147 # Before launching into sheet creation, indicate that we're doing this
148 # in the database. This way, if we take too long to create the sheet
149 # and Slack retries the event, that next event will see this 'pending'
150 # string and cleanly return (eliminating all future retries).
151 item['sheet_url'] = 'pending'
152 turb.table.put_item(Item=item)
154 # Also, let the channel users know what we are up to
156 turb.slack_client, channel_id,
157 "Welcome to the channel for the {} hunt! ".format(item['name'])
158 + "Please wait a minute or two while I create some backend resources.")
160 # Create a sheet for the hunt
161 sheet = sheets_create(turb, item['name'])
163 # Update the database with the URL of the sheet
164 item['sheet_url'] = sheet['url']
165 turb.table.put_item(Item=item)
167 # Message the channel with the URL of the sheet
168 slack_send_message(turb.slack_client, channel_id,
169 "Sheet created for this hunt: {}".format(sheet['url']))
171 # Mark the hunt as active in the database
172 item['active'] = True
173 turb.table.put_item(Item=item)
175 # Message the hunt channel that the database is ready
177 turb.slack_client, channel_id,
178 "Thank you for waiting. This hunt is now ready to begin! "
179 + "Use `/puzzle` to create puzzles for the hunt.")
181 return lambda_success
183 def set_channel_description(turb, puzzle):
184 channel_id = puzzle['channel_id']
185 description = puzzle['name']
186 url = puzzle.get('url', None)
187 sheet_url = puzzle.get('sheet_url', None)
191 links.append("<{}|Puzzle>".format(url))
193 links.append("<{}|Sheet>".format(sheet_url))
196 description += "({})".format(', '.join(links))
198 turb.slack_client.conversations_setPurpose(channel=channel_id,
200 turb.slack_client.conversations_setTopic(channel=channel_id,
203 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
204 """Creates sheet and invites user for a newly-created puzzle channel"""
206 hunt_id = puzzle_channel_name.split('-')[0]
208 # First see if we can find an entry for this puzzle in the database.
209 # If not, simply return an error and let Slack retry
210 response = turb.table.get_item(
211 Key={'channel_id': puzzle_channel_id},
214 if 'Item' not in response:
215 print("Warning: Cannot find channel_id {} in {} table. "
216 .format(puzzle_channel_id, hunt_id)
217 + "Letting Slack retry this event")
220 item = response['Item']
222 if 'sheet_url' in item:
223 print("Info: channel_id {} already has sheet_url {}. Exiting."
224 .format(puzzle_channel_id, item['sheet_url']))
225 return lambda_success
227 # Before launching into sheet creation, indicate that we're doing this
228 # in the database. This way, if we take too long to create the sheet
229 # and Slack retries the event, that next event will see this 'pending'
230 # string and cleanly return (eliminating all future retries).
231 item['sheet_url'] = 'pending'
232 item['channel_url'] = channel_url(puzzle_channel_id)
233 turb.table.put_item(Item=item)
235 # Create a sheet for the puzzle
236 sheet = sheets_create_for_puzzle(turb, item)
238 # Update the database with the URL of the sheet
239 item['sheet_url'] = sheet['url']
240 turb.table.put_item(Item=item)
242 # Get the new sheet_url into the channel description
243 set_channel_description(turb, item)
245 # Lookup and invite all users from this hunt to this new puzzle
246 hunts_table = turb.db.Table('hunts')
247 response = hunts_table.scan(
248 FilterExpression='hunt_id = :hunt_id',
249 ExpressionAttributeValues={':hunt_id': hunt_id}
252 if 'Items' in response:
254 hunt_channel_id = response['Items'][0]['channel_id']
256 # Find all members of the hunt channel
257 members = turbot.slack.slack_channel_members(turb.slack_client,
260 # Filter out Turbot's own ID to avoid inviting itself
261 members = [m for m in members if m != TURBOT_USER_ID]
264 turb.slack_client, puzzle_channel_id,
265 "Inviting all members from the hunt channel: "
266 + "<#{}>".format(hunt_channel_id))
268 # Invite those members to the puzzle channel (in chunks of 500)
270 while cursor < len(members):
271 turb.slack_client.conversations_invite(
272 channel=puzzle_channel_id,
273 users=members[cursor:cursor + 500])
276 # And finally, give a welcome message with some documentation
277 # on how to update the state of the puzzle in the database.
279 "Welcome! This channel is the primary place to "
280 + "discuss things as the team works together to solve the "
281 + "puzzle '{}'. ".format(item['name'])
286 "See the <{}|puzzle itself> ".format(item['url'])
287 + "for what was originally presented to us."
291 "Actual puzzle solving work will take place within the following "
292 + "<{}|shared spreadsheet> ".format(item['sheet_url'])
296 "Whenever the status of the puzzle progress changes "
297 + "significantly, please type `/state` with a brief message "
298 + "explaining where things stand. This could be something "
299 + "like `/state Grid is filled. Need insight for extraction.` "
300 + "or `/state Nathan has printed this and is cutting/assembling`. "
301 + "It's especially important to put information in `/state` "
302 + "when you step away from a puzzle so the next team members "
303 + "to arrive will know what is going on."
307 "When a puzzle has been solved, submitted, and the solution is "
308 + "confirmed, please type `/solved THE PUZZLE ANSWER HERE`. All "
309 + "information given in `/state` and `/solved` will be presented "
310 + "in this channel's topic as well as in the hunt overview "
311 + "(which is available by selecting \"Turbot\" from the Slack "
312 + "list of members)."
315 turb.slack_client.chat_postMessage(
316 channel=puzzle_channel_id,
317 text="New puzzle: {}".format(item['name']),
319 section_block(text_block(welcome_msg)),
320 section_block(text_block(sheet_msg)),
321 section_block(text_block(state_msg)),
322 section_block(text_block(solved_msg))
325 return lambda_success
327 def channel_created(turb, event):
329 channel = event['channel']
330 channel_id = channel['id']
331 channel_name = channel['name']
332 creator = channel['creator']
334 # Ignore any channels that turbot didn't create
335 if creator != TURBOT_USER_ID:
336 print("channel_created: Not a turbot-created channel. Exiting.")
337 return lambda_success
339 # The presence of a hyphen determines whether this is a puzzle
340 # channel or a hunt channel.
341 if '-' in channel_name:
342 return puzzle_channel_created(turb, channel_name, channel_id)
344 return hunt_channel_created(turb, channel_name, channel_id)
346 events['channel_created'] = channel_created