1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
4 from turbot.hunt import find_hunt_for_hunt_id
5 from turbot.puzzle import (
6 puzzle_channel_topic, puzzle_channel_description,
8 from turbot.sheets import (
9 sheets_create, sheets_create_for_puzzle, sheets_create_folder
11 from turbot.slack import slack_send_message, slack_channel_members
12 from turbot.channel import channel_url
13 from boto3.dynamodb.conditions import Key
15 TURBOT_USER_ID = 'U01B9QM4P9R'
19 lambda_success = {'statusCode': 200}
20 lambda_error = {'statusCode': 400}
22 def hunt_link_block(turb, hunt):
25 channel_id = hunt['channel_id']
27 hunt_link = "*<{}|{}>*".format(channel_url(channel_id), name)
29 return section_block(text_block(hunt_link))
31 def home(turb, user_id):
32 """Returns a view to be published as the turbot home tab for user_id
34 The return value is a dictionary suitable to be published to the
35 Slack views_publish API."""
37 # Behave cleanly if there is no "turbot" table at all yet.
39 response = turb.table.scan(
40 IndexName="is_hunt_index",
42 hunts = response['Items']
47 available_hunt_blocks = []
49 if not hunt['active']:
51 if user_id in slack_channel_members(turb.slack_client,
53 my_hunt_blocks.append(hunt_link_block(turb, hunt))
55 available_hunt_blocks.append(hunt_link_block(turb, hunt))
57 if len(my_hunt_blocks):
59 section_block(text_block("*Hunts you belong to:*")),
64 my_hunt_blocks.append([
65 section_block(text_block("You do not belong to any hunts"))
68 if len(available_hunt_blocks):
69 available_hunt_blocks = [
70 section_block(text_block("*Hunts you can join:*")),
72 * available_hunt_blocks
79 * available_hunt_blocks,
80 actions_block(button_block("New hunt", "new_hunt"))
84 def app_home_opened(turb, event):
85 """Handler for the app_home_opened event
87 This event occurs when a user visits the home tab for the turbot app.
88 In response to this event we need to publish a view for the user."""
90 user_id = event['user']
91 view = home(turb, user_id)
92 turb.slack_client.views_publish(user_id=user_id, view=view)
95 events['app_home_opened'] = app_home_opened
97 def hunt_channel_created(turb, channel_name, channel_id):
98 """Creates a Google sheet for a newly-created hunt channel"""
100 # First see if we can find an entry for this hunt in the database.
101 # If not, simply return an error and let Slack retry
102 response = turb.table.query(
103 IndexName='channel_id_index',
104 KeyConditionExpression=Key("channel_id").eq(channel_id)
106 if 'Items' not in response:
107 print("Warning: Cannot find channel_id {} in turbot table. "
108 .format(channel_id) + "Letting Slack retry this event")
111 hunt = response['Items'][0]
113 if 'sheet_url' in hunt:
114 print("Info: channel_id {} already has sheet_url {}. Exiting."
115 .format(channel_id, hunt['sheet_url']))
116 return lambda_success
118 # Before launching into sheet creation, indicate that we're doing this
119 # in the database. This way, if we take too long to create the sheet
120 # and Slack retries the event, that next event will see this 'pending'
121 # string and cleanly return (eliminating all future retries).
122 hunt['sheet_url'] = 'pending'
123 turb.table.put_item(Item=hunt)
125 # Also, let the channel users know what we are up to
127 turb.slack_client, channel_id,
128 "Welcome to the channel for the {} hunt! ".format(hunt['name'])
129 + "Please wait a moment or two while I create some backend resources.")
131 # Create a new folder within Google drive for the hunt in two parts:
133 # ... first, a top-level folder named for the hunt
134 hunt_folder = sheets_create_folder(turb, hunt['hunt_id'])
136 # ... second, a folder within that named "turbot"
138 # The concept here is that non-turbot related content could
139 # be placed adjacent to the turbot folder.
140 hunt['folder_id'] = sheets_create_folder(turb, "turbot",
141 parents = [hunt_folder])
143 # Create a sheet for the hunt
144 sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
145 hunt['sheet_url'] = sheet['url']
147 # Message the channel with the URL of the sheet
148 slack_send_message(turb.slack_client, channel_id,
149 "Sheet created for this hunt: {}".format(sheet['url']))
151 # Mark the hunt as active now
152 hunt['active'] = True
154 # Update the database with all the changes we have made to the hunt
155 turb.table.put_item(Item=hunt)
157 # Message the hunt channel that the database is ready
159 turb.slack_client, channel_id,
160 "Thank you for waiting. This hunt is now ready to begin! "
161 + "Type `/new` to create a puzzle for the hunt and `/help` for help.")
163 return lambda_success
165 def set_channel_topic_and_description(turb, puzzle):
167 channel_id = puzzle['channel_id']
169 topic = puzzle_channel_topic(puzzle)
170 description = puzzle_channel_description(puzzle)
172 turb.slack_client.conversations_setPurpose(channel=channel_id,
174 turb.slack_client.conversations_setTopic(channel=channel_id,
177 def puzzle_channel_created(turb, channel_name, channel_id):
178 """Creates sheet and invites user for a newly-created puzzle channel"""
180 # First see if we can find an entry for this puzzle in the database.
181 # If not, simply return an error and let Slack retry
182 response = turb.table.query(
183 IndexName="channel_id_index",
184 KeyConditionExpression=Key("channel_id").eq(channel_id),
186 if 'Items' not in response:
187 print("Warning: Cannot find channel_id {} in turbot table. "
188 .format(channel_id) + "Letting Slack retry this event")
191 puzzle = response['Items'][0]
193 if 'sheet_url' in puzzle:
194 print("Info: channel_id {} already has sheet_url {}. Exiting."
195 .format(channel_id, puzzle['sheet_url']))
196 return lambda_success
198 # We need hunt from the database to know which folder to create
200 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
202 # Before launching into sheet creation, indicate that we're doing this
203 # in the database. This way, if we take too long to create the sheet
204 # and Slack retries the event, that next event will see this 'pending'
205 # string and cleanly return (eliminating all future retries).
206 puzzle['sheet_url'] = 'pending'
207 puzzle['channel_url'] = channel_url(channel_id)
208 turb.table.put_item(Item=puzzle)
210 # Create a sheet for the puzzle
211 sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
213 # Update the database with the URL of the sheet
214 puzzle['sheet_url'] = sheet['url']
215 turb.table.put_item(Item=puzzle)
217 # Get the new sheet_url into the channel topic and description
218 set_channel_topic_and_description(turb, puzzle)
220 # And finally, give a welcome message with some documentation
221 # on how to update the state of the puzzle in the database.
223 "Welcome! This channel is the primary place to "
224 + "discuss things as the team works together to solve the "
225 + "puzzle \"{}\". ".format(puzzle['name'])
230 "See the <{}|puzzle itself> ".format(puzzle['url'])
231 + "for what was originally presented to us. "
235 "Actual puzzle solving work will take place within the following " +
236 "<{}|shared spreadsheet> ".format(puzzle['sheet_url']) +
238 "Common commands for updating the puzzle are `/state NEW STATE`, " +
239 "`/tag NEW_TAG`, and `/solved SOLUTION` . See `/help` for details " +
240 "and for additional commands."
243 turb.slack_client.chat_postMessage(channel=channel_id, text=welcome_msg)
245 # Finally, finally, notify the hunt channel about the new puzzle
246 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
248 turb.slack_client, hunt['channel_id'],
249 "New puzzle available: <{}|{}>".format(
250 puzzle['channel_url'],
254 return lambda_success
256 def channel_created(turb, event):
258 channel = event['channel']
259 channel_id = channel['id']
260 channel_name = channel['name']
261 creator = channel['creator']
263 # Ignore any channels that turbot didn't create
264 if creator != TURBOT_USER_ID:
265 print("channel_created: Not a turbot-created channel. Exiting.")
266 return lambda_success
268 # The presence of a hyphen determines whether this is a puzzle
269 # channel or a hunt channel.
270 if '-' in channel_name:
271 return puzzle_channel_created(turb, channel_name, channel_id)
273 return hunt_channel_created(turb, channel_name, channel_id)
275 events['channel_created'] = channel_created