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