forked from telegraf/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
composer.js
394 lines (330 loc) · 10.7 KB
/
composer.js
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
const TelegrafContext = require('./core/context')
class Composer {
constructor (...fns) {
this.handler = Composer.compose(fns)
}
use (...fns) {
this.handler = Composer.compose([this.handler, ...fns])
return this
}
on (updateTypes, ...fns) {
return this.use(Composer.mount(updateTypes, ...fns))
}
hears (triggers, ...fns) {
return this.use(Composer.hears(triggers, ...fns))
}
command (commands, ...fns) {
return this.use(Composer.command(commands, ...fns))
}
action (triggers, ...fns) {
return this.use(Composer.action(triggers, ...fns))
}
inlineQuery (triggers, ...fns) {
return this.use(Composer.inlineQuery(triggers, ...fns))
}
gameQuery (...fns) {
return this.use(Composer.gameQuery(...fns))
}
drop (predicate) {
return this.use(Composer.drop(predicate))
}
filter (predicate) {
return this.use(Composer.filter(predicate))
}
entity (...args) {
return this.use(Composer.entity(...args))
}
email (...args) {
return this.use(Composer.email(...args))
}
url (...args) {
return this.use(Composer.url(...args))
}
textLink (...args) {
return this.use(Composer.textLink(...args))
}
textMention (...args) {
return this.use(Composer.textMention(...args))
}
mention (...args) {
return this.use(Composer.mention(...args))
}
phone (...args) {
return this.use(Composer.phone(...args))
}
hashtag (...args) {
return this.use(Composer.hashtag(...args))
}
cashtag (...args) {
return this.use(Composer.cashtag(...args))
}
start (...fns) {
return this.command('start', Composer.tap((ctx) => {
ctx.startPayload = ctx.message.text.substring(7)
}), ...fns)
}
help (...fns) {
return this.command('help', ...fns)
}
settings (...fns) {
return this.command('settings', ...fns)
}
middleware () {
return this.handler
}
static reply (...args) {
return (ctx) => ctx.reply(...args)
}
static fork (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => {
setImmediate(handler, ctx, Composer.safePassThru())
return next(ctx)
}
}
static tap (middleware) {
const handler = Composer.unwrap(middleware)
return (ctx, next) => Promise.resolve(handler(ctx, Composer.safePassThru())).then(() => next(ctx))
}
static passThru () {
return (ctx, next) => next(ctx)
}
static safePassThru () {
return (ctx, next) => typeof next === 'function' ? next(ctx) : Promise.resolve()
}
static lazy (factoryFn) {
if (typeof factoryFn !== 'function') {
throw new Error('Argument must be a function')
}
return (ctx, next) => Promise.resolve(factoryFn(ctx))
.then((middleware) => Composer.unwrap(middleware)(ctx, next))
}
static log (logFn = console.log) {
return Composer.fork((ctx) => logFn(JSON.stringify(ctx.update, null, 2)))
}
static branch (predicate, trueMiddleware, falseMiddleware) {
if (typeof predicate !== 'function') {
return predicate ? trueMiddleware : falseMiddleware
}
return Composer.lazy((ctx) => Promise.resolve(predicate(ctx))
.then((value) => value ? trueMiddleware : falseMiddleware))
}
static optional (predicate, ...fns) {
return Composer.branch(predicate, Composer.compose(fns), Composer.safePassThru())
}
static filter (predicate) {
return Composer.branch(predicate, Composer.safePassThru(), () => { })
}
static drop (predicate) {
return Composer.branch(predicate, () => { }, Composer.safePassThru())
}
static dispatch (routeFn, handlers) {
return typeof routeFn === 'function'
? Composer.lazy((ctx) => Promise.resolve(routeFn(ctx)).then((value) => handlers[value]))
: handlers[routeFn]
}
static mount (updateType, ...fns) {
const updateTypes = normalizeTextArguments(updateType)
const predicate = (ctx) => updateTypes.includes(ctx.updateType) || updateTypes.some((type) => ctx.updateSubTypes.includes(type))
return Composer.optional(predicate, ...fns)
}
static entity (predicate, ...fns) {
if (typeof predicate !== 'function') {
const entityTypes = normalizeTextArguments(predicate)
return Composer.entity(({ type }) => entityTypes.includes(type), ...fns)
}
return Composer.optional((ctx) => {
const message = ctx.message || ctx.channelPost
const entities = message && (message.entities || message.caption_entities)
const text = message && (message.text || message.caption)
return entities && entities.some((entity) =>
predicate(entity, text.substring(entity.offset, entity.offset + entity.length), ctx)
)
}, ...fns)
}
static entityText (entityType, predicate, ...fns) {
if (fns.length === 0) {
return Array.isArray(predicate)
? Composer.entity(entityType, ...predicate)
: Composer.entity(entityType, predicate)
}
const triggers = normalizeTriggers(predicate)
return Composer.entity(({ type }, value, ctx) => {
if (type !== entityType) {
return false
}
for (const trigger of triggers) {
ctx.match = trigger(value, ctx)
if (ctx.match) {
return true
}
}
}, ...fns)
}
static email (email, ...fns) {
return Composer.entityText('email', email, ...fns)
}
static phone (number, ...fns) {
return Composer.entityText('phone_number', number, ...fns)
}
static url (url, ...fns) {
return Composer.entityText('url', url, ...fns)
}
static textLink (link, ...fns) {
return Composer.entityText('text_link', link, ...fns)
}
static textMention (mention, ...fns) {
return Composer.entityText('text_mention', mention, ...fns)
}
static mention (mention, ...fns) {
return Composer.entityText('mention', normalizeTextArguments(mention, '@'), ...fns)
}
static hashtag (hashtag, ...fns) {
return Composer.entityText('hashtag', normalizeTextArguments(hashtag, '#'), ...fns)
}
static cashtag (cashtag, ...fns) {
return Composer.entityText('cashtag', normalizeTextArguments(cashtag, '$'), ...fns)
}
static match (triggers, ...fns) {
return Composer.optional((ctx) => {
const text = (
(ctx.message && (ctx.message.caption || ctx.message.text)) ||
(ctx.callbackQuery && ctx.callbackQuery.data) ||
(ctx.inlineQuery && ctx.inlineQuery.query)
)
for (const trigger of triggers) {
ctx.match = trigger(text, ctx)
if (ctx.match) {
return true
}
}
}, ...fns)
}
static hears (triggers, ...fns) {
return Composer.mount('text', Composer.match(normalizeTriggers(triggers), ...fns))
}
static command (command, ...fns) {
if (fns.length === 0) {
return Composer.entity(['bot_command'], command)
}
const commands = normalizeTextArguments(command, '/')
return Composer.mount('text', Composer.lazy((ctx) => {
const groupCommands = ctx.me && (ctx.chat.type === 'group' || ctx.chat.type === 'supergroup')
? commands.map((command) => `${command}@${ctx.me}`)
: []
return Composer.entity(({ offset, type }, value) =>
offset === 0 &&
type === 'bot_command' &&
(commands.includes(value) || groupCommands.includes(value))
, ...fns)
}))
}
static action (triggers, ...fns) {
return Composer.mount('callback_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static inlineQuery (triggers, ...fns) {
return Composer.mount('inline_query', Composer.match(normalizeTriggers(triggers), ...fns))
}
static acl (userId, ...fns) {
if (typeof userId === 'function') {
return Composer.optional(userId, ...fns)
}
const allowed = Array.isArray(userId) ? userId : [userId]
return Composer.optional((ctx) => !ctx.from || allowed.includes(ctx.from.id), ...fns)
}
static memberStatus (status, ...fns) {
const statuses = Array.isArray(status) ? status : [status]
return Composer.optional((ctx) => ctx.message && ctx.getChatMember(ctx.message.from.id)
.then(member => member && statuses.includes(member.status))
, ...fns)
}
static admin (...fns) {
return Composer.memberStatus(['administrator', 'creator'], ...fns)
}
static creator (...fns) {
return Composer.memberStatus('creator', ...fns)
}
static chatType (type, ...fns) {
const types = Array.isArray(type) ? type : [type]
return Composer.optional((ctx) => ctx.chat && types.includes(ctx.chat.type), ...fns)
}
static privateChat (...fns) {
return Composer.chatType('private', ...fns)
}
static groupChat (...fns) {
return Composer.chatType(['group', 'supergroup'], ...fns)
}
static gameQuery (...fns) {
return Composer.mount('callback_query', Composer.optional((ctx) => ctx.callbackQuery.game_short_name, ...fns))
}
static unwrap (handler) {
if (!handler) {
throw new Error('Handler is undefined')
}
return typeof handler.middleware === 'function'
? handler.middleware()
: handler
}
static compose (middlewares) {
if (!Array.isArray(middlewares)) {
throw new Error('Middlewares must be an array')
}
if (middlewares.length === 0) {
return Composer.safePassThru()
}
if (middlewares.length === 1) {
return Composer.unwrap(middlewares[0])
}
return (ctx, next) => {
let index = -1
return execute(0, ctx)
function execute (i, context) {
if (!(context instanceof TelegrafContext)) {
return Promise.reject(new Error('next(ctx) called with invalid context'))
}
if (i <= index) {
return Promise.reject(new Error('next() called multiple times'))
}
index = i
const handler = middlewares[i] ? Composer.unwrap(middlewares[i]) : next
if (!handler) {
return Promise.resolve()
}
try {
return Promise.resolve(
handler(context, (ctx = context) => execute(i + 1, ctx))
)
} catch (err) {
return Promise.reject(err)
}
}
}
}
}
function normalizeTriggers (triggers) {
if (!Array.isArray(triggers)) {
triggers = [triggers]
}
return triggers.map((trigger) => {
if (!trigger) {
throw new Error('Invalid trigger')
}
if (typeof trigger === 'function') {
return trigger
}
if (trigger instanceof RegExp) {
return (value) => {
trigger.lastIndex = 0
return trigger.exec(value || '')
}
}
return (value) => trigger === value ? value : null
})
}
function normalizeTextArguments (argument, prefix) {
const args = Array.isArray(argument) ? argument : [argument]
return args
.filter(Boolean)
.map((arg) => prefix && typeof arg === 'string' && !arg.startsWith(prefix) ? `${prefix}${arg}` : arg)
}
module.exports = Composer