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 puzzle_block(puzzle):
17 status = puzzle['status']
18 channel_id = puzzle['channel_id']
21 if status == 'solved':
22 status_emoji = ":ballot_box_with_check:"
24 status_emoji = ":white_square:"
26 puzzle_text = "{} {}: <#{}>".format(status_emoji, name, channel_id)
28 return section_block(text_block(puzzle_text))
30 def hunt_block(turb, hunt):
32 hunt_id = hunt['hunt_id']
33 channel_id = hunt['channel_id']
35 response = turb.db.Table(hunt_id).scan()
36 puzzles = response['Items']
38 hunt_text = "*{}*: <#{}>".format(name, channel_id)
41 section_block(text_block(hunt_text)),
42 *[puzzle_block(puzzle) for puzzle in puzzles],
46 def home(turb, user_id):
47 """Returns a view to be published as the turbot home tab for user_id
49 The return value is a dictionary suitable to be published to the
50 Slack views_publish API."""
52 # Behave cleanly if there is no hunts table at all yet.
54 response = turb.db.Table("hunts").scan()
55 hunts = response['Items']
62 hunt_blocks += hunt_block(turb, hunt)
67 section_block(text_block("*Active hunts*")),
70 actions_block(button_block("New hunt", "new_hunt"))
74 def app_home_opened(turb, event):
75 """Handler for the app_home_opened event
77 This event occurs when a user visits the home tab for the turbot app.
78 In response to this event we need to publish a view for the user."""
80 user_id = event['user']
81 view = home(turb, user_id)
82 turb.slack_client.views_publish(user_id=user_id, view=view)
85 events['app_home_opened'] = app_home_opened
87 def hunt_channel_created(turb, channel_name, channel_id):
88 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
90 # First see if we can find an entry for this hunt in the database.
91 # If not, simply return an error and let Slack retry
92 hunts_table = turb.db.Table("hunts")
93 response = hunts_table.get_item(
94 Key={'channel_id': channel_id},
97 if 'Item' not in response:
98 print("Warning: Cannot find channel_id {} in hunts table. "
99 .format(channel_id) + "Letting Slack retry this event")
102 item = response['Item']
104 if 'sheet_url' in item:
105 print("Info: channel_id {} already has sheet_url {}. Exiting."
106 .format(channel_id, item['sheet_url']))
107 return lambda_success
109 # Remove any None items from our item before updating
113 # Before launching into sheet creation, indicate that we're doing this
114 # in the database. This way, if we take too long to create the sheet
115 # and Slack retries the event, that next event will see this 'pending'
116 # string and cleanly return (eliminating all future retries).
117 item['sheet_url'] = 'pending'
118 hunts_table.put_item(Item=item)
120 # Also, let the channel users know what we are up to
121 turb.slack_client.chat_postMessage(
123 text="Welcome to the channel for the {} hunt! ".format(item['name'])
124 + "Please wait a minute or two while I create some backend resources.")
126 # Create a sheet for the channel
127 sheet = turbot.sheets.sheets_create(turb, channel_name)
129 # Update the database with the URL of the sheet
130 item['sheet_url'] = sheet['url']
131 hunts_table.put_item(Item=item)
133 # Message the channel with the URL of the sheet
134 turb.slack_client.chat_postMessage(channel=channel_id,
135 text="Sheet created for this hunt: {}"
136 .format(sheet['url']))
138 # Create a database table for this hunt's puzzles
139 table = turb.db.create_table(
140 TableName=channel_name,
142 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
144 AttributeDefinitions=[
145 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
147 ProvisionedThroughput={
148 'ReadCapacityUnits': 5,
149 'WriteCapacityUnits': 5
153 # Wait until the table exists
154 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
156 # Mark the hunt as active in the database
157 item['active'] = True
158 hunts_table.put_item(Item=item)
160 # Message the hunt channel that the database is ready
161 turb.slack_client.chat_postMessage(
163 text="Thank you for waiting. This hunt is now ready to begin! "
164 + "Use `/puzzle` to create puzzles for the hunt.")
166 return lambda_success
168 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
169 """Creates sheet and invites user for a newly-created puzzle channel"""
171 hunt_id = puzzle_channel_name.split('-')[0]
173 # First see if we can find an entry for this puzzle in the database.
174 # If not, simply return an error and let Slack retry
175 puzzle_table = turb.db.Table(hunt_id)
176 response = puzzle_table.get_item(
177 Key={'channel_id': puzzle_channel_id},
180 if 'Item' not in response:
181 print("Warning: Cannot find channel_id {} in {} table. "
182 .format(puzzle_channel_id, hunt_id)
183 + "Letting Slack retry this event")
186 item = response['Item']
188 if 'sheet_url' in item:
189 print("Info: channel_id {} already has sheet_url {}. Exiting."
190 .format(puzzle_channel_id, item['sheet_url']))
191 return lambda_success
193 # Remove any None items from our item before updating
197 # Before launching into sheet creation, indicate that we're doing this
198 # in the database. This way, if we take too long to create the sheet
199 # and Slack retries the event, that next event will see this 'pending'
200 # string and cleanly return (eliminating all future retries).
201 item['sheet_url'] = 'pending'
202 puzzle_table.put_item(Item=item)
204 # Create a sheet for the puzzle
205 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
207 # Update the database with the URL of the sheet
208 item['sheet_url'] = sheet['url']
209 puzzle_table.put_item(Item=item)
211 # Message the channel with the URL of the puzzle's sheet
212 turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
213 text="Sheet created for this puzzle: {}"
214 .format(sheet['url']))
216 hunts_table = turb.db.Table('hunts')
217 response = hunts_table.scan(
218 FilterExpression='hunt_id = :hunt_id',
219 ExpressionAttributeValues={':hunt_id': hunt_id}
222 if 'Items' in response:
224 hunt_channel_id = response['Items'][0]['channel_id']
226 # Find all members of the hunt channel
227 members = turbot.slack.slack_channel_members(turb.slack_client,
230 # Filter out Turbot's own ID to avoid inviting itself
231 members = [m for m in members if m != TURBOT_USER_ID]
233 turb.slack_client.chat_postMessage(
234 channel=puzzle_channel_id,
235 text="Inviting all members from the hunt channel: {}"
238 # Invite those members to the puzzle channel (in chunks of 500)
240 while cursor < len(members):
241 turb.slack_client.conversations_invite(
242 channel=puzzle_channel_id,
243 users=members[cursor:cursor + 500])
246 return lambda_success
248 def channel_created(turb, event):
249 print("In channel_created with event: {}".format(str(event)))
251 channel = event['channel']
252 channel_id = channel['id']
253 channel_name = channel['name']
254 creator = channel['creator']
256 # Ignore any channels that turbot didn't create
257 if creator != TURBOT_USER_ID:
258 print("channel_created: Not a turbot-created channel. Exiting.")
259 return lambda_success
261 # The presence of a hyphen determines whether this is a puzzle
262 # channel or a hunt channel.
263 if '-' in channel_name:
264 return puzzle_channel_created(turb, channel_name, channel_id)
266 return hunt_channel_created(turb, channel_name, channel_id)
268 events['channel_created'] = channel_created