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, channel_id)
20 return section_block(text_block(text))
22 def home(turb, user_id):
23 """Returns a view to be published as the turbot home tab for user_id
25 The return value is a dictionary suitable to be published to the
26 Slack views_publish API."""
28 # Behave cleanly if there is no hunts table at all yet.
30 response = turb.db.Table("hunts").scan()
31 hunts = response['Items']
38 section_block(text_block("*Active hunts*")),
39 *[hunt_block(hunt) for hunt in hunts if hunt['active']],
40 actions_block(button_block("New hunt", "new_hunt"))
44 def app_home_opened(turb, event):
45 """Handler for the app_home_opened event
47 This event occurs when a user visits the home tab for the turbot app.
48 In response to this event we need to publish a view for the user."""
50 user_id = event['user']
51 view = home(turb, user_id)
52 turb.slack_client.views_publish(user_id=user_id, view=view)
55 events['app_home_opened'] = app_home_opened
57 def hunt_channel_created(turb, channel_name, channel_id):
58 """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
60 # First see if we can find an entry for this hunt in the database.
61 # If not, simply return an error and let Slack retry
62 hunts_table = turb.db.Table("hunts")
63 response = hunts_table.get_item(
64 Key={'channel_id': channel_id},
67 if 'Item' not in response:
68 print("Warning: Cannot find channel_id {} in hunts table. "
69 .format(channel_id) + "Letting Slack retry this event")
72 item = response['Item']
74 if 'sheet_url' in item:
75 print("Info: channel_id {} already has sheet_url {}. Exiting."
76 .format(channel_id, item['sheet_url']))
79 # Remove any None items from our item before updating
83 # Before launching into sheet creation, indicate that we're doing this
84 # in the database. This way, if we take too long to create the sheet
85 # and Slack retries the event, that next event will see this 'pending'
86 # string and cleanly return (eliminating all future retries).
87 item['sheet_url'] = 'pending'
88 hunts_table.put_item(Item=item)
90 # Also, let the channel users know what we are up to
91 turb.slack_client.chat_postMessage(
93 text="Welcome to the channel for the {} hunt! ".format(item['name'])
94 + "Please wait a minute or two while I create some backend resources.")
96 # Create a sheet for the channel
97 sheet = turbot.sheets.sheets_create(turb, channel_name)
99 # Update the database with the URL of the sheet
100 item['sheet_url'] = sheet['url']
101 hunts_table.put_item(Item=item)
103 # Message the channel with the URL of the sheet
104 turb.slack_client.chat_postMessage(channel=channel_id,
105 text="Sheet created for this hunt: {}"
106 .format(sheet['url']))
108 # Create a database table for this hunt's puzzles
109 table = turb.db.create_table(
110 TableName=channel_name,
112 {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
114 AttributeDefinitions=[
115 {'AttributeName': 'channel_id', 'AttributeType': 'S'}
117 ProvisionedThroughput={
118 'ReadCapacityUnits': 5,
119 'WriteCapacityUnits': 5
123 # Wait until the table exists
124 table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
126 # Mark the hunt as active in the database
127 item['active'] = True
128 hunts_table.put_item(Item=item)
130 # Message the hunt channel that the database is ready
131 turb.slack_client.chat_postMessage(
133 text="Thank you for waiting. This hunt is now ready to begin! "
134 + "Use `/puzzle` to create puzzles for the hunt.")
136 return lambda_success
138 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
139 """Creates sheet and invites user for a newly-created puzzle channel"""
141 hunt_id = puzzle_channel_name.split('-')[0]
143 # First see if we can find an entry for this puzzle in the database.
144 # If not, simply return an error and let Slack retry
145 puzzle_table = turb.db.Table(hunt_id)
146 response = puzzle_table.get_item(
147 Key={'channel_id': puzzle_channel_id},
150 if 'Item' not in response:
151 print("Warning: Cannot find channel_id {} in {} table. "
152 .format(puzzle_channel_id, hunt_id)
153 + "Letting Slack retry this event")
156 item = response['Item']
158 if 'sheet_url' in item:
159 print("Info: channel_id {} already has sheet_url {}. Exiting."
160 .format(puzzle_channel_id, item['sheet_url']))
161 return lambda_success
163 # Remove any None items from our item before updating
167 # Before launching into sheet creation, indicate that we're doing this
168 # in the database. This way, if we take too long to create the sheet
169 # and Slack retries the event, that next event will see this 'pending'
170 # string and cleanly return (eliminating all future retries).
171 item['sheet_url'] = 'pending'
172 puzzle_table.put_item(Item=item)
174 # Create a sheet for the puzzle
175 sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
177 # Update the database with the URL of the sheet
178 item['sheet_url'] = sheet['url']
179 puzzle_table.put_item(Item=item)
181 # Message the channel with the URL of the puzzle's sheet
182 turb.slack_client.chat_postMessage(channel=puzzle_channel_id,
183 text="Sheet created for this puzzle: {}"
184 .format(sheet['url']))
186 hunts_table = turb.db.Table('hunts')
187 response = hunts_table.scan(
188 FilterExpression='hunt_id = :hunt_id',
189 ExpressionAttributeValues={':hunt_id': hunt_id}
192 if 'Items' in response:
194 hunt_channel_id = response['Items'][0]['channel_id']
196 # Find all members of the hunt channel
197 members = turbot.slack.slack_channel_members(turb.slack_client,
200 # Filter out Turbot's own ID to avoid inviting itself
201 members = [m for m in members if m != TURBOT_USER_ID]
203 turb.slack_client.chat_postMessage(
204 channel=puzzle_channel_id,
205 text="Inviting all members from the hunt channel: {}"
208 # Invite those members to the puzzle channel (in chunks of 500)
210 while cursor < len(members):
211 turb.slack_client.conversations_invite(
212 channel=puzzle_channel_id,
213 users=members[cursor:cursor + 500])
216 return lambda_success
218 def channel_created(turb, event):
219 print("In channel_created with event: {}".format(str(event)))
221 channel = event['channel']
222 channel_id = channel['id']
223 channel_name = channel['name']
224 creator = channel['creator']
226 # Ignore any channels that turbot didn't create
227 if creator != TURBOT_USER_ID:
228 print("channel_created: Not a turbot-created channel. Exiting.")
229 return lambda_success
231 # The presence of a hyphen determines whether this is a puzzle
232 # channel or a hunt channel.
233 if '-' in channel_name:
234 return puzzle_channel_created(turb, channel_name, channel_id)
236 return hunt_channel_created(turb, channel_name, channel_id)
238 events['channel_created'] = channel_created