grammy-tools 1.36.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +339 -0
  3. package/out/bot.d.ts +314 -0
  4. package/out/bot.js +669 -0
  5. package/out/composer.d.ts +764 -0
  6. package/out/composer.js +704 -0
  7. package/out/context.d.ts +1618 -0
  8. package/out/context.js +1976 -0
  9. package/out/convenience/constants.d.ts +98 -0
  10. package/out/convenience/constants.js +37 -0
  11. package/out/convenience/frameworks.d.ts +216 -0
  12. package/out/convenience/frameworks.js +370 -0
  13. package/out/convenience/inline_query.d.ts +401 -0
  14. package/out/convenience/inline_query.js +461 -0
  15. package/out/convenience/input_media.d.ts +72 -0
  16. package/out/convenience/input_media.js +82 -0
  17. package/out/convenience/keyboard.d.ts +763 -0
  18. package/out/convenience/keyboard.js +935 -0
  19. package/out/convenience/session.d.ts +345 -0
  20. package/out/convenience/session.js +455 -0
  21. package/out/convenience/webhook.d.ts +59 -0
  22. package/out/convenience/webhook.js +80 -0
  23. package/out/core/api.d.ts +1628 -0
  24. package/out/core/api.js +1907 -0
  25. package/out/core/client.d.ts +180 -0
  26. package/out/core/client.js +226 -0
  27. package/out/core/error.d.ts +53 -0
  28. package/out/core/error.js +87 -0
  29. package/out/core/payload.d.ts +39 -0
  30. package/out/core/payload.js +199 -0
  31. package/out/filter.d.ts +959 -0
  32. package/out/filter.js +378 -0
  33. package/out/mod.d.ts +14 -0
  34. package/out/mod.js +43 -0
  35. package/out/platform.node.d.ts +16 -0
  36. package/out/platform.node.js +43 -0
  37. package/out/shim.node.d.ts +2 -0
  38. package/out/shim.node.js +7 -0
  39. package/out/types.d.ts +1 -0
  40. package/out/types.js +17 -0
  41. package/out/types.node.d.ts +78 -0
  42. package/out/types.node.js +107 -0
  43. package/out/web.d.ts +1 -0
  44. package/out/web.mjs +5172 -0
  45. package/package.json +71 -0
