]> git.cworth.org Git - turbot/blob - turbot/events.py
Drop handling of a "placeholder" value for channel_id
[turbot] / turbot / events.py
1 from turbot.blocks import (
2     section_block, text_block, button_block, actions_block
3 )
4 import turbot.sheets
5 import turbot.slack
6
7 TURBOT_USER_ID = 'U01B9QM4P9R'
8
9 events = {}
10
11 lambda_success = {'statusCode': 200}
12 lambda_error = {'statusCode': 400}
13
14 def hunt_block(hunt):
15     name = hunt['name']
16     channel_id = hunt['channel_id']
17
18     text = "{}: <#{}>".format(name, channel_id)
19
20     return section_block(text_block(text))
21
22 def home(turb, user_id):
23     """Returns a view to be published as the turbot home tab for user_id
24
25     The return value is a dictionary suitable to be published to the
26     Slack views_publish API."""
27
28     # Behave cleanly if there is no hunts table at all yet.
29     try:
30         response = turb.db.Table("hunts").scan()
31         hunts = response['Items']
32     except Exception:
33         hunts = []
34
35     return {
36         "type": "home",
37         "blocks": [
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"))
41         ]
42     }
43
44 def app_home_opened(turb, event):
45     """Handler for the app_home_opened event
46
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."""
49
50     user_id = event['user']
51     view = home(turb, user_id)
52     turb.slack_client.views_publish(user_id=user_id, view=view)
53     return lambda_success
54
55 events['app_home_opened'] = app_home_opened
56
57 def hunt_channel_created(turb, channel_name, channel_id):
58     """Creates sheet and a DynamoDB table for a newly-created hunt channel"""
59
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},
65         ConsistentRead=True
66     )
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")
70         return lambda_error
71
72     item = response['Item']
73
74     if 'sheet_url' in item:
75         print("Info: channel_id {} already has sheet_url {}. Exiting."
76               .format(channel_id, item['sheet_url']))
77         return lambda_success
78
79     # Remove any None items from our item before updating
80     if not item['url']:
81         del item['url']
82
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)
89
90     # Also, let the channel users know what we are up to
91     turb.slack_client.chat_postMessage(
92         channel=channel_id,
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.")
95
96     # Create a sheet for the channel
97     sheet = turbot.sheets.sheets_create(turb, channel_name)
98
99     # Update the database with the URL of the sheet
100     item['sheet_url'] = sheet['url']
101     hunts_table.put_item(Item=item)
102
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']))
107
108     # Create a database table for this hunt's puzzles
109     table = turb.db.create_table(
110         TableName=channel_name,
111         KeySchema=[
112             {'AttributeName': 'channel_id', 'KeyType': 'HASH'}
113         ],
114         AttributeDefinitions=[
115             {'AttributeName': 'channel_id', 'AttributeType': 'S'}
116         ],
117         ProvisionedThroughput={
118             'ReadCapacityUnits': 5,
119             'WriteCapacityUnits': 5
120         }
121     )
122
123     # Wait until the table exists
124     table.meta.client.get_waiter('table_exists').wait(TableName=channel_name)
125
126     # Mark the hunt as active in the database
127     item['active'] = True
128     hunts_table.put_item(Item=item)
129
130     # Message the hunt channel that the database is ready
131     turb.slack_client.chat_postMessage(
132         channel=channel_id,
133         text="Thank you for waiting. This hunt is now ready to begin! "
134         + "Use `/puzzle` to create puzzles for the hunt.")
135
136     return lambda_success
137
138 def puzzle_channel_created(turb, puzzle_channel_name, puzzle_channel_id):
139     """Creates sheet and invites user for a newly-created puzzle channel"""
140
141     hunt_id = puzzle_channel_name.split('-')[0]
142
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},
148         ConsistentRead=True
149     )
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")
154         return lambda_error
155
156     item = response['Item']
157
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
162
163     # Remove any None items from our item before updating
164     if not item['url']:
165         del item['url']
166
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)
173
174     # Create a sheet for the puzzle
175     sheet = turbot.sheets.sheets_create_for_puzzle(turb, puzzle_channel_name)
176
177     # Update the database with the URL of the sheet
178     item['sheet_url'] = sheet['url']
179     puzzle_table.put_item(Item=item)
180
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']))
185
186     hunts_table = turb.db.Table('hunts')
187     response = hunts_table.scan(
188         FilterExpression='hunt_id = :hunt_id',
189         ExpressionAttributeValues={':hunt_id': hunt_id}
190     )
191
192     if 'Items' in response:
193
194         hunt_channel_id = response['Items'][0]['channel_id']
195
196         # Find all members of the hunt channel
197         members = turbot.slack.slack_channel_members(turb.slack_client,
198                                                      hunt_channel_id)
199
200         # Filter out Turbot's own ID to avoid inviting itself
201         members = [m for m in members if m != TURBOT_USER_ID]
202
203         turb.slack_client.chat_postMessage(
204             channel=puzzle_channel_id,
205             text="Inviting all members from the hunt channel:  {}"
206             .format(hunt_id))
207
208         # Invite those members to the puzzle channel (in chunks of 500)
209         cursor = 0
210         while cursor < len(members):
211             turb.slack_client.conversations_invite(
212                 channel=puzzle_channel_id,
213                 users=members[cursor:cursor + 500])
214             cursor += 500
215
216     return lambda_success
217
218 def channel_created(turb, event):
219     print("In channel_created with event: {}".format(str(event)))
220
221     channel = event['channel']
222     channel_id = channel['id']
223     channel_name = channel['name']
224     creator = channel['creator']
225
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
230
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)
235     else:
236         return hunt_channel_created(turb, channel_name, channel_id)
237
238 events['channel_created'] = channel_created