1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
7 TURBOT_USER_ID = 'U01B9QM4P9R'
11 lambda_success = {'statusCode': 200}
12 lambda_error = {'statusCode': 400}
14 def channel_url(channel_id):
15 return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
17 def puzzle_block(puzzle):
19 status = puzzle['status']
20 solution = puzzle['solution']
21 channel_id = puzzle['channel_id']
22 url = puzzle.get('url', None)
23 sheet_url = puzzle.get('sheet_url', None)
24 state = puzzle.get('state', None)
28 if status == 'solved':
29 status_emoji = ":ballot_box_with_check:"
31 status_emoji = ":white_square:"
34 solution_str = "*`" + '`, `'.join(solution) + "`*"
38 links.append("<{}|Puzzle>".format(url))
40 links.append("<{}|Sheet>".format(sheet_url))
44 state_str = "\n{}".format(state)
46 puzzle_text = "{}{} <{}|{}> ({}){}".format(
47 status_emoji, solution_str,
48 channel_url(channel_id), name,
49 ', '.join(links), state_str
52 return section_block(text_block(puzzle_text))
54 def hunt_block(turb, hunt):
56 hunt_id = hunt['hunt_id']
57 channel_id = hunt['channel_id']
59 response = turb.db.Table(hunt_id).scan()
60 puzzles = response['Items']
62 hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
65 section_block(text_block(hunt_text)),
66 *[puzzle_block(puzzle) for puzzle in puzzles],
70 def home(turb, user_id):
71 """Returns a view to be published as the turbot home tab for user_id
73 The return value is a dictionary suitable to be published to the
74 Slack views_publish API."""
76 # Behave cleanly if there is no hunts table at all yet.
78 response = turb.db.Table("hunts").scan()
79 hunts = response['Items']
86 hunt_blocks += hunt_block(turb, hunt)
91 section_block(text_block("*Active hunts*")),
94 actions_block(button_block("New hunt", "new_hunt"))
98 def app_home_opened(turb, event):
99 """Handler for the app_home_opened event
101 This event occurs when a user visits the home tab for the turbot app.
102 In response to this event we need to publish a view for the user."""
104 user_id = event['user']
105 view = home(turb, user_id)
106 turb.slack_client.views_publish(user_id=user_id, view=view)
107 return lambda_success
109 events['app_home_opened'] = app_home_opened
111 def hunt_channel_created(turb, channel_name, channel_id):
112 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
114 # First see if we can find an entry for this hunt in the database.
115 # If not, simply return an error and let Slack retry
116 hunts_table = turb.db.Table("hunts")
117 response = hunts_table.get_item(
118 Key={'channel_id': channel_id},
121 if 'Item' not in response:
122 print("Warning: Cannot find channel_id {} in hunts table. "
123 .format(channel_id) + "Letting Slack retry this event")
126 item = response['Item']
128 if 'sheet_url' in item:
129 print("Info: channel_id {} already has sheet_url {}. Exiting."
130 .format(channel_id, item['sheet_url']))
131 return lambda_success
133 # Remove any None items from our item before updating
137 # Before launching into sheet creation, indicate that we're doing this
138 # in the database. This way, if we take too long to create the sheet
139 # and Slack retries the event, that next event will see this 'pending'
140 # string and cleanly return (eliminating all future retries).
141 item['sheet_url'] = 'pending'
142 hunts_table.put_item(Item=item)
144 # Also, let the channel users know what we are up to
145 turb.slack_client.chat_postMessage(
147 text="Welcome to the channel for the {} hunt! ".format(item['name'])
148 + "Please wait a minute or two while I create some backend resources.")
150 # Create a sheet for the channel
151 sheet = turbot.sheets.sheets_create(turb, channel_name)
153 # Update the database with the URL of the sheet
154 item['sheet_url'] = sheet['url']
155 hunts_table.put_item(Item=item)
157 # Message the channel with the URL of the sheet
158 turb.slack_client.chat_postMessage(channel=channel_id,
159 text="Sheet created for this hunt: {}"
160 .format(sheet['url']))
162 # Create a database table for this hunt's puzzles
163 table = turb.db.create_table(
164 TableName=channel_name,
166 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
168 AttributeDefinitions=[
169 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
171 ProvisionedThroughput={
172 'ReadCapacityUnits': 5,
173 'WriteCapacityUnits': 5
177 # Wait until the table exists
178 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
180 # Mark the hunt as active in the database
181 item['active'] = True
182 hunts_table.put_item(Item=item)
184 # Message the hunt channel that the database is ready
185 turb.slack_client.chat_postMessage(
187 text="Thank you for waiting. This hunt is now ready to begin! "
188 + "Use `/puzzle` to create puzzles for the hunt.")
190 return lambda_success
192 def set_channel_description(turb, puzzle):
193 channel_id = puzzle['channel_id']
194 description = puzzle['name']
195 url = puzzle.get('url', None)
196 sheet_url = puzzle.get('sheet_url', None)
200 links.append("<{}|Puzzle>".format(url))
202 links.append("<{}|Sheet>".format(sheet_url))
205 description += "({})".format(', '.join(links))
207 turb.slack_client.conversations_setPurpose(channel=channel_id,
209 turb.slack_client.conversations_setTopic(channel=channel_id,
212 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
213 """Creates sheet and invites user for a newly-created puzzle channel"""
215 hunt_id = puzzle_channel_name.split('-')[0]
217 # First see if we can find an entry for this puzzle in the database.
218 # If not, simply return an error and let Slack retry
219 puzzle_table = turb.db.Table(hunt_id)
220 response = puzzle_table.get_item(
221 Key={'channel_id': puzzle_channel_id},
224 if 'Item' not in response:
225 print("Warning: Cannot find channel_id {} in {} table. "
226 .format(puzzle_channel_id, hunt_id)
227 + "Letting Slack retry this event")
230 item = response['Item']
232 if 'sheet_url' in item:
233 print("Info: channel_id {} already has sheet_url {}. Exiting."
234 .format(puzzle_channel_id, item['sheet_url']))
235 return lambda_success
237 # Remove any None items from our item before updating
241 # Before launching into sheet creation, indicate that we're doing this
242 # in the database. This way, if we take too long to create the sheet
243 # and Slack retries the event, that next event will see this 'pending'
244 # string and cleanly return (eliminating all future retries).
245 item['sheet_url'] = 'pending'
246 puzzle_table.put_item(Item=item)
248 # Create a sheet for the puzzle
249 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
251 # Update the database with the URL of the sheet
252 item['sheet_url'] = sheet['url']
253 puzzle_table.put_item(Item=item)
255 # Get the new sheet_url into the channel description
256 set_channel_description(turb, item)
258 hunts_table = turb.db.Table('hunts')
259 response = hunts_table.scan(
260 FilterExpression='hunt_id = :hunt_id',
261 ExpressionAttributeValues={':hunt_id': hunt_id}
264 if 'Items' in response:
266 hunt_channel_id = response['Items'][0]['channel_id']
268 # Find all members of the hunt channel
269 members = turbot.slack.slack_channel_members(turb.slack_client,
272 # Filter out Turbot's own ID to avoid inviting itself
273 members = [m for m in members if m != TURBOT_USER_ID]
275 turb.slack_client.chat_postMessage(
276 channel=puzzle_channel_id,
277 text="Inviting all members from the hunt channel: {}"
280 # Invite those members to the puzzle channel (in chunks of 500)
282 while cursor < len(members):
283 turb.slack_client.conversations_invite(
284 channel=puzzle_channel_id,
285 users=members[cursor:cursor + 500])
288 return lambda_success
290 def channel_created(turb, event):
291 print("In channel_created with event: {}".format(str(event)))
293 channel = event['channel']
294 channel_id = channel['id']
295 channel_name = channel['name']
296 creator = channel['creator']
298 # Ignore any channels that turbot didn't create
299 if creator != TURBOT_USER_ID:
300 print("channel_created: Not a turbot-created channel. Exiting.")
301 return lambda_success
303 # The presence of a hyphen determines whether this is a puzzle
304 # channel or a hunt channel.
305 if '-' in channel_name:
306 return puzzle_channel_created(turb, channel_name, channel_id)
308 return hunt_channel_created(turb, channel_name, channel_id)
310 events['channel_created'] = channel_created