@@ -0,0 +1,704 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Composer = exports.BotError = void 0;
4
+ exports.run = run;
5
+ const context_js_1 = require("./context.js");
6
+ // === Middleware errors
7
+ /**
8
+ * This error is thrown when middleware throws. It simply wraps the original
9
+ * error (accessible via the `error` property), but also provides access to the
10
+ * respective context object that was processed while the error occurred.
11
+ */
12
+ class BotError extends Error {
13
+ constructor(error, ctx) {
14
+ super(generateBotErrorMessage(error));
15
+ this.error = error;
16
+ this.ctx = ctx;
17
+ this.name = "BotError";
18
+ if (error instanceof Error)
19
+ this.stack = error.stack;
20
+ }
21
+ }
22
+ exports.BotError = BotError;
23
+ function generateBotErrorMessage(error) {
24
+ let msg;
25
+ if (error instanceof Error) {
26
+ msg = `${error.name} in middleware: ${error.message}`;
27
+ }
28
+ else {
29
+ const type = typeof error;
30
+ msg = `Non-error value of type ${type} thrown in middleware`;
31
+ switch (type) {
32
+ case "bigint":
33
+ case "boolean":
34
+ case "number":
35
+ case "symbol":
36
+ msg += `: ${error}`;
37
+ break;
38
+ case "string":
39
+ msg += `: ${String(error).substring(0, 50)}`;
40
+ break;
41
+ default:
42
+ msg += "!";
43
+ break;
44
+ }
45
+ }
46
+ return msg;
47
+ }
48
+ // === Middleware base functions
49
+ function flatten(mw) {
50
+ return typeof mw === "function"
51
+ ? mw
52
+ : (ctx, next) => mw.middleware()(ctx, next);
53
+ }
54
+ function concat(first, andThen) {
55
+ return async (ctx, next) => {
56
+ let nextCalled = false;
57
+ await first(ctx, async () => {
58
+ if (nextCalled)
59
+ throw new Error("`next` already called before!");
60
+ else
61
+ nextCalled = true;
62
+ await andThen(ctx, next);
63
+ });
64
+ };
65
+ }
66
+ function pass(_ctx, next) {
67
+ return next();
68
+ }
69
+ const leaf = () => Promise.resolve();
70
+ /**
71
+ * Runs some given middleware function with a given context object.
72
+ *
73
+ * @param middleware The middleware to run
74
+ * @param ctx The context to use
75
+ */
76
+ async function run(middleware, ctx) {
77
+ await middleware(ctx, leaf);
78
+ }
79
+ // === Composer
80
+ /**
81
+ * The composer is the heart of the middleware system in grammY. It is also the
82
+ * superclass of `Bot`. Whenever you call `use` or `on` or some of the other
83
+ * methods on your bot, you are in fact using the underlying composer instance
84
+ * to register your middleware.
85
+ *
86
+ * If you're just getting started, you do not need to worry about what
87
+ * middleware is, or about how to use a composer.
88
+ *
89
+ * On the other hand, if you want to dig deeper into how grammY implements
90
+ * middleware, check out the
91
+ * [documentation](https://grammy.dev/advanced/middleware) on the website.
92
+ */
93
+ class Composer {
94
+ /**
95
+ * Constructs a new composer based on the provided middleware. If no
96
+ * middleware is given, the composer instance will simply make all context
97
+ * objects pass through without touching them.
98
+ *
99
+ * @param middleware The middleware to compose
100
+ */
101
+ constructor(...middleware) {
102
+ this.handler = middleware.length === 0
103
+ ? pass
104
+ : middleware.map(flatten).reduce(concat);
105
+ }
106
+ middleware() {
107
+ return this.handler;
108
+ }
109
+ /**
110
+ * Registers some middleware that receives all updates. It is installed by
111
+ * concatenating it to the end of all previously installed middleware.
112
+ *
113
+ * Often, this method is used to install middleware that behaves like a
114
+ * plugin, for example session middleware.
115
+ * ```ts
116
+ * bot.use(session())
117
+ * ```
118
+ *
119
+ * This method returns a new instance of composer. The returned instance can
120
+ * be further extended, and all changes will be regarded here. Confer the
121
+ * [documentation](https://grammy.dev/advanced/middleware) on the
122
+ * website if you want to know more about how the middleware system in
123
+ * grammY works, especially when it comes to chaining the method calls
124
+ * (`use( ... ).use( ... ).use( ... )`).
125
+ *
126
+ * @param middleware The middleware to register
127
+ */
128
+ use(...middleware) {
129
+ const composer = new Composer(...middleware);
130
+ this.handler = concat(this.handler, flatten(composer));
131
+ return composer;
132
+ }
133
+ /**
134
+ * Registers some middleware that will only be executed for some specific
135
+ * updates, namely those matching the provided filter query. Filter queries
136
+ * are a concise way to specify which updates you are interested in.
137
+ *
138
+ * Here are some examples of valid filter queries:
139
+ * ```ts
140
+ * // All kinds of message updates
141
+ * bot.on('message', ctx => { ... })
142
+ *
143
+ * // Only text messages
144
+ * bot.on('message:text', ctx => { ... })
145
+ *
146
+ * // Only text messages with URL
147
+ * bot.on('message:entities:url', ctx => { ... })
148
+ *
149
+ * // Text messages and text channel posts
150
+ * bot.on(':text', ctx => { ... })
151
+ *
152
+ * // Messages with URL in text or caption (i.e. entities or caption entities)
153
+ * bot.on('message::url', ctx => { ... })
154
+ *
155
+ * // Messages or channel posts with URL in text or caption
156
+ * bot.on('::url', ctx => { ... })
157
+ * ```
158
+ *
159
+ * You can use autocomplete in VS Code to see all available filter queries.
160
+ * Check out the
161
+ * [documentation](https://grammy.dev/guide/filter-queries) on the
162
+ * website to learn more about filter queries in grammY.
163
+ *
164
+ * It is possible to pass multiple filter queries in an array, i.e.
165
+ * ```ts
166
+ * // Matches all text messages and edited text messages that contain a URL
167
+ * bot.on(['message:entities:url', 'edited_message:entities:url'], ctx => { ... })
168
+ * ```
169
+ *
170
+ * Your middleware will be executed if _any of the provided filter queries_
171
+ * matches (logical OR).
172
+ *
173
+ * If you instead want to match _all of the provided filter queries_
174
+ * (logical AND), you can chain the `.on` calls:
175
+ * ```ts
176
+ * // Matches all messages and channel posts that both a) contain a URL and b) are forwards
177
+ * bot.on('::url').on(':forward_origin', ctx => { ... })
178
+ * ```
179
+ *
180
+ * @param filter The filter query to use, may also be an array of queries
181
+ * @param middleware The middleware to register behind the given filter
182
+ */
183
+ on(filter, ...middleware) {
184
+ return this.filter(context_js_1.Context.has.filterQuery(filter), ...middleware);
185
+ }
186
+ /**
187
+ * Registers some middleware that will only be executed when the message
188
+ * contains some text. Is it possible to pass a regular expression to match:
189
+ * ```ts
190
+ * // Match some text (exact match)
191
+ * bot.hears('I love grammY', ctx => ctx.reply('And grammY loves you! <3'))
192
+ * // Match a regular expression
193
+ * bot.hears(/\/echo (.+)/, ctx => ctx.reply(ctx.match[1]))
194
+ * ```
195
+ * Note how `ctx.match` will contain the result of the regular expression.
196
+ * Here it is a `RegExpMatchArray` object, so `ctx.match[1]` refers to the
197
+ * part of the regex that was matched by `(.+)`, i.e. the text that comes
198
+ * after “/echo”.
199
+ *
200
+ * You can pass an array of triggers. Your middleware will be executed if at
201
+ * least one of them matches.
202
+ *
203
+ * Both text and captions of the received messages will be scanned. For
204
+ * example, when a photo is sent to the chat and its caption matches the
205
+ * trigger, your middleware will be executed.
206
+ *
207
+ * If you only want to match text messages and not captions, you can do
208
+ * this:
209
+ * ```ts
210
+ * // Only matches text messages (and channel posts) for the regex
211
+ * bot.on(':text').hears(/\/echo (.+)/, ctx => { ... })
212
+ * ```
213
+ *
214
+ * @param trigger The text to look for
215
+ * @param middleware The middleware to register
216
+ */
217
+ hears(trigger, ...middleware) {
218
+ return this.filter(context_js_1.Context.has.text(trigger), ...middleware);
219
+ }
220
+ /**
221
+ * Registers some middleware that will only be executed when a certain
222
+ * command is found.
223
+ * ```ts
224
+ * // Reacts to /start commands
225
+ * bot.command('start', ctx => { ... })
226
+ * // Reacts to /help commands
227
+ * bot.command('help', ctx => { ... })
228
+ * ```
229
+ *
230
+ * The rest of the message (excluding the command, and trimmed) is provided
231
+ * via `ctx.match`.
232
+ *
233
+ * > **Did you know?** You can use deep linking
234
+ * > (https://core.telegram.org/bots/features#deep-linking) to let users
235
+ * > start your bot with a custom payload. As an example, send someone the
236
+ * > link https://t.me/name-of-your-bot?start=custom-payload and register a
237
+ * > start command handler on your bot with grammY. As soon as the user
238
+ * > starts your bot, you will receive `custom-payload` in the `ctx.match`
239
+ * > property!
240
+ * > ```ts
241
+ * > bot.command('start', ctx => {
242
+ * > const payload = ctx.match // will be 'custom-payload'
243
+ * > })
244
+ * > ```
245
+ *
246
+ * Note that commands are not matched in captions or in the middle of the
247
+ * text.
248
+ * ```ts
249
+ * bot.command('start', ctx => { ... })
250
+ * // ... does not match:
251
+ * // A message saying: “some text /start some more text”
252
+ * // A photo message with the caption “/start”
253
+ * ```
254
+ *
255
+ * By default, commands are detected in channel posts, too. This means that
256
+ * `ctx.message` is potentially `undefined`, so you should use `ctx.msg`
257
+ * instead to grab both messages and channel posts. Alternatively, if you
258
+ * want to limit your bot to finding commands only in private and group
259
+ * chats, you can use `bot.on('message').command('start', ctx => { ... })`,
260
+ * or even store a message-only version of your bot in a variable like so:
261
+ * ```ts
262
+ * const m = bot.on('message')
263
+ *
264
+ * m.command('start', ctx => { ... })
265
+ * m.command('help', ctx => { ... })
266
+ * // etc
267
+ * ```
268
+ *
269
+ * If you need more freedom matching your commands, check out the `commands`
270
+ * plugin.
271
+ *
272
+ * @param command The command to look for
273
+ * @param middleware The middleware to register
274
+ */
275
+ command(command, ...middleware) {
276
+ return this.filter(context_js_1.Context.has.command(command), ...middleware);
277
+ }
278
+ /**
279
+ * Registers some middleware that will only be added when a new reaction of
280
+ * the given type is added to a message.
281
+ * ```ts
282
+ * // Reacts to new '👍' reactions
283
+ * bot.reaction('👍', ctx => { ... })
284
+ * // Reacts to new '👍' or '👎' reactions
285
+ * bot.reaction(['👍', '👎'], ctx => { ... })
286
+ * ```
287
+ *
288
+ * > Note that you have to enable `message_reaction` updates in
289
+ * `allowed_updates` if you want your bot to receive updates about message
290
+ * reactions.
291
+ *
292
+ * `bot.reaction` will trigger if:
293
+ * - a new emoji reaction is added to a message
294
+ * - a new custom emoji reaction is added a message
295
+ *
296
+ * `bot.reaction` will not trigger if:
297
+ * - a reaction is removed
298
+ * - an anonymous reaction count is updated, such as on channel posts
299
+ * - `message_reaction` updates are not enabled for your bot
300
+ *
301
+ * @param reaction The reaction to look for
302
+ * @param middleware The middleware to register
303
+ */
304
+ reaction(reaction, ...middleware) {
305
+ return this.filter(context_js_1.Context.has.reaction(reaction), ...middleware);
306
+ }
307
+ /**
308
+ * Registers some middleware for certain chat types only. For example, you
309
+ * can use this method to only receive updates from private chats. The four
310
+ * chat types are `"channel"`, `"supergroup"`, `"group"`, and `"private"`.
311
+ * This is especially useful when combined with other filtering logic. For
312
+ * example, this is how can you respond to `/start` commands only from
313
+ * private chats:
314
+ * ```ts
315
+ * bot.chatType("private").command("start", ctx => { ... })
316
+ * ```
317
+ *
318
+ * Naturally, you can also use this method on its own.
319
+ * ```ts
320
+ * // Private chats only
321
+ * bot.chatType("private", ctx => { ... });
322
+ * // Channels only
323
+ * bot.chatType("channel", ctx => { ... });
324
+ * ```
325
+ *
326
+ * You can pass an array of chat types if you want your middleware to run
327
+ * for any of several provided chat types.
328
+ * ```ts
329
+ * // Groups and supergroups only
330
+ * bot.chatType(["group", "supergroup"], ctx => { ... });
331
+ * ```
332
+ * [Remember](https://grammy.dev/guide/context#shortcuts) also that you
333
+ * can access the chat type via `ctx.chat.type`.
334
+ *
335
+ * @param chatType The chat type
336
+ * @param middleware The middleware to register
337
+ */
338
+ chatType(chatType, ...middleware) {
339
+ return this.filter(context_js_1.Context.has.chatType(chatType), ...middleware);
340
+ }
341
+ /**
342
+ * Registers some middleware for callback queries, i.e. the updates that
343
+ * Telegram delivers to your bot when a user clicks an inline button (that
344
+ * is a button under a message).
345
+ *
346
+ * This method is essentially the same as calling
347
+ * ```ts
348
+ * bot.on('callback_query:data', ctx => { ... })
349
+ * ```
350
+ * but it also allows you to match the query data against a given text or
351
+ * regular expression.
352
+ *
353
+ * ```ts
354
+ * // Create an inline keyboard
355
+ * const keyboard = new InlineKeyboard().text('Go!', 'button-payload')
356
+ * // Send a message with the keyboard
357
+ * await bot.api.sendMessage(chat_id, 'Press a button!', {
358
+ * reply_markup: keyboard
359
+ * })
360
+ * // Listen to users pressing buttons with that specific payload
361
+ * bot.callbackQuery('button-payload', ctx => { ... })
362
+ *
363
+ * // Listen to users pressing any button your bot ever sent
364
+ * bot.on('callback_query:data', ctx => { ... })
365
+ * ```
366
+ *
367
+ * Always remember to call `answerCallbackQuery`—even if you don't perform
368
+ * any action: https://core.telegram.org/bots/api#answercallbackquery
369
+ * ```ts
370
+ * bot.on('callback_query:data', async ctx => {
371
+ * await ctx.answerCallbackQuery()
372
+ * })
373
+ * ```
374
+ *
375
+ * You can pass an array of triggers. Your middleware will be executed if at
376
+ * least one of them matches.
377
+ *
378
+ * @param trigger The string to look for in the payload
379
+ * @param middleware The middleware to register
380
+ */
381
+ callbackQuery(trigger, ...middleware) {
382
+ return this.filter(context_js_1.Context.has.callbackQuery(trigger), ...middleware);
383
+ }
384
+ /**
385
+ * Registers some middleware for game queries, i.e. the updates that
386
+ * Telegram delivers to your bot when a user clicks an inline button for the
387
+ * HTML5 games platform on Telegram.
388
+ *
389
+ * This method is essentially the same as calling
390
+ * ```ts
391
+ * bot.on('callback_query:game_short_name', ctx => { ... })
392
+ * ```
393
+ * but it also allows you to match the query data against a given text or
394
+ * regular expression.
395
+ *
396
+ * You can pass an array of triggers. Your middleware will be executed if at
397
+ * least one of them matches.
398
+ *
399
+ * @param trigger The string to look for in the payload
400
+ * @param middleware The middleware to register
401
+ */
402
+ gameQuery(trigger, ...middleware) {
403
+ return this.filter(context_js_1.Context.has.gameQuery(trigger), ...middleware);
404
+ }
405
+ /**
406
+ * Registers middleware for inline queries. Telegram sends an inline query
407
+ * to your bot whenever a user types “@your_bot_name ...” into a text field
408
+ * in Telegram. You bot will then receive the entered search query and can
409
+ * respond with a number of results (text, images, etc) that the user can
410
+ * pick from to send a message _via_ your bot to the respective chat. Check
411
+ * out https://core.telegram.org/bots/inline to read more about inline bots.
412
+ *
413
+ * > Note that you have to enable inline mode for you bot by contacting
414
+ * > @BotFather first.
415
+ *
416
+ * ```ts
417
+ * // Listen for users typing “@your_bot_name query”
418
+ * bot.inlineQuery('query', async ctx => {
419
+ * // Answer the inline query, confer https://core.telegram.org/bots/api#answerinlinequery
420
+ * await ctx.answerInlineQuery( ... )
421
+ * })
422
+ * ```
423
+ *
424
+ * @param trigger The inline query text to match
425
+ * @param middleware The middleware to register
426
+ */
427
+ inlineQuery(trigger, ...middleware) {
428
+ return this.filter(context_js_1.Context.has.inlineQuery(trigger), ...middleware);
429
+ }
430
+ /**
431
+ * Registers middleware for the ChosenInlineResult by the given id or ids.
432
+ * ChosenInlineResult represents a result of an inline query that was chosen
433
+ * by the user and sent to their chat partner. Check out
434
+ * https://core.telegram.org/bots/api#choseninlineresult to read more about
435
+ * chosen inline results.
436
+ *
437
+ * ```ts
438
+ * bot.chosenInlineResult('id', async ctx => {
439
+ * const id = ctx.result_id;
440
+ * // Your code
441
+ * })
442
+ * ```
443
+ *
444
+ * @param resultId An id or array of ids
445
+ * @param middleware The middleware to register
446
+ */
447
+ chosenInlineResult(resultId, ...middleware) {
448
+ return this.filter(context_js_1.Context.has.chosenInlineResult(resultId), ...middleware);
449
+ }
450
+ /**
451
+ * Registers middleware for pre-checkout queries. Telegram sends a
452
+ * pre-checkout query to your bot whenever a user has confirmed their
453
+ * payment and shipping details. You bot will then receive all information
454
+ * about the order and has to respond within 10 seconds with a confirmation
455
+ * of whether everything is alright (goods are available, etc.) and the bot
456
+ * is ready to proceed with the order. Check out
457
+ * https://core.telegram.org/bots/api#precheckoutquery to read more about
458
+ * pre-checkout queries.
459
+ *
460
+ * ```ts
461
+ * bot.preCheckoutQuery('invoice_payload', async ctx => {
462
+ * // Answer the pre-checkout query, confer https://core.telegram.org/bots/api#answerprecheckoutquery
463
+ * await ctx.answerPreCheckoutQuery( ... )
464
+ * })
465
+ * ```
466
+ *
467
+ * @param trigger The string to look for in the invoice payload
468
+ * @param middleware The middleware to register
469
+ */
470
+ preCheckoutQuery(trigger, ...middleware) {
471
+ return this.filter(context_js_1.Context.has.preCheckoutQuery(trigger), ...middleware);
472
+ }
473
+ /**
474
+ * Registers middleware for shipping queries. If you sent an invoice
475
+ * requesting a shipping address and the parameter _is_flexible_ was
476
+ * specified, Telegram will send a shipping query to your bot whenever a
477
+ * user has confirmed their shipping details. You bot will then receive the
478
+ * shipping information and can respond with a confirmation of whether
479
+ * delivery to the specified address is possible. Check out
480
+ * https://core.telegram.org/bots/api#shippingquery to read more about
481
+ * shipping queries.
482
+ *
483
+ * ```ts
484
+ * bot.shippingQuery('invoice_payload', async ctx => {
485
+ * // Answer the shipping query, confer https://core.telegram.org/bots/api#answershippingquery
486
+ * await ctx.answerShippingQuery( ... )
487
+ * })
488
+ * ```
489
+ *
490
+ * @param trigger The string to look for in the invoice payload
491
+ * @param middleware The middleware to register
492
+ */
493
+ shippingQuery(trigger, ...middleware) {
494
+ return this.filter(context_js_1.Context.has.shippingQuery(trigger), ...middleware);
495
+ }
496
+ filter(predicate, ...middleware) {
497
+ const composer = new Composer(...middleware);
498
+ this.branch(predicate, composer, pass);
499
+ return composer;
500
+ }
501
+ /**
502
+ * > This is an advanced method of grammY.
503
+ *
504
+ * Registers middleware behind a custom filter function that operates on the
505
+ * context object and decides whether or not to execute the middleware. In
506
+ * other words, the middleware will only be executed if the given predicate
507
+ * returns `false` for the given context object. Otherwise, it will be
508
+ * skipped and the next middleware will be executed. Note that the predicate
509
+ * may be asynchronous, i.e. it can return a Promise of a boolean.
510
+ *
511
+ * This method is the same using `filter` (normal usage) with a negated
512
+ * predicate.
513
+ *
514
+ * @param predicate The predicate to check
515
+ * @param middleware The middleware to register
516
+ */
517
+ drop(predicate, ...middleware) {
518
+ return this.filter(async (ctx) => !(await predicate(ctx)), ...middleware);
519
+ }
520
+ /**
521
+ * > This is an advanced method of grammY.
522
+ *
523
+ * Registers some middleware that runs concurrently to the executing
524
+ * middleware stack.
525
+ * ```ts
526
+ * bot.use( ... ) // will run first
527
+ * bot.fork( ... ) // will be started second, but run concurrently
528
+ * bot.use( ... ) // will also be run second
529
+ * ```
530
+ * In the first middleware, as soon as `next`'s Promise resolves, both forks
531
+ * have completed.
532
+ *
533
+ * Both the fork and the downstream middleware are awaited with
534
+ * `Promise.all`, so you will only be to catch up to one error (the one that
535
+ * is thrown first).
536
+ *
537
+ * In opposite to the other middleware methods on composer, `fork` does not
538
+ * return simply return the composer connected to the main middleware stack.
539
+ * Instead, it returns the created composer _of the fork_ connected to the
540
+ * middleware stack. This allows for the following pattern.
541
+ * ```ts
542
+ * // Middleware will be run concurrently!
543
+ * bot.fork().on('message', ctx => { ... })
544
+ * ```
545
+ *
546
+ * @param middleware The middleware to run concurrently
547
+ */
548
+ fork(...middleware) {
549
+ const composer = new Composer(...middleware);
550
+ const fork = flatten(composer);
551
+ this.use((ctx, next) => Promise.all([next(), run(fork, ctx)]));
552
+ return composer;
553
+ }
554
+ /**
555
+ * > This is an advanced method of grammY.
556
+ *
557
+ * Executes some middleware that can be generated on the fly for each
558
+ * context. Pass a factory function that creates some middleware (or a
559
+ * middleware array even). The factory function will be called once per
560
+ * context, and its result will be executed with the context object.
561
+ * ```ts
562
+ * // The middleware returned by `createMyMiddleware` will be used only once
563
+ * bot.lazy(ctx => createMyMiddleware(ctx))
564
+ * ```
565
+ *
566
+ * You may generate this middleware in an `async` fashion.
567
+ *
568
+ * You can decide to return an empty array (`[]`) if you don't want to run
569
+ * any middleware for a given context object. This is equivalent to
570
+ * returning an empty instance of `Composer`.
571
+ *
572
+ * @param middlewareFactory The factory function creating the middleware
573
+ */
574
+ lazy(middlewareFactory) {
575
+ return this.use(async (ctx, next) => {
576
+ const middleware = await middlewareFactory(ctx);
577
+ const arr = Array.isArray(middleware) ? middleware : [middleware];
578
+ await flatten(new Composer(...arr))(ctx, next);
579
+ });
580
+ }
581
+ /**
582
+ * > This is an advanced method of grammY.
583
+ *
584
+ * _Not to be confused with the `router` plugin._
585
+ *
586
+ * This method is an alternative to the `router` plugin. It allows you to
587
+ * branch between different middleware per context object. You can pass two
588
+ * things to it:
589
+ * 1. A routing function
590
+ * 2. Different middleware identified by key
591
+ *
592
+ * The routing function decides based on the context object which middleware
593
+ * to run. Each middleware is identified by a key, so the routing function
594
+ * simply returns the key of that middleware.
595
+ * ```ts
596
+ * // Define different route handlers
597
+ * const routeHandlers = {
598
+ * evenUpdates: (ctx: Context) => { ... }
599
+ * oddUpdates: (ctx: Context) => { ... }
600
+ * }
601
+ * // Decide for a context object which one to pick
602
+ * const router = (ctx: Context) => ctx.update.update_id % 2 === 0
603
+ * ? 'evenUpdates'
604
+ * : 'oddUpdates'
605
+ * // Route it!
606
+ * bot.route(router, routeHandlers)
607
+ * ```
608
+ *
609
+ * Optionally, you can pass a third option that is used as fallback
610
+ * middleware if your route function returns `undefined`, or if the key
611
+ * returned by your router has no middleware associated with it.
612
+ *
613
+ * This method may need less setup than first instantiating a `Router`, but
614
+ * for more complex setups, having a `Router` may be more readable.
615
+ *
616
+ * @param router The routing function to use
617
+ * @param routeHandlers Handlers for every route
618
+ * @param fallback Optional fallback middleware if no route matches
619
+ */
620
+ route(router, routeHandlers, fallback = pass) {
621
+ return this.lazy(async (ctx) => {
622
+ var _a;
623
+ const route = await router(ctx);
624
+ return (_a = (route === undefined || !routeHandlers[route]
625
+ ? fallback
626
+ : routeHandlers[route])) !== null && _a !== void 0 ? _a : [];
627
+ });
628
+ }
629
+ /**
630
+ * > This is an advanced method of grammY.
631
+ *
632
+ * Allows you to branch between two cases for a given context object.
633
+ *
634
+ * This method takes a predicate function that is tested once per context
635
+ * object. If it returns `true`, the first supplied middleware is executed.
636
+ * If it returns `false`, the second supplied middleware is executed. Note
637
+ * that the predicate may be asynchronous, i.e. it can return a Promise of a
638
+ * boolean.
639
+ *
640
+ * @param predicate The predicate to check
641
+ * @param trueMiddleware The middleware for the `true` case
642
+ * @param falseMiddleware The middleware for the `false` case
643
+ */
644
+ branch(predicate, trueMiddleware, falseMiddleware) {
645
+ return this.lazy(async (ctx) => (await predicate(ctx)) ? trueMiddleware : falseMiddleware);
646
+ }
647
+ /**
648
+ * > This is an advanced function of grammY.
649
+ *
650
+ * Installs an error boundary that catches errors that happen only inside
651
+ * the given middleware. This allows you to install custom error handlers
652
+ * that protect some parts of your bot. Errors will not be able to bubble
653
+ * out of this part of your middleware system, unless the supplied error
654
+ * handler rethrows them, in which case the next surrounding error boundary
655
+ * will catch the error.
656
+ *
657
+ * Example usage:
658
+ * ```ts
659
+ * function errHandler(err: BotError) {
660
+ * console.error('Error boundary caught error!', err)
661
+ * }
662
+ *
663
+ * const safe =
664
+ * // All passed middleware will be protected by the error boundary.
665
+ * bot.errorBoundary(errHandler, middleware0, middleware1, middleware2)
666
+ *
667
+ * // Those will also be protected!
668
+ * safe.on('message', middleware3)
669
+ *
670
+ * // No error from `middleware4` will reach the `errHandler` from above,
671
+ * // as errors are suppressed.
672
+ *
673
+ * // do nothing on error (suppress error), and run outside middleware
674
+ * const suppress = (_err: BotError, next: NextFunction) => { return next() }
675
+ * safe.errorBoundary(suppress).on('edited_message', middleware4)
676
+ * ```
677
+ *
678
+ * Check out the
679
+ * [documentation](https://grammy.dev/guide/errors#error-boundaries) on
680
+ * the website to learn more about error boundaries.
681
+ *
682
+ * @param errorHandler The error handler to use
683
+ * @param middleware The middleware to protect
684
+ */
685
+ errorBoundary(errorHandler, ...middleware) {
686
+ const composer = new Composer(...middleware);
687
+ const bound = flatten(composer);
688
+ this.use(async (ctx, next) => {
689
+ let nextCalled = false;
690
+ const cont = () => ((nextCalled = true), Promise.resolve());
691
+ try {
692
+ await bound(ctx, cont);
693
+ }
694
+ catch (err) {
695
+ nextCalled = false;
696
+ await errorHandler(new BotError(err, ctx), cont);
697
+ }
698
+ if (nextCalled)
699
+ await next();
700
+ });
701
+ return composer;
702
+ }
703
+ }
704
+ exports.Composer = Composer;