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.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.append(hunt_link_block(turb, hunt))
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:*")),
61 my_hunt_blocks.append([
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 in two parts:
130 # ... first, a top-level folder named for the hunt
131 hunt_folder = sheets_create_folder(turb, hunt['hunt_id'])
133 # ... second, a folder within that named "turbot"
135 # The concept here is that non-turbot related content could
136 # be placed adjacent to the turbot folder.
137 hunt['folder_id'] = sheets_create_folder(turb, "turbot",
138 parents = [hunt_folder])
140 # Create a sheet for the hunt
141 sheet = sheets_create(turb, hunt['name'], hunt['folder_id'])
142 hunt['sheet_url'] = sheet['url']
144 # Message the channel with the URL of the sheet
145 slack_send_message(turb.slack_client, channel_id,
146 "Sheet created for this hunt: {}".format(sheet['url']))
148 # Mark the hunt as active now
149 hunt['active'] = True
151 # Update the database with all the changes we have made to the hunt
152 turb.table.put_item(Item=hunt)
154 # Message the hunt channel that the database is ready
156 turb.slack_client, channel_id,
157 "Thank you for waiting. This hunt is now ready to begin! "
158 + "Type `/new` to create a puzzle for the hunt and `/help` for help.")
160 return lambda_success
162 def set_channel_description(turb, puzzle):
163 channel_id = puzzle['channel_id']
164 description = puzzle['name']
165 url = puzzle.get('url', None)
166 sheet_url = puzzle.get('sheet_url', None)
170 links.append("<{}|Puzzle>".format(url))
172 links.append("<{}|Sheet>".format(sheet_url))
175 description += "({})".format(', '.join(links))
177 turb.slack_client.conversations_setPurpose(channel=channel_id,
179 turb.slack_client.conversations_setTopic(channel=channel_id,
182 def puzzle_channel_created(turb, channel_name, channel_id):
183 """Creates sheet and invites user for a newly-created puzzle channel"""
185 # First see if we can find an entry for this puzzle in the database.
186 # If not, simply return an error and let Slack retry
187 response = turb.table.query(
188 IndexName="channel_id_index",
189 KeyConditionExpression=Key("channel_id").eq(channel_id),
191 if 'Items' not in response:
192 print("Warning: Cannot find channel_id {} in turbot table. "
193 .format(channel_id) + "Letting Slack retry this event")
196 puzzle = response['Items'][0]
198 if 'sheet_url' in puzzle:
199 print("Info: channel_id {} already has sheet_url {}. Exiting."
200 .format(channel_id, puzzle['sheet_url']))
201 return lambda_success
203 # We need hunt from the database to know which folder to create
205 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
207 # Before launching into sheet creation, indicate that we're doing this
208 # in the database. This way, if we take too long to create the sheet
209 # and Slack retries the event, that next event will see this 'pending'
210 # string and cleanly return (eliminating all future retries).
211 puzzle['sheet_url'] = 'pending'
212 puzzle['channel_url'] = channel_url(channel_id)
213 turb.table.put_item(Item=puzzle)
215 # Create a sheet for the puzzle
216 sheet = sheets_create_for_puzzle(turb, puzzle, hunt['folder_id'])
218 # Update the database with the URL of the sheet
219 puzzle['sheet_url'] = sheet['url']
220 turb.table.put_item(Item=puzzle)
222 # Get the new sheet_url into the channel description
223 set_channel_description(turb, puzzle)
225 # And finally, give a welcome message with some documentation
226 # on how to update the state of the puzzle in the database.
228 "Welcome! This channel is the primary place to "
229 + "discuss things as the team works together to solve the "
230 + "puzzle \"{}\". ".format(puzzle['name'])
235 "See the <{}|puzzle itself> ".format(puzzle['url'])
236 + "for what was originally presented to us. "
240 "Actual puzzle solving work will take place within the following " +
241 "<{}|shared spreadsheet> ".format(puzzle['sheet_url']) +
243 "Common commands for updating the puzzle are `/state NEW STATE`, " +
244 "`/tag NEW_TAG`, and `/solved SOLUTION` . See `/help` for details " +
245 "and for additional commands."
248 turb.slack_client.chat_postMessage(channel=channel_id, text=welcome_msg)
250 # Finally, finally, notify the hunt channel about the new puzzle
251 hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
253 turb.slack_client, hunt['channel_id'],
254 "New puzzle available: <{}|{}>".format(
255 puzzle['channel_url'],
259 return lambda_success
261 def channel_created(turb, event):
263 channel = event['channel']
264 channel_id = channel['id']
265 channel_name = channel['name']
266 creator = channel['creator']
268 # Ignore any channels that turbot didn't create
269 if creator != TURBOT_USER_ID:
270 print("channel_created: Not a turbot-created channel. Exiting.")
271 return lambda_success
273 # The presence of a hyphen determines whether this is a puzzle
274 # channel or a hunt channel.
275 if '-' in channel_name:
276 return puzzle_channel_created(turb, channel_name, channel_id)
278 return hunt_channel_created(turb, channel_name, channel_id)
280 events['channel_created'] = channel_created