forked from F3Nation-Community/slackblast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
432 lines (390 loc) · 14.8 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import logging
from decouple import config
from fastapi import FastAPI, Request
from slack_bolt.adapter.fastapi.async_handler import AsyncSlackRequestHandler
from slack_bolt.async_app import AsyncApp
import datetime
from datetime import datetime, timezone, timedelta
import json
# def get_categories():
# with open('categories.json') as c:
# data = json.load(c)
# return data
# def formatted_categories(filteredcats):
# opts = []
# for cat in filteredcats:
# x = {
# "text": {
# "type": "plain_text",
# "text": cat["name"]
# },
# "value": str(cat["id"])
# }
# opts.append(x)
# return opts
logging.basicConfig(level=logging.DEBUG)
#categories = []
slack_app = AsyncApp(
token=config('SLACK_BOT_TOKEN'),
signing_secret=config('SLACK_SIGNING_SECRET')
)
app_handler = AsyncSlackRequestHandler(slack_app)
#categories = get_categories()
@slack_app.middleware # or app.use(log_request)
async def log_request(logger, body, next):
logger.debug(body)
return await next()
@slack_app.event("app_mention")
async def event_test(body, say, logger):
logger.info(body)
await say("What's up yo?")
@slack_app.event("message")
async def handle_message():
pass
def get_channel_id_and_name(body, logger):
user_id = body.get("user_id")
# Get "text" value which is everything after the /slash-command
# e.g. /slackblast #our-aggregate-backblast-channel
# then text would be "#our-aggregate-backblast-channel" if /slash command is not encoding
# but encoding needs to be checked so it will be "<#C01V75UFE56|our-aggregate-backblast-channel>" instead
channel_name = body.get("text") or ''
channel_id = ''
try:
channel_id = channel_name.split('|')[0].split('#')[1]
channel_name = channel_name.split('|')[1].split('>')[0]
except IndexError as ierr:
logger.error('Bad user input - cannot parse channel id')
except Exception as error:
logger.error('User did not pass in any input')
return channel_id, channel_name
@slack_app.command("/slackblast")
@slack_app.command("/backblast")
async def command(ack, body, respond, client, logger):
await ack()
today = datetime.now(timezone.utc).astimezone()
today = today - timedelta(hours = 6)
datestring = today.strftime("%Y-%m-%d")
user_id = body.get("user_id")
# Figure out where user sent slashcommand from to set current channel id and name
is_direct_message = body.get("channel_name") == 'directmessage'
current_channel_id = user_id if is_direct_message else body.get("channel_id")
current_channel_name = "Me" if is_direct_message else body.get("channel_id")
# The channel where user submitted the slashcommand
current_channel_option = {
"text": {
"type": "plain_text",
"text": "Current Channel"
},
"value": current_channel_id
}
# In .env, CHANNEL=USER
channel_me_option = {
"text": {
"type": "plain_text",
"text": "Me"
},
"value": user_id
}
# In .env, CHANNEL=THE_AO
channel_the_ao_option = {
"text": {
"type": "plain_text",
"text": "The AO Channel"
},
"value": "THE_AO"
}
# In .env, CHANNEL=<channel-id>
channel_configured_ao_option = {
"text": {
"type": "plain_text",
"text": "Preconfigured Backblast Channel"
},
"value": config('CHANNEL', default=current_channel_id)
}
# User may have typed /slackblast #<channel-name> AND
# slackblast slashcommand is checked to escape channels.
# Escape channels, users, and links sent to your app
# Escaped: <#C1234|general>
channel_id, channel_name = get_channel_id_and_name(body, logger)
channel_user_specified_channel_option = {
"text": {
"type": "plain_text",
"text": '# ' + channel_name
},
"value": channel_id
}
channel_options = []
# figure out which channel should be default/initial and then remaining operations
if channel_id:
initial_channel_option = channel_user_specified_channel_option
channel_options.append(channel_user_specified_channel_option)
channel_options.append(current_channel_option)
channel_options.append(channel_me_option)
channel_options.append(channel_the_ao_option)
channel_options.append(channel_configured_ao_option)
elif config('CHANNEL', default=current_channel_id) == 'USER':
initial_channel_option = channel_me_option
channel_options.append(channel_me_option)
channel_options.append(current_channel_option)
channel_options.append(channel_the_ao_option)
elif config('CHANNEL', default=current_channel_id) == 'THE_AO':
initial_channel_option = channel_the_ao_option
channel_options.append(channel_the_ao_option)
channel_options.append(current_channel_option)
channel_options.append(channel_me_option)
elif config('CHANNEL', default=current_channel_id) == current_channel_id:
# if there is no .env CHANNEL value, use default of current channel
initial_channel_option = current_channel_option
channel_options.append(current_channel_option)
channel_options.append(channel_me_option)
channel_options.append(channel_the_ao_option)
else:
# Default to using the .env CHANNEL value which at this point must be a channel id
initial_channel_option = channel_configured_ao_option
channel_options.append(channel_configured_ao_option)
channel_options.append(current_channel_option)
channel_options.append(channel_me_option)
channel_options.append(channel_the_ao_option)
res = await client.views_open(
trigger_id=body["trigger_id"],
view={
"type": "modal",
"callback_id": "backblast-id",
"title": {
"type": "plain_text",
"text": "Create a Backblast"
},
"submit": {
"type": "plain_text",
"text": "Submit"
},
"blocks": [
{
"type": "input",
"block_id": "title",
"element": {
"type": "plain_text_input",
"action_id": "title",
"placeholder": {
"type": "plain_text",
"text": "Snarky Title?"
}
},
"label": {
"type": "plain_text",
"text": "Title"
}
},
{
"type": "input",
"block_id": "the_ao",
"element": {
"type": "channels_select",
"placeholder": {
"type": "plain_text",
"text": "Select the AO",
"emoji": True
},
"action_id": "channels_select-action"
},
"label": {
"type": "plain_text",
"text": "The AO",
"emoji": True
}
},
{
"type": "input",
"block_id": "date",
"element": {
"type": "datepicker",
"initial_date": datestring,
"placeholder": {
"type": "plain_text",
"text": "Select a date",
"emoji": True
},
"action_id": "datepicker-action"
},
"label": {
"type": "plain_text",
"text": "Workout Date",
"emoji": True
}
},
{
"type": "input",
"block_id": "the_q",
"element": {
"type": "users_select",
"placeholder": {
"type": "plain_text",
"text": "Tag the Q",
"emoji": True
},
"action_id": "users_select-action"
},
"label": {
"type": "plain_text",
"text": "The Q",
"emoji": True
}
},
{
"type": "input",
"block_id": "the_pax",
"element": {
"type": "multi_users_select",
"placeholder": {
"type": "plain_text",
"text": "Tag the PAX",
"emoji": True
},
"action_id": "multi_users_select-action"
},
"label": {
"type": "plain_text",
"text": "The PAX",
"emoji": True
}
},
{
"type": "input",
"block_id": "fngs",
"element": {
"type": "plain_text_input",
"action_id": "fng-action",
"initial_value": "None",
"placeholder": {
"type": "plain_text",
"text": "FNGs"
}
},
"label": {
"type": "plain_text",
"text": "List untaggable names separated by commas (FNGs, Willy Lomans, etc.)"
}
},
{
"type": "input",
"block_id": "count",
"element": {
"type": "plain_text_input",
"action_id": "count-action",
"placeholder": {
"type": "plain_text",
"text": "Total PAX count including FNGs"
}
},
"label": {
"type": "plain_text",
"text": "Count"
}
},
{
"type": "input",
"block_id": "moleskine",
"element": {
"type": "plain_text_input",
"multiline": True,
"action_id": "plain_text_input-action",
"initial_value": "WARMUP: \nTHE THANG: \nMARY: \nANNOUNCEMENTS: \nCOT: ",
"placeholder": {
"type": "plain_text",
"text": "Tell us what happened\n\n"
}
},
"label": {
"type": "plain_text",
"text": "The Moleskine",
"emoji": True
}
},
{
"type": "divider"
},
{
"type": "section",
"block_id": "destination",
"text": {
"type": "plain_text",
"text": "Choose where to post this"
},
"accessory": {
"action_id": "destination-action",
"type": "static_select",
"placeholder": {
"type": "plain_text",
"text": "Choose where"
},
"initial_option": initial_channel_option,
"options": channel_options
}
}
]
},
)
logger.info(res)
@slack_app.view("backblast-id")
async def view_submission(ack, body, logger, client):
await ack()
result = body["view"]["state"]["values"]
title = result["title"]["title"]["value"]
date = result["date"]["datepicker-action"]["selected_date"]
the_ao = result["the_ao"]["channels_select-action"]["selected_channel"]
the_q = result["the_q"]["users_select-action"]["selected_user"]
pax = result["the_pax"]["multi_users_select-action"]["selected_users"]
fngs = result["fngs"]["fng-action"]["value"]
count = result["count"]["count-action"]["value"]
moleskine = result["moleskine"]["plain_text_input-action"]["value"]
destination = result["destination"]["destination-action"]["selected_option"]["value"]
the_date = result["date"]["datepicker-action"]["selected_date"]
pax_formatted = await get_pax(pax)
logger.info(result)
chan = destination
if chan == 'THE_AO':
chan = the_ao
logger.info('Channel to post to will be', chan, " Because the selected destination value was", destination, " while the selected AO in the modal was", the_ao)
msg = ""
try:
# formatting a message
# todo: change to use json object
msg = f"*Slackblast*: " + \
"\n*Title*: " + title + \
"\n*Date*: " + date + \
"\n*AO*: <#" + the_ao + ">" + \
"\n*Q*: <@" + the_q + ">" + \
"\n*PAX*: " + pax_formatted + \
"\n*FNGs*: " + fngs + \
"\n*Count*: " + count + \
"\n*Moleskine*:\n" + moleskine
except Exception as e:
# Handle error
msg = "There was an error with your submission: " + e
finally:
# Message the user via the app/bot name
if config('POST_TO_CHANNEL', cast=bool):
await client.chat_postMessage(channel=chan, text=msg)
# @slack_app.options("es_categories")
# async def show_categories(ack, body, logger):
# await ack()
# lookup = body["value"]
# filtered = [x for x in categories if lookup.lower() in x["name"].lower()]
# output = formatted_categories(filtered)
# options = output
# logger.info(options)
# await ack(options=options)
async def get_pax(pax):
p = ""
for x in pax:
p += "<@" + x + "> "
return p
app = FastAPI()
@app.post("/slack/events")
async def endpoint(req: Request):
logging.debug('[In app.post("/slack/events")]');
return await app_handler.handle(req)
@app.get("/")
async def status_ok():
logging.debug('[In app.get("/")]')
return "ok"