]> git.cworth.org Git - turbot/blob - turbot/events.py
Add a list of puzzles under each hunt on the Turbot home tab
[turbot] / turbot / events.py
1 from turbot.blocks import (
2     section_block, text_block, button_block, actions_block, divider_block
3 )
4 import turbot.sheets
5 import turbot.slack
6 import itertools
7
8 TURBOT_USER_ID = 'U01B9QM4P9R'
9
10 events = {}
11
12 lambda_success = {'statusCode': 200}
13 lambda_error = {'statusCode': 400}
14
15 def puzzle_block(puzzle):
16     name = puzzle['name']
17     status = puzzle['status']
18     channel_id = puzzle['channel_id']
19     status_emoji = ''
20
21     if status == 'solved':
22         status_emoji = ":ballot_box_with_check:"
23     else:
24         status_emoji = ":white_square:"
25
26     puzzle_text = "{} {}: <#{}>".format(status_emoji, name, channel_id)
27
28     return section_block(text_block(puzzle_text))
29
30 def hunt_block(turb, hunt):
31     name = hunt['name']
32     hunt_id = hunt['hunt_id']
33     channel_id = hunt['channel_id']
34
35     response = turb.db.Table(hunt_id).scan()
36     puzzles = response['Items']
37
38     hunt_text = "*{}*: <#{}>".format(name, channel_id)
39
40     return [
41         section_block(text_block(hunt_text)),
42         *[puzzle_block(puzzle) for puzzle in puzzles],
43         divider_block()
44     ]
45
46 def home(turb, user_id):
47     """Returns a view to be published as the turbot home tab for user_id
48
49     The return value is a dictionary suitable to be published to the
50     Slack views_publish API."""
51
52     # Behave cleanly if there is no hunts table at all yet.
53     try:
54         response = turb.db.Table("hunts").scan()
55         hunts = response['Items']
56     except Exception:
57         hunts = []
58
59     hunt_blocks = []
60     for hunt in hunts:
61         if hunt['active']:
62             hunt_blocks += hunt_block(turb, hunt)
63
64     return {
65         "type": "home",
66         "blocks": [
67             section_block(text_block("*Active hunts*")),
68             divider_block(),
69             * hunt_blocks,
70             actions_block(button_block("New hunt", "new_hunt"))
71         ]
72     }
73
74 def app_home_opened(turb, event):
75     """Handler for the app_home_opened event
76
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."""
79
80     user_id = event['user']
81     view = home(turb, user_id)
82     turb.slack_client.views_publish(user_id=user_id, view=view)
83     return lambda_success
84
85 events['app_home_opened'] = app_home_opened
86
87 def hunt_channel_created(turb, channel_name, channel_id):
88     """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
89
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},
95         ConsistentRead=True
96     )
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")
100         return lambda_error
101
102     item = response['Item']
103
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
108
109     # Remove any None items from our item before updating
110     if not item['url']:
111         del item['url']
112
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)
119
120     # Also, let the channel users know what we are up to
121     turb.slack_client.chat_postMessage(
122         channel=channel_id,
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.")
125
126     # Create a sheet for the channel
127     sheet = turbot.sheets.sheets_create(turb, channel_name)
128
129     # Update the database with the URL of the sheet
130     item['sheet_url'] = sheet['url']
131     hunts_table.put_item(Item=item)
132
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']))
137
138     # Create a database table for this hunt's puzzles
139     table = turb.db.create_table(
140         TableName=channel_name,
141         KeySchema=[
142             {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
143         ],
144         AttributeDefinitions=[
145             {'AttributeName': 'channel_id', 'AttributeType': 'S'}
146         ],
147         ProvisionedThroughput={
148             'ReadCapacityUnits': 5,
149             'WriteCapacityUnits': 5
150         }
151     )
152
153     # Wait until the table exists
154     table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
155
156     # Mark the hunt as active in the database
157     item['active'] = True
158     hunts_table.put_item(Item=item)
159
160     # Message the hunt channel that the database is ready
161     turb.slack_client.chat_postMessage(
162         channel=channel_id,
163         text="Thank you for waiting. This hunt is now ready to begin! "
164         + "Use `/puzzle` to create puzzles for the hunt.")
165
166     return lambda_success
167
168 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
169     """Creates sheet and invites user for a newly-created puzzle channel"""
170
171     hunt_id = puzzle_channel_name.split('-')[0]
172
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},
178         ConsistentRead=True
179     )
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")
184         return lambda_error
185
186     item = response['Item']
187
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
192
193     # Remove any None items from our item before updating
194     if not item['url']:
195         del item['url']
196
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)
203
204     # Create a sheet for the puzzle
205     sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
206
207     # Update the database with the URL of the sheet
208     item['sheet_url'] = sheet['url']
209     puzzle_table.put_item(Item=item)
210
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']))
215
216     hunts_table = turb.db.Table('hunts')
217     response = hunts_table.scan(
218         FilterExpression='hunt_id = :hunt_id',
219         ExpressionAttributeValues={':hunt_id': hunt_id}
220     )
221
222     if 'Items' in response:
223
224         hunt_channel_id = response['Items'][0]['channel_id']
225
226         # Find all members of the hunt channel
227         members = turbot.slack.slack_channel_members(turb.slack_client,
228                                                      hunt_channel_id)
229
230         # Filter out Turbot's own ID to avoid inviting itself
231         members = [m for m in members if m != TURBOT_USER_ID]
232
233         turb.slack_client.chat_postMessage(
234             channel=puzzle_channel_id,
235             text="Inviting all members from the hunt channel:  {}"
236             .format(hunt_id))
237
238         # Invite those members to the puzzle channel (in chunks of 500)
239         cursor = 0
240         while cursor < len(members):
241             turb.slack_client.conversations_invite(
242                 channel=puzzle_channel_id,
243                 users=members[cursor:cursor + 500])
244             cursor += 500
245
246     return lambda_success
247
248 def channel_created(turb, event):
249     print("In channel_created with event: {}".format(str(event)))
250
251     channel = event['channel']
252     channel_id = channel['id']
253     channel_name = channel['name']
254     creator = channel['creator']
255
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
260
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)
265     else:
266         return hunt_channel_created(turb, channel_name, channel_id)
267
268 events['channel_created'] = channel_created