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