]> git.cworth.org Git - turbot/blob - turbot/events.py
Add a slack_send_message function
[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 from turbot.slack import slack_send_message
7
8 TURBOT_USER_ID = 'U01B9QM4P9R'
9
10 events = {}
11
12 lambda_success = {'statusCode': 200}
13 lambda_error = {'statusCode': 400}
14
15 def channel_url(channel_id):
16     return "https://halibutthatbass.slack.com/archives/{}".format(channel_id)
17
18 def puzzle_block(puzzle):
19     name = puzzle['name']
20     status = puzzle['status']
21     solution = puzzle['solution']
22     channel_id = puzzle['channel_id']
23     url = puzzle.get('url', None)
24     sheet_url = puzzle.get('sheet_url', None)
25     state = puzzle.get('state', None)
26     status_emoji = ''
27     solution_str = ''
28
29     if status == 'solved':
30         status_emoji = ":ballot_box_with_check:"
31     else:
32         status_emoji = ":white_square:"
33
34     if len(solution):
35         solution_str = "*`" + '`, `'.join(solution) + "`*"
36
37     links = []
38     if url:
39         links.append("<{}|Puzzle>".format(url))
40     if sheet_url:
41         links.append("<{}|Sheet>".format(sheet_url))
42
43     state_str = ''
44     if state:
45         state_str = "\n{}".format(state)
46
47     puzzle_text = "{}{} <{}|{}> ({}){}".format(
48         status_emoji, solution_str,
49         channel_url(channel_id), name,
50         ', '.join(links), state_str
51     )
52
53     return section_block(text_block(puzzle_text))
54
55 def hunt_block(turb, hunt):
56     name = hunt['name']
57     hunt_id = hunt['hunt_id']
58     channel_id = hunt['channel_id']
59
60     response = turb.db.Table(hunt_id).scan()
61     puzzles = response['Items']
62
63     hunt_text = "*<{}|{}>*".format(channel_url(channel_id), name)
64
65     return [
66         section_block(text_block(hunt_text)),
67         *[puzzle_block(puzzle) for puzzle in puzzles],
68         divider_block()
69     ]
70
71 def home(turb, user_id):
72     """Returns a view to be published as the turbot home tab for user_id
73
74     The return value is a dictionary suitable to be published to the
75     Slack views_publish API."""
76
77     # Behave cleanly if there is no hunts table at all yet.
78     try:
79         response = turb.db.Table("hunts").scan()
80         hunts = response['Items']
81     except Exception:
82         hunts = []
83
84     hunt_blocks = []
85     for hunt in hunts:
86         if hunt['active']:
87             hunt_blocks += hunt_block(turb, hunt)
88
89     return {
90         "type": "home",
91         "blocks": [
92             section_block(text_block("*Active hunts*")),
93             divider_block(),
94             * hunt_blocks,
95             actions_block(button_block("New hunt", "new_hunt"))
96         ]
97     }
98
99 def app_home_opened(turb, event):
100     """Handler for the app_home_opened event
101
102     This event occurs when a user visits the home tab for the turbot app.
103     In response to this event we need to publish a view for the user."""
104
105     user_id = event['user']
106     view = home(turb, user_id)
107     turb.slack_client.views_publish(user_id=user_id, view=view)
108     return lambda_success
109
110 events['app_home_opened'] = app_home_opened
111
112 def hunt_channel_created(turb, channel_name, channel_id):
113     """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
114
115     # First see if we can find an entry for this hunt in the database.
116     # If not, simply return an error and let Slack retry
117     hunts_table = turb.db.Table("hunts")
118     response = hunts_table.get_item(
119         Key={'channel_id': channel_id},
120         ConsistentRead=True
121     )
122     if 'Item' not in response:
123         print("Warning: Cannot find channel_id {} in hunts table. "
124               .format(channel_id) + "Letting Slack retry this event")
125         return lambda_error
126
127     item = response['Item']
128
129     if 'sheet_url' in item:
130         print("Info: channel_id {} already has sheet_url {}. Exiting."
131               .format(channel_id, item['sheet_url']))
132         return lambda_success
133
134     # Remove any None items from our item before updating
135     if not item['url']:
136         del item['url']
137
138     # Before launching into sheet creation, indicate that we're doing this
139     # in the database. This way, if we take too long to create the sheet
140     # and Slack retries the event, that next event will see this 'pending'
141     # string and cleanly return (eliminating all future retries).
142     item['sheet_url'] = 'pending'
143     hunts_table.put_item(Item=item)
144
145     # Also, let the channel users know what we are up to
146     slack_send_message(
147         turb.slack_client, channel_id,
148         "Welcome to the channel for the {} hunt! ".format(item['name'])
149         + "Please wait a minute or two while I create some backend resources.")
150
151     # Create a sheet for the channel
152     sheet = turbot.sheets.sheets_create(turb, channel_name)
153
154     # Update the database with the URL of the sheet
155     item['sheet_url'] = sheet['url']
156     hunts_table.put_item(Item=item)
157
158     # Message the channel with the URL of the sheet
159     slack_send_message(turb.slack_client, channel_id,
160                        "Sheet created for this hunt: {}".format(sheet['url']))
161
162     # Create a database table for this hunt's puzzles
163     table = turb.db.create_table(
164         TableName=channel_name,
165         KeySchema=[
166             {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
167         ],
168         AttributeDefinitions=[
169             {'AttributeName': 'channel_id', 'AttributeType': 'S'}
170         ],
171         ProvisionedThroughput={
172             'ReadCapacityUnits': 5,
173             'WriteCapacityUnits': 5
174         }
175     )
176
177     # Wait until the table exists
178     table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
179
180     # Mark the hunt as active in the database
181     item['active'] = True
182     hunts_table.put_item(Item=item)
183
184     # Message the hunt channel that the database is ready
185     slack_send_message(
186         turb.slack_client, channel_id,
187         "Thank you for waiting. This hunt is now ready to begin! "
188         + "Use `/puzzle` to create puzzles for the hunt.")
189
190     return lambda_success
191
192 def set_channel_description(turb, puzzle):
193     channel_id = puzzle['channel_id']
194     description = puzzle['name']
195     url = puzzle.get('url', None)
196     sheet_url = puzzle.get('sheet_url', None)
197
198     links = []
199     if url:
200         links.append("<{}|Puzzle>".format(url))
201     if sheet_url:
202         links.append("<{}|Sheet>".format(sheet_url))
203
204     if len(links):
205         description += "({})".format(', '.join(links))
206
207     turb.slack_client.conversations_setPurpose(channel=channel_id,
208                                                purpose=description)
209     turb.slack_client.conversations_setTopic(channel=channel_id,
210                                              topic=description)
211
212 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
213     """Creates sheet and invites user for a newly-created puzzle channel"""
214
215     hunt_id = puzzle_channel_name.split('-')[0]
216
217     # First see if we can find an entry for this puzzle in the database.
218     # If not, simply return an error and let Slack retry
219     puzzle_table = turb.db.Table(hunt_id)
220     response = puzzle_table.get_item(
221         Key={'channel_id': puzzle_channel_id},
222         ConsistentRead=True
223     )
224     if 'Item' not in response:
225         print("Warning: Cannot find channel_id {} in {} table. "
226               .format(puzzle_channel_id, hunt_id)
227               + "Letting Slack retry this event")
228         return lambda_error
229
230     item = response['Item']
231
232     if 'sheet_url' in item:
233         print("Info: channel_id {} already has sheet_url {}. Exiting."
234               .format(puzzle_channel_id, item['sheet_url']))
235         return lambda_success
236
237     # Remove any None items from our item before updating
238     if not item['url']:
239         del item['url']
240
241     # Before launching into sheet creation, indicate that we're doing this
242     # in the database. This way, if we take too long to create the sheet
243     # and Slack retries the event, that next event will see this 'pending'
244     # string and cleanly return (eliminating all future retries).
245     item['sheet_url'] = 'pending'
246     puzzle_table.put_item(Item=item)
247
248     # Create a sheet for the puzzle
249     sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
250
251     # Update the database with the URL of the sheet
252     item['sheet_url'] = sheet['url']
253     puzzle_table.put_item(Item=item)
254
255     # Get the new sheet_url into the channel description
256     set_channel_description(turb, item)
257
258     hunts_table = turb.db.Table('hunts')
259     response = hunts_table.scan(
260         FilterExpression='hunt_id = :hunt_id',
261         ExpressionAttributeValues={':hunt_id': hunt_id}
262     )
263
264     if 'Items' in response:
265
266         hunt_channel_id = response['Items'][0]['channel_id']
267
268         # Find all members of the hunt channel
269         members = turbot.slack.slack_channel_members(turb.slack_client,
270                                                      hunt_channel_id)
271
272         # Filter out Turbot's own ID to avoid inviting itself
273         members = [m for m in members if m != TURBOT_USER_ID]
274
275         slack_send_message(
276             turb.slack_client, puzzle_channel_id,
277             "Inviting all members from the hunt channel:  {}"
278             .format(hunt_id))
279
280         # Invite those members to the puzzle channel (in chunks of 500)
281         cursor = 0
282         while cursor < len(members):
283             turb.slack_client.conversations_invite(
284                 channel=puzzle_channel_id,
285                 users=members[cursor:cursor + 500])
286             cursor += 500
287
288     return lambda_success
289
290 def channel_created(turb, event):
291     print("In channel_created with event: {}".format(str(event)))
292
293     channel = event['channel']
294     channel_id = channel['id']
295     channel_name = channel['name']
296     creator = channel['creator']
297
298     # Ignore any channels that turbot didn't create
299     if creator != TURBOT_USER_ID:
300         print("channel_created: Not a turbot-created channel. Exiting.")
301         return lambda_success
302
303     # The presence of a hyphen determines whether this is a puzzle
304     # channel or a hunt channel.
305     if '-' in channel_name:
306         return puzzle_channel_created(turb, channel_name, channel_id)
307     else:
308         return hunt_channel_created(turb, channel_name, channel_id)
309
310     
311
312 events['channel_created'] = channel_created