-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.ts
884 lines (841 loc) · 28.7 KB
/
app.ts
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
import { SlackAppEnv, SlackEdgeAppEnv, SlackSocketModeAppEnv } from "./app-env";
import { parseRequestBody } from "./request/request-parser";
import { verifySlackRequest } from "./request/request-verification";
import {
BlockActionAckHandler,
BlockActionLazyHandler,
BlockSuggestionAckHandler,
EventLazyHandler,
GlobalShortcutAckHandler,
GlobalShortcutLazyHandler,
MessageEventLazyHandler,
MessageShortcutAckHandler,
MessageShortcutLazyHandler,
ShortcutAckHandler,
ShortcutLazyHandler,
SlackHandler,
SlashCommandAckHandler,
SlashCommandLazyHandler,
ViewAckHandler,
ViewClosedAckHandler,
ViewClosedLazyHandler,
ViewLazyHandler,
ViewSubmissionAckHandler,
ViewSubmissionLazyHandler,
} from "./handler/handler";
import { SlackRequestBody } from "./request/request-body";
import {
PreAuthorizeSlackMiddlwareRequest,
SlackMiddlwareRequest,
SlackRequest,
SlackRequestWithChannelId,
} from "./request/request";
import { SlashCommand } from "./request/payload/slash-command";
import { toCompleteResponse } from "./response/response";
import {
SlackEvent,
AnySlackEvent,
AnySlackEventWithChannelId,
} from "./request/payload/event";
import { ResponseUrlSender, SlackAPIClient } from "slack-web-api-client";
import {
builtBaseContext,
SlackAppContext,
SlackAppContextWithChannelId,
SlackAppContextWithRespond,
} from "./context/context";
import { PreAuthorizeMiddleware, Middleware } from "./middleware/middleware";
import { isDebugLogEnabled, prettyPrint } from "slack-web-api-client";
import { Authorize } from "./authorization/authorize";
import { AuthorizeResult } from "./authorization/authorize-result";
import {
ignoringSelfEvents,
urlVerification,
} from "./middleware/built-in-middleware";
import { ConfigError } from "./errors";
import { GlobalShortcut } from "./request/payload/global-shortcut";
import { MessageShortcut } from "./request/payload/message-shortcut";
import {
BlockAction,
BlockElementActions,
BlockElementTypes,
} from "./request/payload/block-action";
import { ViewSubmission } from "./request/payload/view-submission";
import { ViewClosed } from "./request/payload/view-closed";
import { BlockSuggestion } from "./request/payload/block-suggestion";
import { SlackOptionsHandler } from "./handler/options-handler";
import { SlackViewHandler } from "./handler/view-handler";
import { SlackMessageHandler } from "./handler/message-handler";
import { singleTeamAuthorize } from "./authorization/single-team-authorize";
import { ExecutionContext, NoopExecutionContext } from "./execution-context";
import { PayloadType } from "./request/payload-types";
import { isPostedMessageEvent } from "./utility/message-events";
import { SocketModeClient } from "./socket-mode/socket-mode-client";
import { isFunctionExecutedEvent } from "./utility/function-executed-event";
export interface SlackAppOptions<
E extends SlackEdgeAppEnv | SlackSocketModeAppEnv,
> {
env: E;
authorize?: Authorize<E>;
routes?: {
// The name "events" could be somewhat confusing, but this path handles all types of request patterns
events: string;
};
socketMode?: boolean;
startLazyListenerAfterAck?: boolean;
}
export class SlackApp<E extends SlackEdgeAppEnv | SlackSocketModeAppEnv> {
public env: E;
public client: SlackAPIClient;
public authorize: Authorize<E>;
public routes: {
// The name "events" could be somewhat confusing, but this path handles all types of request patterns
events: string | undefined;
};
public signingSecret: string;
public appLevelToken: string | undefined;
public socketMode: boolean; // default: false
public socketModeClient: SocketModeClient | undefined;
public startLazyListenerAfterAck: boolean; // default: false
// deno-lint-ignore no-explicit-any
public preAuthorizeMiddleware: PreAuthorizeMiddleware<any>[] = [
urlVerification,
];
// deno-lint-ignore no-explicit-any
public postAuthorizeMiddleware: Middleware<any>[] = [ignoringSelfEvents];
#slashCommands: ((
body: SlackRequestBody,
) => SlackMessageHandler<E, SlashCommand> | null)[] = [];
#events: ((
body: SlackRequestBody,
) => SlackHandler<E, SlackEvent<string>> | null)[] = [];
#globalShorcuts: ((
body: SlackRequestBody,
) => SlackHandler<E, GlobalShortcut> | null)[] = [];
#messageShorcuts: ((
body: SlackRequestBody,
) => SlackHandler<E, MessageShortcut> | null)[] = [];
#blockActions: ((body: SlackRequestBody) => SlackHandler<
E,
// deno-lint-ignore no-explicit-any
BlockAction<any>
> | null)[] = [];
#blockSuggestions: ((
body: SlackRequestBody,
) => SlackOptionsHandler<E, BlockSuggestion> | null)[] = [];
#viewSubmissions: ((
body: SlackRequestBody,
) => SlackViewHandler<E, ViewSubmission> | null)[] = [];
#viewClosed: ((
body: SlackRequestBody,
) => SlackViewHandler<E, ViewClosed> | null)[] = [];
constructor(options: SlackAppOptions<E>) {
if (
options.env.SLACK_BOT_TOKEN === undefined &&
(options.authorize === undefined ||
options.authorize === singleTeamAuthorize)
) {
throw new ConfigError(
"When you don't pass env.SLACK_BOT_TOKEN, your own authorize function, which supplies a valid token to use, needs to be passed instead.",
);
}
this.env = options.env;
this.client = new SlackAPIClient(options.env.SLACK_BOT_TOKEN, {
logLevel: this.env.SLACK_LOGGING_LEVEL,
});
this.appLevelToken = options.env.SLACK_APP_TOKEN;
this.socketMode = options.socketMode ?? this.appLevelToken !== undefined;
if (this.socketMode) {
this.signingSecret = "";
} else {
if (!this.env.SLACK_SIGNING_SECRET) {
throw new ConfigError(
"env.SLACK_SIGNING_SECRET is required to run your app on edge functions!",
);
}
this.signingSecret = this.env.SLACK_SIGNING_SECRET;
}
this.startLazyListenerAfterAck = options.startLazyListenerAfterAck ?? false;
this.authorize = options.authorize ?? singleTeamAuthorize;
this.routes = { events: options.routes?.events };
}
beforeAuthorize(middleware: PreAuthorizeMiddleware<E>): SlackApp<E> {
this.preAuthorizeMiddleware.push(middleware);
return this;
}
middleware(middleware: Middleware<E>): SlackApp<E> {
return this.afterAuthorize(middleware);
}
use(middleware: Middleware<E>): SlackApp<E> {
return this.afterAuthorize(middleware);
}
afterAuthorize(middleware: Middleware<E>): SlackApp<E> {
this.postAuthorizeMiddleware.push(middleware);
return this;
}
command(
pattern: StringOrRegExp,
ack: SlashCommandAckHandler<E>,
lazy: SlashCommandLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackMessageHandler<E, SlashCommand> = { ack, lazy };
this.#slashCommands.push((body) => {
if (body.type || !body.command) {
return null;
}
if (typeof pattern === "string" && body.command === pattern) {
return handler;
} else if (
typeof pattern === "object" &&
pattern instanceof RegExp &&
body.command.match(pattern)
) {
return handler;
}
return null;
});
return this;
}
function(
callbackId: FunctionExecutedEventCallbackIdPattern,
lazy: EventLazyHandler<"function_executed", E>,
) {
this.#events.push((body) => {
if (
body.type !== PayloadType.EventsAPI ||
!body.event ||
body.event.type !== "function_executed"
) {
return null;
}
if (isFunctionExecutedEvent(body.event)) {
let matched = true;
if (callbackId !== undefined) {
if (typeof callbackId === "string") {
matched = body.event.function.callback_id.includes(callbackId);
}
if (typeof callbackId === "object") {
matched =
body.event.function.callback_id.match(callbackId) !== null;
}
}
if (matched) {
// deno-lint-ignore require-await
return { ack: async (_: EventRequest<E, "message">) => "", lazy };
}
}
return null;
});
return this;
}
event<Type extends string>(
event: Type,
lazy: EventLazyHandler<Type, E>,
): SlackApp<E> {
this.#events.push((body) => {
if (body.type !== PayloadType.EventsAPI || !body.event) {
return null;
}
if (body.event.type === event) {
// deno-lint-ignore require-await
return { ack: async () => "", lazy };
}
return null;
});
return this;
}
anyMessage(lazy: MessageEventLazyHandler<E>): SlackApp<E> {
return this.message(undefined, lazy);
}
message(
pattern: MessageEventPattern,
lazy: MessageEventLazyHandler<E>,
): SlackApp<E> {
this.#events.push((body) => {
if (
body.type !== PayloadType.EventsAPI ||
!body.event ||
body.event.type !== "message"
) {
return null;
}
if (isPostedMessageEvent(body.event)) {
let matched = true;
if (pattern !== undefined) {
if (typeof pattern === "string") {
matched = body.event.text!.includes(pattern);
}
if (typeof pattern === "object") {
matched = body.event.text!.match(pattern) !== null;
}
}
if (matched) {
// deno-lint-ignore require-await
return { ack: async (_: EventRequest<E, "message">) => "", lazy };
}
}
return null;
});
return this;
}
shortcut(
callbackId: StringOrRegExp,
ack: ShortcutAckHandler<E>,
lazy: ShortcutLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
return this.globalShortcut(callbackId, ack, lazy).messageShortcut(
callbackId,
ack,
lazy,
);
}
globalShortcut(
callbackId: StringOrRegExp,
ack: GlobalShortcutAckHandler<E>,
lazy: GlobalShortcutLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackHandler<E, GlobalShortcut> = { ack, lazy };
this.#globalShorcuts.push((body) => {
if (body.type !== PayloadType.GlobalShortcut || !body.callback_id) {
return null;
}
if (typeof callbackId === "string" && body.callback_id === callbackId) {
return handler;
} else if (
typeof callbackId === "object" &&
callbackId instanceof RegExp &&
body.callback_id.match(callbackId)
) {
return handler;
}
return null;
});
return this;
}
messageShortcut(
callbackId: StringOrRegExp,
ack: MessageShortcutAckHandler<E>,
lazy: MessageShortcutLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackHandler<E, MessageShortcut> = { ack, lazy };
this.#messageShorcuts.push((body) => {
if (body.type !== PayloadType.MessageShortcut || !body.callback_id) {
return null;
}
if (typeof callbackId === "string" && body.callback_id === callbackId) {
return handler;
} else if (
typeof callbackId === "object" &&
callbackId instanceof RegExp &&
body.callback_id.match(callbackId)
) {
return handler;
}
return null;
});
return this;
}
action<
T extends BlockElementTypes,
A extends BlockAction<
Extract<BlockElementActions, { type: T }>
> = BlockAction<Extract<BlockElementActions, { type: T }>>,
>(
constraints:
| StringOrRegExp
| { type: T; block_id?: string; action_id: string },
ack: BlockActionAckHandler<T, E, A>,
lazy: BlockActionLazyHandler<T, E, A> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackHandler<E, A> = { ack, lazy };
this.#blockActions.push((body) => {
if (
body.type !== PayloadType.BlockAction ||
!body.actions ||
!body.actions[0]
) {
return null;
}
const action = body.actions[0];
if (typeof constraints === "string" && action.action_id === constraints) {
return handler;
} else if (typeof constraints === "object") {
if (constraints instanceof RegExp) {
if (action.action_id.match(constraints)) {
return handler;
}
} else if (constraints.type) {
if (action.type === constraints.type) {
if (action.action_id === constraints.action_id) {
if (
constraints.block_id &&
action.block_id !== constraints.block_id
) {
return null;
}
return handler;
}
}
}
}
return null;
});
return this;
}
options(
constraints: StringOrRegExp | { block_id?: string; action_id: string },
ack: BlockSuggestionAckHandler<E>,
): SlackApp<E> {
// Note that block_suggestion response must be done within 3 seconds.
// So, we don't support the lazy handler for it.
const handler: SlackOptionsHandler<E, BlockSuggestion> = { ack };
this.#blockSuggestions.push((body) => {
if (body.type !== PayloadType.BlockSuggestion || !body.action_id) {
return null;
}
if (typeof constraints === "string" && body.action_id === constraints) {
return handler;
} else if (typeof constraints === "object") {
if (constraints instanceof RegExp) {
if (body.action_id.match(constraints)) {
return handler;
}
} else {
if (body.action_id === constraints.action_id) {
if (body.block_id && body.block_id !== constraints.block_id) {
return null;
}
return handler;
}
}
}
return null;
});
return this;
}
view(
callbackId: StringOrRegExp,
ack: ViewAckHandler<E>,
lazy: ViewLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
return this.viewSubmission(callbackId, ack, lazy).viewClosed(
callbackId,
ack,
lazy,
);
}
viewSubmission(
callbackId: StringOrRegExp,
ack: ViewSubmissionAckHandler<E>,
lazy: ViewSubmissionLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackViewHandler<E, ViewSubmission> = { ack, lazy };
this.#viewSubmissions.push((body) => {
if (body.type !== PayloadType.ViewSubmission || !body.view) {
return null;
}
if (
typeof callbackId === "string" &&
body.view.callback_id === callbackId
) {
return handler;
} else if (
typeof callbackId === "object" &&
callbackId instanceof RegExp &&
body.view.callback_id.match(callbackId)
) {
return handler;
}
return null;
});
return this;
}
viewClosed(
callbackId: StringOrRegExp,
ack: ViewClosedAckHandler<E>,
lazy: ViewClosedLazyHandler<E> = noopLazyHandler,
): SlackApp<E> {
const handler: SlackViewHandler<E, ViewClosed> = { ack, lazy };
this.#viewClosed.push((body) => {
if (body.type !== PayloadType.ViewClosed || !body.view) {
return null;
}
if (
typeof callbackId === "string" &&
body.view.callback_id === callbackId
) {
return handler;
} else if (
typeof callbackId === "object" &&
callbackId instanceof RegExp &&
body.view.callback_id.match(callbackId)
) {
return handler;
}
return null;
});
return this;
}
async run(
request: Request,
ctx: ExecutionContext = new NoopExecutionContext(),
): Promise<Response> {
return await this.handleEventRequest(request, ctx);
}
async connect(): Promise<void> {
if (!this.socketMode) {
throw new ConfigError(
"Both env.SLACK_APP_TOKEN and socketMode: true are required to start a Socket Mode connection!",
);
}
this.socketModeClient = new SocketModeClient(this);
await this.socketModeClient.connect();
}
async disconnect(): Promise<void> {
if (this.socketModeClient) {
await this.socketModeClient.disconnect();
}
}
async handleEventRequest(
request: Request,
ctx: ExecutionContext,
): Promise<Response> {
// If the routes.events is missing, any URLs can work for handing requests from Slack
if (this.routes.events) {
const { pathname } = new URL(request.url);
if (pathname !== this.routes.events) {
return new Response("Not found", { status: 404 });
}
}
// To avoid the following warning by Cloudflware, parse the body as Blob first
// Called .text() on an HTTP body which does not appear to be text ..
const blobRequestBody = await request.blob();
// We can safely assume the incoming request body is always text data
const rawBody: string = await blobRequestBody.text();
// For Request URL verification
if (rawBody.includes("ssl_check=")) {
// Slack does not send the x-slack-signature header for this pattern.
// Thus, we need to check the pattern before verifying a request.
const bodyParams = new URLSearchParams(rawBody);
if (bodyParams.get("ssl_check") === "1" && bodyParams.get("token")) {
return new Response("", { status: 200 });
}
}
// Verify the request headers and body
const isRequestSignatureVerified =
this.socketMode ||
(await verifySlackRequest(this.signingSecret, request.headers, rawBody));
if (isRequestSignatureVerified) {
// deno-lint-ignore no-explicit-any
const body: Record<string, any> = await parseRequestBody(
request.headers,
rawBody,
);
let retryNum: number | undefined = undefined;
try {
const retryNumHeader = request.headers.get("x-slack-retry-num");
if (retryNumHeader) {
retryNum = Number.parseInt(retryNumHeader);
} else if (this.socketMode && body.retry_attempt) {
retryNum = Number.parseInt(body.retry_attempt);
}
// deno-lint-ignore no-unused-vars
} catch (e) {
// Ignore an exception here
}
const retryReason =
request.headers.get("x-slack-retry-reason") ?? body.retry_reason;
const preAuthorizeRequest: PreAuthorizeSlackMiddlwareRequest<E> = {
body,
rawBody,
retryNum,
retryReason,
context: builtBaseContext(body),
env: this.env,
headers: request.headers,
};
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(`*** Received request body ***\n ${prettyPrint(body)}`);
}
for (const middlware of this.preAuthorizeMiddleware) {
const response = await middlware(preAuthorizeRequest);
if (response) {
return toCompleteResponse(response);
}
}
const authorizeResult: AuthorizeResult =
await this.authorize(preAuthorizeRequest);
const primaryToken =
preAuthorizeRequest.context.functionBotAccessToken ||
authorizeResult.botToken;
const authorizedContext: SlackAppContext = {
...preAuthorizeRequest.context,
authorizeResult,
client: new SlackAPIClient(primaryToken, {
logLevel: this.env.SLACK_LOGGING_LEVEL,
}),
botToken: authorizeResult.botToken,
botId: authorizeResult.botId,
botUserId: authorizeResult.botUserId,
userToken: authorizeResult.userToken,
};
if (authorizedContext.channelId) {
const context = authorizedContext as SlackAppContextWithChannelId;
const primaryToken = context.functionBotAccessToken || context.botToken;
const client = new SlackAPIClient(primaryToken);
context.say = async (params) =>
await client.chat.postMessage({
channel: context.channelId,
...params,
});
}
if (authorizedContext.responseUrl) {
const responseUrl = authorizedContext.responseUrl;
// deno-lint-ignore require-await
(authorizedContext as SlackAppContextWithRespond).respond = async (
params,
) => {
return new ResponseUrlSender(responseUrl).call(params);
};
}
const baseRequest: SlackMiddlwareRequest<E> = {
...preAuthorizeRequest,
context: authorizedContext,
};
for (const middlware of this.postAuthorizeMiddleware) {
const response = await middlware(baseRequest);
if (response) {
return toCompleteResponse(response);
}
}
const payload = body as SlackRequestBody;
if (body.type === PayloadType.EventsAPI) {
// Events API
const slackRequest: SlackRequest<E, SlackEvent<string>> = {
payload: body.event,
...baseRequest,
};
for (const matcher of this.#events) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (!body.type && body.command) {
// Slash commands
const slackRequest: SlackRequest<E, SlashCommand> = {
payload: body as SlashCommand,
...baseRequest,
};
for (const matcher of this.#slashCommands) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.GlobalShortcut) {
// Global shortcuts
const slackRequest: SlackRequest<E, GlobalShortcut> = {
payload: body as GlobalShortcut,
...baseRequest,
};
for (const matcher of this.#globalShorcuts) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.MessageShortcut) {
// Message shortcuts
const slackRequest: SlackRequest<E, MessageShortcut> = {
payload: body as MessageShortcut,
...baseRequest,
};
for (const matcher of this.#messageShorcuts) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.BlockAction) {
// Block actions
// deno-lint-ignore no-explicit-any
const slackRequest: SlackRequest<E, BlockAction<any>> = {
// deno-lint-ignore no-explicit-any
payload: body as BlockAction<any>,
...baseRequest,
};
for (const matcher of this.#blockActions) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.BlockSuggestion) {
// Block suggestions
const slackRequest: SlackRequest<E, BlockSuggestion> = {
payload: body as BlockSuggestion,
...baseRequest,
};
for (const matcher of this.#blockSuggestions) {
const handler = matcher(payload);
if (handler) {
// Note that the only way to respond to a block_suggestion request
// is to send an HTTP response with options/option_groups.
// Thus, we don't support lazy handlers for this pattern.
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.ViewSubmission) {
// View submissions
const slackRequest: SlackRequest<E, ViewSubmission> = {
payload: body as ViewSubmission,
...baseRequest,
};
for (const matcher of this.#viewSubmissions) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
} else if (body.type === PayloadType.ViewClosed) {
// View closed
const slackRequest: SlackRequest<E, ViewClosed> = {
payload: body as ViewClosed,
...baseRequest,
};
for (const matcher of this.#viewClosed) {
const handler = matcher(payload);
if (handler) {
if (!this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
const slackResponse = await handler.ack(slackRequest);
if (isDebugLogEnabled(this.env.SLACK_LOGGING_LEVEL)) {
console.log(
`*** Slack response ***\n${prettyPrint(slackResponse)}`,
);
}
if (this.startLazyListenerAfterAck) {
ctx.waitUntil(handler.lazy(slackRequest));
}
return toCompleteResponse(slackResponse);
}
}
}
// TODO: Add code suggestion here
console.log(
`*** No listener found ***\n${JSON.stringify(baseRequest.body)}`,
);
return new Response("No listener found", { status: 404 });
}
return new Response("Invalid signature", { status: 401 });
}
}
export type StringOrRegExp = string | RegExp;
export type EventRequest<E extends SlackAppEnv, T> =
Extract<AnySlackEventWithChannelId, { type: T }> extends never
? SlackRequest<E, Extract<AnySlackEvent, { type: T }>>
: SlackRequestWithChannelId<
E,
Extract<AnySlackEventWithChannelId, { type: T }>
>;
export type FunctionExecutedEventCallbackIdPattern =
| string
| RegExp
| undefined;
export type MessageEventPattern = string | RegExp | undefined;
export type MessageEventRequest<
E extends SlackAppEnv,
ST extends string | undefined,
> = SlackRequestWithChannelId<
E,
Extract<AnySlackEventWithChannelId, { subtype: ST }>
>;
export type MessageEventSubtypes =
| undefined
| "bot_message"
| "thread_broadcast"
| "file_share";
export type MessageEventHandler<E extends SlackAppEnv> = (
req: MessageEventRequest<E, MessageEventSubtypes>,
) => Promise<void>;
export const noopLazyHandler = async () => {};