1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block, divider_block
8 TURBOT_USER_ID = 'U01B9QM4P9R'
12 lambda_success = {'statusCode': 200}
13 lambda_error = {'statusCode': 400}
15 def channel_url(channel_id):
16 return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
18 def puzzle_block(puzzle):
20 status = puzzle['status']
21 solution = puzzle['solution']
22 channel_id = puzzle['channel_id']
26 if status == 'solved':
27 status_emoji = ":ballot_box_with_check:"
29 status_emoji = ":white_square:"
32 solution_str = "*`" + '`, `'.join(solution) + "`*"
34 puzzle_text = "{}{} <{}|{}>".format(
35 status_emoji, solution_str, channel_url(channel_id), name)
37 return section_block(text_block(puzzle_text))
39 def hunt_block(turb, hunt):
41 hunt_id = hunt['hunt_id']
42 channel_id = hunt['channel_id']
44 response = turb.db.Table(hunt_id).scan()
45 puzzles = response['Items']
47 hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
50 section_block(text_block(hunt_text)),
51 *[puzzle_block(puzzle) for puzzle in puzzles],
55 def home(turb, user_id):
56 """Returns a view to be published as the turbot home tab for user_id
58 The return value is a dictionary suitable to be published to the
59 Slack views_publish API."""
61 # Behave cleanly if there is no hunts table at all yet.
63 response = turb.db.Table("hunts").scan()
64 hunts = response['Items']
71 hunt_blocks += hunt_block(turb, hunt)
76 section_block(text_block("*Active hunts*")),
79 actions_block(button_block("New hunt", "new_hunt"))
83 def app_home_opened(turb, event):
84 """Handler for the app_home_opened event
86 This event occurs when a user visits the home tab for the turbot app.
87 In response to this event we need to publish a view for the user."""
89 user_id = event['user']
90 view = home(turb, user_id)
91 turb.slack_client.views_publish(user_id=user_id, view=view)
94 events['app_home_opened'] = app_home_opened
96 def hunt_channel_created(turb, channel_name, channel_id):
97 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
99 # First see if we can find an entry for this hunt in the database.
100 # If not, simply return an error and let Slack retry
101 hunts_table = turb.db.Table("hunts")
102 response = hunts_table.get_item(
103 Key={'channel_id': channel_id},
106 if 'Item' not in response:
107 print("Warning: Cannot find channel_id {} in hunts table. "
108 .format(channel_id) + "Letting Slack retry this event")
111 item = response['Item']
113 if 'sheet_url' in item:
114 print("Info: channel_id {} already has sheet_url {}. Exiting."
115 .format(channel_id, item['sheet_url']))
116 return lambda_success
118 # Remove any None items from our item before updating
122 # Before launching into sheet creation, indicate that we're doing this
123 # in the database. This way, if we take too long to create the sheet
124 # and Slack retries the event, that next event will see this 'pending'
125 # string and cleanly return (eliminating all future retries).
126 item['sheet_url'] = 'pending'
127 hunts_table.put_item(Item=item)
129 # Also, let the channel users know what we are up to
130 turb.slack_client.chat_postMessage(
132 text="Welcome to the channel for the {} hunt! ".format(item['name'])
133 + "Please wait a minute or two while I create some backend resources.")
135 # Create a sheet for the channel
136 sheet = turbot.sheets.sheets_create(turb, channel_name)
138 # Update the database with the URL of the sheet
139 item['sheet_url'] = sheet['url']
140 hunts_table.put_item(Item=item)
142 # Message the channel with the URL of the sheet
143 turb.slack_client.chat_postMessage(channel=channel_id,
144 text="Sheet created for this hunt: {}"
145 .format(sheet['url']))
147 # Create a database table for this hunt's puzzles
148 table = turb.db.create_table(
149 TableName=channel_name,
151 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
153 AttributeDefinitions=[
154 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
156 ProvisionedThroughput={
157 'ReadCapacityUnits': 5,
158 'WriteCapacityUnits': 5
162 # Wait until the table exists
163 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
165 # Mark the hunt as active in the database
166 item['active'] = True
167 hunts_table.put_item(Item=item)
169 # Message the hunt channel that the database is ready
170 turb.slack_client.chat_postMessage(
172 text="Thank you for waiting. This hunt is now ready to begin! "
173 + "Use `/puzzle` to create puzzles for the hunt.")
175 return lambda_success
177 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
178 """Creates sheet and invites user for a newly-created puzzle channel"""
180 hunt_id = puzzle_channel_name.split('-')[0]
182 # First see if we can find an entry for this puzzle in the database.
183 # If not, simply return an error and let Slack retry
184 puzzle_table = turb.db.Table(hunt_id)
185 response = puzzle_table.get_item(
186 Key={'channel_id': puzzle_channel_id},
189 if 'Item' not in response:
190 print("Warning: Cannot find channel_id {} in {} table. "
191 .format(puzzle_channel_id, hunt_id)
192 + "Letting Slack retry this event")
195 item = response['Item']
197 if 'sheet_url' in item:
198 print("Info: channel_id {} already has sheet_url {}. Exiting."
199 .format(puzzle_channel_id, item['sheet_url']))
200 return lambda_success
202 # Remove any None items from our item before updating
206 # Before launching into sheet creation, indicate that we're doing this
207 # in the database. This way, if we take too long to create the sheet
208 # and Slack retries the event, that next event will see this 'pending'
209 # string and cleanly return (eliminating all future retries).
210 item['sheet_url'] = 'pending'
211 puzzle_table.put_item(Item=item)
213 # Create a sheet for the puzzle
214 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
216 # Update the database with the URL of the sheet
217 item['sheet_url'] = sheet['url']
218 puzzle_table.put_item(Item=item)
220 # Message the channel with the URL of the puzzle's sheet
221 turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
222 text="Sheet created for this puzzle: {}"
223 .format(sheet['url']))
225 hunts_table = turb.db.Table('hunts')
226 response = hunts_table.scan(
227 FilterExpression='hunt_id = :hunt_id',
228 ExpressionAttributeValues={':hunt_id': hunt_id}
231 if 'Items' in response:
233 hunt_channel_id = response['Items'][0]['channel_id']
235 # Find all members of the hunt channel
236 members = turbot.slack.slack_channel_members(turb.slack_client,
239 # Filter out Turbot's own ID to avoid inviting itself
240 members = [m for m in members if m != TURBOT_USER_ID]
242 turb.slack_client.chat_postMessage(
243 channel=puzzle_channel_id,
244 text="Inviting all members from the hunt channel: {}"
247 # Invite those members to the puzzle channel (in chunks of 500)
249 while cursor < len(members):
250 turb.slack_client.conversations_invite(
251 channel=puzzle_channel_id,
252 users=members[cursor:cursor + 500])
255 return lambda_success
257 def channel_created(turb, event):
258 print("In channel_created with event: {}".format(str(event)))
260 channel = event['channel']
261 channel_id = channel['id']
262 channel_name = channel['name']
263 creator = channel['creator']
265 # Ignore any channels that turbot didn't create
266 if creator != TURBOT_USER_ID:
267 print("channel_created: Not a turbot-created channel. Exiting.")
268 return lambda_success
270 # The presence of a hyphen determines whether this is a puzzle
271 # channel or a hunt channel.
272 if '-' in channel_name:
273 return puzzle_channel_created(turb, channel_name, channel_id)
275 return hunt_channel_created(turb, channel_name, channel_id)
277 events['channel_created'] = channel_created