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 puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
188 """Creates sheet and invites user for a newly-created puzzle channel"""
190 hunt_id = puzzle_channel_name.split('-')[0]
192 # First see if we can find an entry for this puzzle in the database.
193 # If not, simply return an error and let Slack retry
194 puzzle_table = turb.db.Table(hunt_id)
195 response = puzzle_table.get_item(
196 Key={'channel_id': puzzle_channel_id},
199 if 'Item' not in response:
200 print("Warning: Cannot find channel_id {} in {} table. "
201 .format(puzzle_channel_id, hunt_id)
202 + "Letting Slack retry this event")
205 item = response['Item']
207 if 'sheet_url' in item:
208 print("Info: channel_id {} already has sheet_url {}. Exiting."
209 .format(puzzle_channel_id, item['sheet_url']))
210 return lambda_success
212 # Remove any None items from our item before updating
216 # Before launching into sheet creation, indicate that we're doing this
217 # in the database. This way, if we take too long to create the sheet
218 # and Slack retries the event, that next event will see this 'pending'
219 # string and cleanly return (eliminating all future retries).
220 item['sheet_url'] = 'pending'
221 puzzle_table.put_item(Item=item)
223 # Create a sheet for the puzzle
224 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
226 # Update the database with the URL of the sheet
227 item['sheet_url'] = sheet['url']
228 puzzle_table.put_item(Item=item)
230 # Message the channel with the URL of the puzzle's sheet
231 turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
232 text="Sheet created for this puzzle: {}"
233 .format(sheet['url']))
235 hunts_table = turb.db.Table('hunts')
236 response = hunts_table.scan(
237 FilterExpression='hunt_id = :hunt_id',
238 ExpressionAttributeValues={':hunt_id': hunt_id}
241 if 'Items' in response:
243 hunt_channel_id = response['Items'][0]['channel_id']
245 # Find all members of the hunt channel
246 members = turbot.slack.slack_channel_members(turb.slack_client,
249 # Filter out Turbot's own ID to avoid inviting itself
250 members = [m for m in members if m != TURBOT_USER_ID]
252 turb.slack_client.chat_postMessage(
253 channel=puzzle_channel_id,
254 text="Inviting all members from the hunt channel: {}"
257 # Invite those members to the puzzle channel (in chunks of 500)
259 while cursor < len(members):
260 turb.slack_client.conversations_invite(
261 channel=puzzle_channel_id,
262 users=members[cursor:cursor + 500])
265 return lambda_success
267 def channel_created(turb, event):
268 print("In channel_created with event: {}".format(str(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