-
Notifications
You must be signed in to change notification settings - Fork 395
/
builtin.ts
315 lines (270 loc) · 9.19 KB
/
builtin.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
import {
Middleware,
AnyMiddlewareArgs,
SlackActionMiddlewareArgs,
SlackCommandMiddlewareArgs,
SlackEventMiddlewareArgs,
SlackOptionsMiddlewareArgs,
SlackEvent,
SlackAction,
SlashCommand,
OptionsRequest,
InteractiveMessage,
DialogSubmitAction,
MessageAction,
BlockElementAction,
ContextMissingPropertyError,
} from '../types';
import { ActionConstraints } from '../App';
import { ErrorCode, errorWithCode } from '../errors';
/**
* Middleware that filters out any event that isn't an action
*/
export const onlyActions: Middleware<AnyMiddlewareArgs & { action?: SlackAction }> = ({ action, next }) => {
// Filter out any non-actions
if (action === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
next();
};
/**
* Middleware that filters out any event that isn't a command
*/
export const onlyCommands: Middleware<AnyMiddlewareArgs & { command?: SlashCommand }> = ({ command, next }) => {
// Filter out any non-commands
if (command === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
next();
};
/**
* Middleware that filters out any event that isn't an options
*/
export const onlyOptions: Middleware<AnyMiddlewareArgs & { options?: OptionsRequest }> = ({ options, next }) => {
// Filter out any non-options requests
if (options === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
next();
};
/**
* Middleware that filters out any event that isn't an event
*/
export const onlyEvents: Middleware<AnyMiddlewareArgs & { event?: SlackEvent }> = ({ event, next }) => {
// Filter out any non-events
if (event === undefined) {
return;
}
// It matches so we should continue down this middleware listener chain
next();
};
/**
* Middleware that checks for matches given constraints
*/
export function matchConstraints(
constraints: ActionConstraints,
): Middleware<SlackActionMiddlewareArgs | SlackOptionsMiddlewareArgs> {
return ({ payload, body, next, context }) => {
// TODO: is putting matches in an array actually helpful? there's no way to know which of the regexps contributed
// which matches (and in which order)
let tempMatches: RegExpMatchArray | null;
if (constraints.block_id !== undefined) {
if (!isBlockPayload(payload)) {
return;
}
if (typeof constraints.block_id === 'string') {
if (payload.block_id !== constraints.block_id) {
return;
}
} else {
tempMatches = payload.block_id.match(constraints.block_id);
if (tempMatches !== null) {
context['blockIdMatches'] = tempMatches;
} else {
return;
}
}
}
if (constraints.action_id !== undefined) {
if (!isBlockPayload(payload)) {
return;
}
if (typeof constraints.action_id === 'string') {
if (payload.action_id !== constraints.action_id) {
return;
}
} else {
tempMatches = payload.action_id.match(constraints.action_id);
if (tempMatches !== null) {
context['actionIdMatches'] = tempMatches;
} else {
return;
}
}
}
if (constraints.callback_id !== undefined) {
if (!isCallbackIdentifiedBody(body)) {
return;
}
if (typeof constraints.callback_id === 'string') {
if (body.callback_id !== constraints.callback_id) {
return;
}
} else {
tempMatches = body.callback_id.match(constraints.callback_id);
if (tempMatches !== null) {
context['callbackIdMatches'] = tempMatches;
} else {
return;
}
}
}
next();
};
}
/*
* Middleware that filters out messages that don't match pattern
*/
export function matchMessage(pattern: string | RegExp): Middleware<SlackEventMiddlewareArgs<'message'>> {
return ({ message, context, next }) => {
let tempMatches: RegExpMatchArray | null;
if (message.text === undefined) {
return;
}
// Filter out messages that don't contain the pattern
if (typeof pattern === 'string') {
if (!message.text.includes(pattern)) {
return;
}
} else {
tempMatches = message.text.match(pattern);
if (tempMatches !== null) {
context['matches'] = tempMatches;
} else {
return;
}
}
next();
};
}
/**
* Middleware that filters out any command that doesn't match name
*/
export function matchCommandName(name: string): Middleware<SlackCommandMiddlewareArgs> {
return ({ command, next }) => {
// Filter out any commands that are not the correct command name
if (name !== command.command) {
return;
}
next();
};
}
/**
* Middleware that filters out any event that isn't of given type
*/
export function matchEventType(type: string): Middleware<SlackEventMiddlewareArgs> {
return ({ event, next }) => {
// Filter out any events that are not the correct type
if (type !== event.type) {
return;
}
next();
};
}
export function ignoreSelf(): Middleware<AnyMiddlewareArgs> {
return (args) => {
// When context does not have a botId in it, then this middleware cannot perform its job. Bail immediately.
if (args.context.botId === undefined) {
args.next(contextMissingPropertyError(
'botId',
'Cannot ignore events from the app without a bot ID. Ensure authorize callback returns a botId.',
));
return;
}
const botId = args.context.botId as string;
const botUserId = args.context.botUserId !== undefined ? args.context.botUserId as string : undefined;
if (isEventArgs(args)) {
// Once we've narrowed the type down to SlackEventMiddlewareArgs, there's no way to further narrow it down to
// SlackEventMiddlewareArgs<'message'> without a cast, so the following couple lines do that.
if (args.message !== undefined) {
const message = args.message as SlackEventMiddlewareArgs<'message'>['message'];
// TODO: revisit this once we have all the message subtypes defined to see if we can do this better with
// type narrowing
// Look for an event that is identified as a bot message from the same bot ID as this app, and return to skip
if (message.subtype === 'bot_message' && message.bot_id === botId) {
return;
}
}
// Its an Events API event that isn't of type message, but the user ID might match our own app. Filter these out.
if (botUserId !== undefined && args.event.user === botUserId) {
return;
}
}
// If all the previous checks didn't skip this message, then its okay to resume to next
args.next();
};
}
export function subtype(subtype: string): Middleware<SlackEventMiddlewareArgs<'message'>> {
return ({ message, next }) => {
if (message.subtype === subtype) {
next();
}
};
}
const slackLink = /<(?<type>[@#!])?(?<link>[^>|]+)(?:\|(?<label>[^>]+))?>/;
export function directMention(): Middleware<SlackEventMiddlewareArgs<'message'>> {
return ({ message, context, next }) => {
// When context does not have a botUserId in it, then this middleware cannot perform its job. Bail immediately.
if (context.botUserId === undefined) {
next(contextMissingPropertyError(
'botUserId',
'Cannot match direct mentions of the app without a bot user ID. Ensure authorize callback returns a botUserId.',
));
return;
}
if (message.text === undefined) {
return;
}
// Match the message text with a user mention format
const text = message.text.trim();
const matches = slackLink.exec(text);
if (
matches === null || // stop when no matches are found
matches.index !== 0 || // stop if match isn't at the beginning
// stop if match isn't a user mention with the right user ID
matches.groups === undefined || matches.groups.type !== '@' || matches.groups.link !== context.botUserId
) {
return;
}
next();
};
}
function isBlockPayload(
payload: SlackActionMiddlewareArgs['payload'] | SlackOptionsMiddlewareArgs['payload'],
): payload is BlockElementAction | OptionsRequest<'block_suggestion'> {
return (payload as BlockElementAction | OptionsRequest<'block_suggestion'>).action_id !== undefined;
}
type CallbackIdentifiedBody =
| InteractiveMessage
| DialogSubmitAction
| MessageAction
| OptionsRequest<'interactive_message' | 'dialog_suggestion'>;
function isCallbackIdentifiedBody(
body: SlackActionMiddlewareArgs['body'] | SlackOptionsMiddlewareArgs['body'],
): body is CallbackIdentifiedBody {
return (body as CallbackIdentifiedBody).callback_id !== undefined;
}
function isEventArgs(
args: AnyMiddlewareArgs,
): args is SlackEventMiddlewareArgs {
return (args as SlackEventMiddlewareArgs).event !== undefined;
}
export function contextMissingPropertyError(propertyName: string, message?: string): ContextMissingPropertyError {
const m = message === undefined ? `Context missing property: ${propertyName}` : message;
const error = errorWithCode(m, ErrorCode.ContextMissingPropertyError);
(error as ContextMissingPropertyError).missingProperty = propertyName;
return error as ContextMissingPropertyError;
}