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 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
10 TURBOT_USER_ID = 'U01B9QM4P9R'
14 lambda_success = {'statusCode': 200}
15 lambda_error = {'statusCode': 400}
17 def hunt_link_block(turb, hunt):
20 channel_id = hunt['channel_id']
22 hunt_link = "*<{}|{}>*".format(channel_url(channel_id), name)
24 return section_block(text_block(hunt_link))
26 def home(turb, user_id):
27 """Returns a view to be published as the turbot home tab for user_id
29 The return value is a dictionary suitable to be published to the
30 Slack views_publish API."""
32 # Behave cleanly if there is no "turbot" table at all yet.
34 response = turb.table.scan(
35 IndexName="is_hunt_index",
37 hunts = response['Items']
42 available_hunt_blocks = []
44 if not hunt['active']:
46 if user_id in slack_channel_members(turb.slack_client,
48 my_hunt_blocks += hunt_blocks(turb, hunt, puzzle_status='all')
50 available_hunt_blocks.append(hunt_link_block(turb, hunt))
52 if len(my_hunt_blocks):
54 section_block(text_block("*Hunts you belong to:*")),
60 section_block(text_block("You do not belong to any hunts"))
63 if len(available_hunt_blocks):
64 available_hunt_blocks = [
65 section_block(text_block("*Hunts you can join:*")),
67 * available_hunt_blocks
74 * available_hunt_blocks,
75 actions_block(button_block("New hunt", "new_hunt"))
79 def app_home_opened(turb, event):
80 """Handler for the app_home_opened event
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."""
85 user_id = event['user']
86 view = home(turb, user_id)
87 turb.slack_client.views_publish(user_id=user_id, view=view)
90 events['app_home_opened'] = app_home_opened
92 def hunt_channel_created(turb, channel_name, channel_id):
93 """Creates a Google sheet for a newly-created hunt channel"""
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)
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")
106 item = response['Items'][0]
108 if 'sheet_url' in item:
109 print("Info: channel_id {} already has sheet_url {}. Exiting."
110 .format(channel_id, item['sheet_url']))
111 return lambda_success
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 item['sheet_url'] = 'pending'
118 turb.table.put_item(Item=item)
120 # Also, let the channel users know what we are up to
122 turb.slack_client, channel_id,
123 "Welcome to the channel for the {} hunt! ".format(item['name'])
124 + "Please wait a minute or two while I create some backend resources.")
126 # Create a sheet for the hunt
127 sheet = sheets_create(turb, item['name'])
129 # Update the database with the URL of the sheet
130 item['sheet_url'] = sheet['url']
131 turb.table.put_item(Item=item)
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']))
137 # Mark the hunt as active in the database
138 item['active'] = True
139 turb.table.put_item(Item=item)
141 # Message the hunt channel that the database is ready
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.")
147 return lambda_success
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)
157 links.append("<{}|Puzzle>".format(url))
159 links.append("<{}|Sheet>".format(sheet_url))
162 description += "({})".format(', '.join(links))
164 turb.slack_client.conversations_setPurpose(channel=channel_id,
166 turb.slack_client.conversations_setTopic(channel=channel_id,
169 def puzzle_channel_created(turb, channel_name, channel_id):
170 """Creates sheet and invites user for a newly-created puzzle channel"""
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),
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")
183 puzzle = response['Items'][0]
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
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)
198 # Create a sheet for the puzzle
199 sheet = sheets_create_for_puzzle(turb, puzzle)
201 # Update the database with the URL of the sheet
202 puzzle['sheet_url'] = sheet['url']
203 turb.table.put_item(Item=puzzle)
205 # Get the new sheet_url into the channel description
206 set_channel_description(turb, puzzle)
208 # And finally, give a welcome message with some documentation
209 # on how to update the state of the puzzle in the database.
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'])
218 "See the <{}|puzzle itself> ".format(puzzle['url'])
219 + "for what was originally presented to us."
223 "Actual puzzle solving work will take place within the following "
224 + "<{}|shared spreadsheet> ".format(puzzle['sheet_url'])
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."
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)."
247 turb.slack_client.chat_postMessage(
249 text="New puzzle: {}".format(['name']),
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))
257 # Finally, finally, notify the hunt channel about the new puzzle
258 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
260 turb.slack_client, hunt['channel_id'],
261 "New puzzle available: <{}|{}>".format(
262 puzzle['channel_url'],
266 return lambda_success
268 def channel_created(turb, event):
270 channel = event['channel']
271 channel_id = channel['id']
272 channel_name = channel['name']
273 creator = channel['creator']
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
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)
285 return hunt_channel_created(turb, channel_name, channel_id)
287 events['channel_created'] = channel_created