1 from turbot.blocks import (
2 section_block, text_block, button_block, actions_block
7 TURBOT_USER_ID = 'U01B9QM4P9R'
11 lambda_success = {'statusCode': 200}
12 lambda_error = {'statusCode': 400}
16 channel_id = hunt['channel_id']
18 text = "{}: ".format(name)
20 if (channel_id.startswith("placeholder-")):
21 text += "[Slack channel is still being created. Please wait.]"
23 text += "<#{}>".format(channel_id)
25 return section_block(text_block(text))
27 def home(turb, user_id):
28 """Returns a view to be published as the turbot home tab for user_id
30 The return value is a dictionary suitable to be published to the
31 Slack views_publish API."""
33 # Behave cleanly if there is no hunts table at all yet.
35 response = turb.db.Table("hunts").scan()
36 hunts = response['Items']
43 section_block(text_block("*Active hunts*")),
44 *[hunt_block(hunt) for hunt in hunts if hunt['active']],
45 actions_block(button_block("New hunt", "new_hunt"))
49 def app_home_opened(turb, event):
50 """Handler for the app_home_opened event
52 This event occurs when a user visits the home tab for the turbot app.
53 In response to this event we need to publish a view for the user."""
55 user_id = event['user']
56 view = home(turb, user_id)
57 turb.slack_client.views_publish(user_id=user_id, view=view)
60 events['app_home_opened'] = app_home_opened
62 def hunt_channel_created(turb, channel_name, channel_id):
63 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
65 # First see if we can find an entry for this hunt in the database.
66 # If not, simply return an error and let Slack retry
67 hunts_table = turb.db.Table("hunts")
68 response = hunts_table.get_item(
69 Key={'channel_id': channel_id},
72 if 'Item' not in response:
73 print("Warning: Cannot find channel_id {} in hunts table. "
74 .format(channel_id) + "Letting Slack retry this event")
77 item = response['Item']
79 if 'sheet_url' in item:
80 print("Info: channel_id {} already has sheet_url {}. Exiting."
81 .format(channel_id, item['sheet_url']))
84 # Remove any None items from our item before updating
88 # Before launching into sheet creation, indicate that we're doing this
89 # in the database. This way, if we take too long to create the sheet
90 # and Slack retries the event, that next event will see this 'pending'
91 # string and cleanly return (eliminating all future retries).
92 item['sheet_url'] = 'pending'
93 hunts_table.put_item(Item=item)
95 # Also, let the channel users know what we are up to
96 turb.slack_client.chat_postMessage(
98 text="Welcome to the channel for the {} hunt! ".format(item['name'])
99 + "Please wait a minute or two while I create some backend resources.")
101 # Create a sheet for the channel
102 sheet = turbot.sheets.sheets_create(turb, channel_name)
104 # Update the database with the URL of the sheet
105 item['sheet_url'] = sheet['url']
106 hunts_table.put_item(Item=item)
108 # Message the channel with the URL of the sheet
109 turb.slack_client.chat_postMessage(channel=channel_id,
110 text="Sheet created for this hunt: {}"
111 .format(sheet['url']))
113 # Create a database table for this hunt's puzzles
114 table = turb.db.create_table(
115 TableName=channel_name,
117 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
119 AttributeDefinitions=[
120 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
122 ProvisionedThroughput={
123 'ReadCapacityUnits': 5,
124 'WriteCapacityUnits': 5
128 # Wait until the table exists
129 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
131 # Mark the hunt as active in the database
132 item['active'] = True
133 hunts_table.put_item(Item=item)
135 # Message the hunt channel that the database is ready
136 turb.slack_client.chat_postMessage(
138 text="Thank you for waiting. This hunt is now ready to begin! "
139 + "Use `/puzzle` to create puzzles for the hunt.")
141 return lambda_success
143 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
144 """Creates sheet and invites user for a newly-created puzzle channel"""
146 hunt_id = puzzle_channel_name.split('-')[0]
148 # First see if we can find an entry for this puzzle in the database.
149 # If not, simply return an error and let Slack retry
150 puzzle_table = turb.db.Table(hunt_id)
151 response = puzzle_table.get_item(
152 Key={'channel_id': puzzle_channel_id},
155 if 'Item' not in response:
156 print("Warning: Cannot find channel_id {} in {} table. "
157 .format(puzzle_channel_id, hunt_id)
158 + "Letting Slack retry this event")
161 item = response['Item']
163 if 'sheet_url' in item:
164 print("Info: channel_id {} already has sheet_url {}. Exiting."
165 .format(puzzle_channel_id, item['sheet_url']))
166 return lambda_success
168 # Remove any None items from our item before updating
172 # Before launching into sheet creation, indicate that we're doing this
173 # in the database. This way, if we take too long to create the sheet
174 # and Slack retries the event, that next event will see this 'pending'
175 # string and cleanly return (eliminating all future retries).
176 item['sheet_url'] = 'pending'
177 puzzle_table.put_item(Item=item)
179 # Create a sheet for the puzzle
180 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
182 # Update the database with the URL of the sheet
183 item['sheet_url'] = sheet['url']
184 puzzle_table.put_item(Item=item)
186 # Message the channel with the URL of the puzzle's sheet
187 turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
188 text="Sheet created for this puzzle: {}"
189 .format(sheet['url']))
191 hunts_table = turb.db.Table('hunts')
192 response = hunts_table.scan(
193 FilterExpression='hunt_id = :hunt_id',
194 ExpressionAttributeValues={':hunt_id': hunt_id},
197 if 'Items' in response:
199 hunt_channel_id = response['Items'][0]['channel_id']
201 # Find all members of the hunt channel
202 members = turbot.slack.slack_channel_members(turb.slack_client,
205 # Filter out Turbot's own ID to avoid inviting itself
206 members = [m for m in members if m != TURBOT_USER_ID]
208 turb.slack_client.chat_postMessage(
209 channel=puzzle_channel_id,
210 text="Inviting all members from the hunt channel: {}"
213 # Invite those members to the puzzle channel (in chunks of 500)
215 while cursor < len(members):
216 turb.slack_client.conversations_invite(
217 channel=puzzle_channel_id,
218 users=members[cursor:cursor + 500])
221 return lambda_success
223 def channel_created(turb, event):
224 print("In channel_created with event: {}".format(str(event)))
226 channel = event['channel']
227 channel_id = channel['id']
228 channel_name = channel['name']
229 creator = channel['creator']
231 # Ignore any channels that turbot didn't create
232 if creator != TURBOT_USER_ID:
233 print("channel_created: Not a turbot-created channel. Exiting.")
234 return lambda_success
236 # The presence of a hyphen determines whether this is a puzzle
237 # channel or a hunt channel.
238 if '-' in channel_name:
239 return puzzle_channel_created(turb, channel_name, channel_id)
241 return hunt_channel_created(turb, channel_name, channel_id)
243 events['channel_created'] = channel_created