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)
27 if status == 'solved':
28 status_emoji = ":ballot_box_with_check:"
30 status_emoji = ":white_square:"
33 solution_str = "*`" + '`, `'.join(solution) + "`*"
37 links.append("<{}|Puzzle>".format(url))
39 links.append("<{}|Sheet>".format(sheet_url))
41 puzzle_text = "{}{} <{}|{}> ({})".format(
42 status_emoji, solution_str,
43 channel_url(channel_id), name,
47 return section_block(text_block(puzzle_text))
49 def hunt_block(turb, hunt):
51 hunt_id = hunt['hunt_id']
52 channel_id = hunt['channel_id']
54 response = turb.db.Table(hunt_id).scan()
55 puzzles = response['Items']
57 hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
60 section_block(text_block(hunt_text)),
61 *[puzzle_block(puzzle) for puzzle in puzzles],
65 def home(turb, user_id):
66 """Returns a view to be published as the turbot home tab for user_id
68 The return value is a dictionary suitable to be published to the
69 Slack views_publish API."""
71 # Behave cleanly if there is no hunts table at all yet.
73 response = turb.db.Table("hunts").scan()
74 hunts = response['Items']
81 hunt_blocks += hunt_block(turb, hunt)
86 section_block(text_block("*Active hunts*")),
89 actions_block(button_block("New hunt", "new_hunt"))
93 def app_home_opened(turb, event):
94 """Handler for the app_home_opened event
96 This event occurs when a user visits the home tab for the turbot app.
97 In response to this event we need to publish a view for the user."""
99 user_id = event['user']
100 view = home(turb, user_id)
101 turb.slack_client.views_publish(user_id=user_id, view=view)
102 return lambda_success
104 events['app_home_opened'] = app_home_opened
106 def hunt_channel_created(turb, channel_name, channel_id):
107 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
109 # First see if we can find an entry for this hunt in the database.
110 # If not, simply return an error and let Slack retry
111 hunts_table = turb.db.Table("hunts")
112 response = hunts_table.get_item(
113 Key={'channel_id': channel_id},
116 if 'Item' not in response:
117 print("Warning: Cannot find channel_id {} in hunts table. "
118 .format(channel_id) + "Letting Slack retry this event")
121 item = response['Item']
123 if 'sheet_url' in item:
124 print("Info: channel_id {} already has sheet_url {}. Exiting."
125 .format(channel_id, item['sheet_url']))
126 return lambda_success
128 # Remove any None items from our item before updating
132 # Before launching into sheet creation, indicate that we're doing this
133 # in the database. This way, if we take too long to create the sheet
134 # and Slack retries the event, that next event will see this 'pending'
135 # string and cleanly return (eliminating all future retries).
136 item['sheet_url'] = 'pending'
137 hunts_table.put_item(Item=item)
139 # Also, let the channel users know what we are up to
140 turb.slack_client.chat_postMessage(
142 text="Welcome to the channel for the {} hunt! ".format(item['name'])
143 + "Please wait a minute or two while I create some backend resources.")
145 # Create a sheet for the channel
146 sheet = turbot.sheets.sheets_create(turb, channel_name)
148 # Update the database with the URL of the sheet
149 item['sheet_url'] = sheet['url']
150 hunts_table.put_item(Item=item)
152 # Message the channel with the URL of the sheet
153 turb.slack_client.chat_postMessage(channel=channel_id,
154 text="Sheet created for this hunt: {}"
155 .format(sheet['url']))
157 # Create a database table for this hunt's puzzles
158 table = turb.db.create_table(
159 TableName=channel_name,
161 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
163 AttributeDefinitions=[
164 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
166 ProvisionedThroughput={
167 'ReadCapacityUnits': 5,
168 'WriteCapacityUnits': 5
172 # Wait until the table exists
173 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
175 # Mark the hunt as active in the database
176 item['active'] = True
177 hunts_table.put_item(Item=item)
179 # Message the hunt channel that the database is ready
180 turb.slack_client.chat_postMessage(
182 text="Thank you for waiting. This hunt is now ready to begin! "
183 + "Use `/puzzle` to create puzzles for the hunt.")
185 return lambda_success
187 def set_channel_description(turb, puzzle):
188 channel_id = puzzle['channel_id']
189 description = puzzle['name']
190 url = puzzle.get('url', None)
191 sheet_url = puzzle.get('sheet_url', None)
195 links.append("<{}|Puzzle>".format(url))
197 links.append("<{}|Sheet>".format(sheet_url))
200 description += "({})".format(', '.join(links))
202 turb.slack_client.conversations_setPurpose(channel=channel_id,
204 turb.slack_client.conversations_setTopic(channel=channel_id,
207 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
208 """Creates sheet and invites user for a newly-created puzzle channel"""
210 hunt_id = puzzle_channel_name.split('-')[0]
212 # First see if we can find an entry for this puzzle in the database.
213 # If not, simply return an error and let Slack retry
214 puzzle_table = turb.db.Table(hunt_id)
215 response = puzzle_table.get_item(
216 Key={'channel_id': puzzle_channel_id},
219 if 'Item' not in response:
220 print("Warning: Cannot find channel_id {} in {} table. "
221 .format(puzzle_channel_id, hunt_id)
222 + "Letting Slack retry this event")
225 item = response['Item']
227 if 'sheet_url' in item:
228 print("Info: channel_id {} already has sheet_url {}. Exiting."
229 .format(puzzle_channel_id, item['sheet_url']))
230 return lambda_success
232 # Remove any None items from our item before updating
236 # Before launching into sheet creation, indicate that we're doing this
237 # in the database. This way, if we take too long to create the sheet
238 # and Slack retries the event, that next event will see this 'pending'
239 # string and cleanly return (eliminating all future retries).
240 item['sheet_url'] = 'pending'
241 puzzle_table.put_item(Item=item)
243 # Create a sheet for the puzzle
244 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
246 # Update the database with the URL of the sheet
247 item['sheet_url'] = sheet['url']
248 puzzle_table.put_item(Item=item)
250 # Get the new sheet_url into the channel description
251 set_channel_description(turb, item)
253 hunts_table = turb.db.Table('hunts')
254 response = hunts_table.scan(
255 FilterExpression='hunt_id = :hunt_id',
256 ExpressionAttributeValues={':hunt_id': hunt_id}
259 if 'Items' in response:
261 hunt_channel_id = response['Items'][0]['channel_id']
263 # Find all members of the hunt channel
264 members = turbot.slack.slack_channel_members(turb.slack_client,
267 # Filter out Turbot's own ID to avoid inviting itself
268 members = [m for m in members if m != TURBOT_USER_ID]
270 turb.slack_client.chat_postMessage(
271 channel=puzzle_channel_id,
272 text="Inviting all members from the hunt channel: {}"
275 # Invite those members to the puzzle channel (in chunks of 500)
277 while cursor < len(members):
278 turb.slack_client.conversations_invite(
279 channel=puzzle_channel_id,
280 users=members[cursor:cursor + 500])
283 return lambda_success
285 def channel_created(turb, event):
286 print("In channel_created with event: {}".format(str(event)))
288 channel = event['channel']
289 channel_id = channel['id']
290 channel_name = channel['name']
291 creator = channel['creator']
293 # Ignore any channels that turbot didn't create
294 if creator != TURBOT_USER_ID:
295 print("channel_created: Not a turbot-created channel. Exiting.")
296 return lambda_success
298 # The presence of a hyphen determines whether this is a puzzle
299 # channel or a hunt channel.
300 if '-' in channel_name:
301 return puzzle_channel_created(turb, channel_name, channel_id)
303 return hunt_channel_created(turb, channel_name, channel_id)
305 events['channel_created'] = channel_created