/
context.ts
2971 lines (2849 loc) · 128 KB
/
context.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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// deno-lint-ignore-file camelcase
import { type Api, type Other as OtherApi } from "./core/api.ts";
import { type Methods, type RawApi } from "./core/client.ts";
import {
type Filter,
type FilterCore,
type FilterQuery,
matchFilter,
} from "./filter.ts";
import {
type Chat,
type ChatPermissions,
type InlineQueryResult,
type InputFile,
type InputMedia,
type InputMediaAudio,
type InputMediaDocument,
type InputMediaPhoto,
type InputMediaVideo,
type InputPollOption,
type LabeledPrice,
type Message,
type MessageEntity,
type PassportElementError,
type ReactionType,
type ReactionTypeEmoji,
type Update,
type User,
type UserFromGetMe,
} from "./types.ts";
// === Util types
export type MaybeArray<T> = T | T[];
export type StringWithSuggestions<S extends string> =
| (string & Record<never, never>)
| S; // permits `string` but gives hints
type Other<M extends Methods<RawApi>, X extends string = never> = OtherApi<
RawApi,
M,
X
>;
type SnakeToCamelCase<S extends string> = S extends `${infer L}_${infer R}`
? `${L}${Capitalize<SnakeToCamelCase<R>>}`
: S;
type AliasProps<U> = {
[K in string & keyof U as SnakeToCamelCase<K>]: U[K];
};
type RenamedUpdate = AliasProps<Omit<Update, "update_id">>;
// === Context probing logic
interface StaticHas {
/**
* Generates a predicate function that can test context objects for matching
* the given filter query. This uses the same logic as `bot.on`.
*
* @param filter The filter query to check
*/
filterQuery<Q extends FilterQuery>(
filter: Q | Q[],
): <C extends Context>(ctx: C) => ctx is Filter<C, Q>;
/**
* Generates a predicate function that can test context objects for
* containing the given text, or for the text to match the given regular
* expression. This uses the same logic as `bot.hears`.
*
* @param trigger The string or regex to match
*/
text(
trigger: MaybeArray<string | RegExp>,
): <C extends Context>(ctx: C) => ctx is HearsContext<C>;
/**
* Generates a predicate function that can test context objects for
* containing a command. This uses the same logic as `bot.command`.
*
* @param command The command to match
*/
command<S extends string>(
command: MaybeArray<
StringWithSuggestions<S | "start" | "help" | "settings">
>,
): <C extends Context>(ctx: C) => ctx is CommandContext<C>;
/**
* Generates a predicate function that can test context
* objects for containing a message reaction update. This uses the same
* logic as `bot.reaction`.
*
* @param reaction The reaction to test against
*/
reaction(
reaction: MaybeArray<ReactionTypeEmoji["emoji"] | ReactionType>,
): <C extends Context>(ctx: C) => ctx is ReactionContext<C>;
/**
* Generates a predicate function that can test context objects for
* belonging to a chat with the given chat type. This uses the same logic as
* `bot.chatType`.
*
* @param chatType The chat type to match
*/
chatType<T extends Chat["type"]>(
chatType: MaybeArray<T>,
): <C extends Context>(ctx: C) => ctx is ChatTypeContext<C, T>;
/**
* Generates a predicate function that can test context objects for
* containing the given callback query, or for the callback query data to
* match the given regular expression. This uses the same logic as
* `bot.callbackQuery`.
*
* @param trigger The string or regex to match
*/
callbackQuery(
trigger: MaybeArray<string | RegExp>,
): <C extends Context>(ctx: C) => ctx is CallbackQueryContext<C>;
/**
* Generates a predicate function that can test context objects for
* containing the given game query, or for the game name to match the given
* regular expression. This uses the same logic as `bot.gameQuery`.
*
* @param trigger The string or regex to match
*/
gameQuery(
trigger: MaybeArray<string | RegExp>,
): <C extends Context>(ctx: C) => ctx is GameQueryContext<C>;
/**
* Generates a predicate function that can test context objects for
* containing the given inline query, or for the inline query to match the
* given regular expression. This uses the same logic as `bot.inlineQuery`.
*
* @param trigger The string or regex to match
*/
inlineQuery(
trigger: MaybeArray<string | RegExp>,
): <C extends Context>(ctx: C) => ctx is InlineQueryContext<C>;
/**
* Generates a predicate function that can test context objects for
* containing the chosen inline result, or for the chosen inline result to
* match the given regular expression.
*
* @param trigger The string or regex to match
*/
chosenInlineResult(
trigger: MaybeArray<string | RegExp>,
): <C extends Context>(ctx: C) => ctx is ChosenInlineResultContext<C>;
}
const checker: StaticHas = {
filterQuery<Q extends FilterQuery>(filter: Q | Q[]) {
const pred = matchFilter(filter);
return <C extends Context>(ctx: C): ctx is Filter<C, Q> => pred(ctx);
},
text(trigger) {
const hasText = checker.filterQuery([":text", ":caption"]);
const trg = triggerFn(trigger);
return <C extends Context>(ctx: C): ctx is HearsContext<C> => {
if (!hasText(ctx)) return false;
const msg = ctx.message ?? ctx.channelPost;
const txt = msg.text ?? msg.caption;
return match(ctx, txt, trg);
};
},
command(command) {
const hasEntities = checker.filterQuery(":entities:bot_command");
const atCommands = new Set<string>();
const noAtCommands = new Set<string>();
toArray(command).forEach((cmd) => {
if (cmd.startsWith("/")) {
throw new Error(
`Do not include '/' when registering command handlers (use '${
cmd.substring(1)
}' not '${cmd}')`,
);
}
const set = cmd.includes("@") ? atCommands : noAtCommands;
set.add(cmd);
});
return <C extends Context>(ctx: C): ctx is CommandContext<C> => {
if (!hasEntities(ctx)) return false;
const msg = ctx.message ?? ctx.channelPost;
const txt = msg.text ?? msg.caption;
return msg.entities.some((e) => {
if (e.type !== "bot_command") return false;
if (e.offset !== 0) return false;
const cmd = txt.substring(1, e.length);
if (noAtCommands.has(cmd) || atCommands.has(cmd)) {
ctx.match = txt.substring(cmd.length + 1).trimStart();
return true;
}
const index = cmd.indexOf("@");
if (index === -1) return false;
const atTarget = cmd.substring(index + 1).toLowerCase();
const username = ctx.me.username.toLowerCase();
if (atTarget !== username) return false;
const atCommand = cmd.substring(0, index);
if (noAtCommands.has(atCommand)) {
ctx.match = txt.substring(cmd.length + 1).trimStart();
return true;
}
return false;
});
};
},
reaction(reaction) {
const hasMessageReaction = checker.filterQuery("message_reaction");
const normalized: ReactionType[] = typeof reaction === "string"
? [{ type: "emoji", emoji: reaction }]
: (Array.isArray(reaction) ? reaction : [reaction]).map((emoji) =>
typeof emoji === "string" ? { type: "emoji", emoji } : emoji
);
return <C extends Context>(ctx: C): ctx is ReactionContext<C> => {
if (!hasMessageReaction(ctx)) return false;
const { old_reaction, new_reaction } = ctx.messageReaction;
for (const reaction of new_reaction) {
let isOld = false;
if (reaction.type === "emoji") {
for (const old of old_reaction) {
if (old.type !== "emoji") continue;
if (old.emoji === reaction.emoji) {
isOld = true;
break;
}
}
} else if (reaction.type === "custom_emoji") {
for (const old of old_reaction) {
if (old.type !== "custom_emoji") continue;
if (old.custom_emoji_id === reaction.custom_emoji_id) {
isOld = true;
break;
}
}
} else {
// always regard unsupported emoji types as new
}
if (!isOld) {
if (reaction.type === "emoji") {
for (const wanted of normalized) {
if (wanted.type !== "emoji") continue;
if (wanted.emoji === reaction.emoji) {
return true;
}
}
} else if (reaction.type === "custom_emoji") {
for (const wanted of normalized) {
if (wanted.type !== "custom_emoji") continue;
if (
wanted.custom_emoji_id ===
reaction.custom_emoji_id
) {
return true;
}
}
} else {
// always regard unsupported emoji types as new
return true;
}
}
}
return false;
};
},
chatType<T extends Chat["type"]>(chatType: MaybeArray<T>) {
const set = new Set<Chat["type"]>(toArray(chatType));
return <C extends Context>(ctx: C): ctx is ChatTypeContext<C, T> =>
ctx.chat?.type !== undefined && set.has(ctx.chat.type);
},
callbackQuery(trigger) {
const hasCallbackQuery = checker.filterQuery("callback_query:data");
const trg = triggerFn(trigger);
return <C extends Context>(ctx: C): ctx is CallbackQueryContext<C> =>
hasCallbackQuery(ctx) && match(ctx, ctx.callbackQuery.data, trg);
},
gameQuery(trigger) {
const hasGameQuery = checker.filterQuery(
"callback_query:game_short_name",
);
const trg = triggerFn(trigger);
return <C extends Context>(ctx: C): ctx is GameQueryContext<C> =>
hasGameQuery(ctx) &&
match(ctx, ctx.callbackQuery.game_short_name, trg);
},
inlineQuery(trigger) {
const hasInlineQuery = checker.filterQuery("inline_query");
const trg = triggerFn(trigger);
return <C extends Context>(ctx: C): ctx is InlineQueryContext<C> =>
hasInlineQuery(ctx) && match(ctx, ctx.inlineQuery.query, trg);
},
chosenInlineResult(trigger) {
const hasChosenInlineResult = checker.filterQuery(
"chosen_inline_result",
);
const trg = triggerFn(trigger);
return <C extends Context>(
ctx: C,
): ctx is ChosenInlineResultContext<C> =>
hasChosenInlineResult(ctx) &&
match(ctx, ctx.chosenInlineResult.result_id, trg);
},
};
// === Context class
/**
* When your bot receives a message, Telegram sends an update object to your
* bot. The update contains information about the chat, the user, and of course
* the message itself. There are numerous other updates, too:
* https://core.telegram.org/bots/api#update
*
* When grammY receives an update, it wraps this update into a context object
* for you. Context objects are commonly named `ctx`. A context object does two
* things:
* 1. **`ctx.update`** holds the update object that you can use to process the
* message. This includes providing useful shortcuts for the update, for
* instance, `ctx.msg` is a shortcut that gives you the message object from
* the update—no matter whether it is contained in `ctx.update.message`, or
* `ctx.update.edited_message`, or `ctx.update.channel_post`, or
* `ctx.update.edited_channel_post`.
* 2. **`ctx.api`** gives you access to the full Telegram Bot API so that you
* can directly call any method, such as responding via
* `ctx.api.sendMessage`. Also here, the context objects has some useful
* shortcuts for you. For instance, if you want to send a message to the same
* chat that a message comes from (i.e. just respond to a user) you can call
* `ctx.reply`. This is nothing but a wrapper for `ctx.api.sendMessage` with
* the right `chat_id` pre-filled for you. Almost all methods of the Telegram
* Bot API have their own shortcut directly on the context object, so you
* probably never really have to use `ctx.api` at all.
*
* This context object is then passed to all of the listeners (called
* middleware) that you register on your bot. Because this is so useful, the
* context object is often used to hold more information. One example are
* sessions (a chat-specific data storage that is stored in a database), and
* another example is `ctx.match` that is used by `bot.command` and other
* methods to keep information about how a regular expression was matched.
*
* Read up about middleware on the
* [website](https://grammy.dev/guide/context.html) if you want to know more
* about the powerful opportunities that lie in context objects, and about how
* grammY implements them.
*/
export class Context implements RenamedUpdate {
/**
* Used by some middleware to store information about how a certain string
* or regular expression was matched.
*/
public match: string | RegExpMatchArray | undefined;
constructor(
/**
* The update object that is contained in the context.
*/
public readonly update: Update,
/**
* An API instance that allows you to call any method of the Telegram
* Bot API.
*/
public readonly api: Api,
/**
* Information about the bot itself.
*/
public readonly me: UserFromGetMe,
) {}
// UPDATE SHORTCUTS
/** Alias for `ctx.update.message` */
get message() {
return this.update.message;
}
/** Alias for `ctx.update.edited_message` */
get editedMessage() {
return this.update.edited_message;
}
/** Alias for `ctx.update.channel_post` */
get channelPost() {
return this.update.channel_post;
}
/** Alias for `ctx.update.edited_channel_post` */
get editedChannelPost() {
return this.update.edited_channel_post;
}
/** Alias for `ctx.update.business_connection` */
get businessConnection() {
return this.update.business_connection;
}
/** Alias for `ctx.update.business_message` */
get businessMessage() {
return this.update.business_message;
}
/** Alias for `ctx.update.edited_business_message` */
get editedBusinessMessage() {
return this.update.edited_business_message;
}
/** Alias for `ctx.update.deleted_business_messages` */
get deletedBusinessMessages() {
return this.update.deleted_business_messages;
}
/** Alias for `ctx.update.message_reaction` */
get messageReaction() {
return this.update.message_reaction;
}
/** Alias for `ctx.update.message_reaction_count` */
get messageReactionCount() {
return this.update.message_reaction_count;
}
/** Alias for `ctx.update.inline_query` */
get inlineQuery() {
return this.update.inline_query;
}
/** Alias for `ctx.update.chosen_inline_result` */
get chosenInlineResult() {
return this.update.chosen_inline_result;
}
/** Alias for `ctx.update.callback_query` */
get callbackQuery() {
return this.update.callback_query;
}
/** Alias for `ctx.update.shipping_query` */
get shippingQuery() {
return this.update.shipping_query;
}
/** Alias for `ctx.update.pre_checkout_query` */
get preCheckoutQuery() {
return this.update.pre_checkout_query;
}
/** Alias for `ctx.update.poll` */
get poll() {
return this.update.poll;
}
/** Alias for `ctx.update.poll_answer` */
get pollAnswer() {
return this.update.poll_answer;
}
/** Alias for `ctx.update.my_chat_member` */
get myChatMember() {
return this.update.my_chat_member;
}
/** Alias for `ctx.update.chat_member` */
get chatMember() {
return this.update.chat_member;
}
/** Alias for `ctx.update.chat_join_request` */
get chatJoinRequest() {
return this.update.chat_join_request;
}
/** Alias for `ctx.update.chat_boost` */
get chatBoost() {
return this.update.chat_boost;
}
/** Alias for `ctx.update.removed_chat_boost` */
get removedChatBoost() {
return this.update.removed_chat_boost;
}
// AGGREGATION SHORTCUTS
/**
* Get the message object from wherever possible. Alias for `this.message ??
* this.editedMessage ?? this.channelPost ?? this.editedChannelPost ??
* this.businessMessage ?? this.editedBusinessMessage ??
* this.callbackQuery?.message`.
*/
get msg(): Message | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.message ??
this.editedMessage ??
this.channelPost ??
this.editedChannelPost ??
this.businessMessage ??
this.editedBusinessMessage ??
this.callbackQuery?.message
);
}
/**
* Get the chat object from wherever possible. Alias for `(this.msg ??
* this.deletedBusinessMessages ?? this.messageReaction ??
* this.messageReactionCount ?? this.myChatMember ?? this.chatMember ??
* this.chatJoinRequest ?? this.chatBoost ?? this.removedChatBoost)?.chat`.
*/
get chat(): Chat | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.msg ??
this.deletedBusinessMessages ??
this.messageReaction ??
this.messageReactionCount ??
this.myChatMember ??
this.chatMember ??
this.chatJoinRequest ??
this.chatBoost ??
this.removedChatBoost
)?.chat;
}
/**
* Get the sender chat object from wherever possible. Alias for
* `ctx.msg?.sender_chat`.
*/
get senderChat(): Chat | undefined {
// Keep in sync with types in `filter.ts`.
return this.msg?.sender_chat;
}
/**
* Get the user object from wherever possible. Alias for
* `(this.businessConnection ?? this.messageReaction ??
* (this.chatBoost?.boost ?? this.removedChatBoost)?.source)?.user ??
* (this.callbackQuery ?? this.msg ?? this.inlineQuery ??
* this.chosenInlineResult ?? this.shippingQuery ?? this.preCheckoutQuery ??
* this.myChatMember ?? this.chatMember ?? this.chatJoinRequest)?.from`.
*/
get from(): User | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.businessConnection ??
this.messageReaction ??
(this.chatBoost?.boost ?? this.removedChatBoost)?.source
)?.user ??
(
this.callbackQuery ??
this.msg ??
this.inlineQuery ??
this.chosenInlineResult ??
this.shippingQuery ??
this.preCheckoutQuery ??
this.myChatMember ??
this.chatMember ??
this.chatJoinRequest
)?.from;
}
/**
* Get the message identifier from wherever possible. Alias for
* `this.msg?.message_id ?? this.messageReaction?.message_id ??
* this.messageReactionCount?.message_id`.
*/
get msgId(): number | undefined {
// Keep in sync with types in `filter.ts`.
return this.msg?.message_id ?? this.messageReaction?.message_id ??
this.messageReactionCount?.message_id;
}
/**
* Gets the chat identifier from wherever possible. Alias for `this.chat?.id
* ?? this.businessConnection?.user_chat_id`.
*/
get chatId(): number | undefined {
// Keep in sync with types in `filter.ts`.
return this.chat?.id ?? this.businessConnection?.user_chat_id;
}
/**
* Get the inline message identifier from wherever possible. Alias for
* `(ctx.callbackQuery ?? ctx.chosenInlineResult)?.inline_message_id`.
*/
get inlineMessageId(): string | undefined {
return (
this.callbackQuery?.inline_message_id ??
this.chosenInlineResult?.inline_message_id
);
}
/**
* Get the business connection identifier from wherever possible. Alias for
* `this.msg?.business_connection_id ?? this.businessConnection?.id ??
* this.deletedBusinessMessages?.business_connection_id`.
*/
get businessConnectionId(): string | undefined {
return this.msg?.business_connection_id ??
this.businessConnection?.id ??
this.deletedBusinessMessages?.business_connection_id;
}
/**
* Get entities and their text. Extracts the text from `ctx.msg.text` or `ctx.msg.caption`.
* Returns an empty array if one of `ctx.msg`, `ctx.msg.text`
* or `ctx.msg.entities` is undefined.
*
* You can filter specific entity types by passing the `types` parameter. Example:
*
* ```ts
* ctx.entities() // Returns all entity types
* ctx.entities('url') // Returns only url entities
* ctx.enttities(['url', 'email']) // Returns url and email entities
* ```
*
* @param types Types of entities to return. Omit to get all entities.
* @returns Array of entities and their texts, or empty array when there's no text
*/
entities(): Array<
MessageEntity & {
/** Slice of the message text that contains this entity */
text: string;
}
>;
entities<T extends MessageEntity["type"]>(
types: MaybeArray<T>,
): Array<
MessageEntity & {
type: T;
/** Slice of the message text that contains this entity */
text: string;
}
>;
entities(types?: MaybeArray<MessageEntity["type"]>) {
const message = this.msg;
if (message === undefined) return [];
const text = message.text ?? message.caption;
if (text === undefined) return [];
let entities = message.entities ?? message.caption_entities;
if (entities === undefined) return [];
if (types !== undefined) {
const filters = new Set(toArray(types));
entities = entities.filter((entity) => filters.has(entity.type));
}
return entities.map((entity) => ({
...entity,
text: text.substring(entity.offset, entity.offset + entity.length),
}));
}
/**
* Find out which reactions were added and removed in a `message_reaction`
* update. This method looks at `ctx.messageReaction` and computes the
* difference between the old reaction and the new reaction. It also groups
* the reactions by emoji reactions and custom emoji reactions. For example,
* the resulting object could look like this:
* ```ts
* {
* emoji: ['👍', '🎉']
* emojiAdded: ['🎉'],
* emojiKept: ['👍'],
* emojiRemoved: [],
* customEmoji: [],
* customEmojiAdded: [],
* customEmojiKept: [],
* customEmojiRemoved: ['id0123'],
* }
* ```
* In the above example, a tada reaction was added by the user, and a custom
* emoji reaction with the custom emoji 'id0123' was removed in the same
* update. The user had already reacted with a thumbs up reaction, which
* they left unchanged. As a result, the current reaction by the user is
* thumbs up and tada. Note that the current reaction (both emoji and custom
* emoji in one list) can also be obtained from
* `ctx.messageReaction.new_reaction`.
*
* Remember that reaction updates only include information about the
* reaction of a specific user. The respective message may have many more
* reactions by other people which will not be included in this update.
*
* @returns An object containing information about the reaction update
*/
reactions(): {
/** Emoji currently present in this user's reaction */
emoji: ReactionTypeEmoji["emoji"][];
/** Emoji newly added to this user's reaction */
emojiAdded: ReactionTypeEmoji["emoji"][];
/** Emoji not changed by the update to this user's reaction */
emojiKept: ReactionTypeEmoji["emoji"][];
/** Emoji removed from this user's reaction */
emojiRemoved: ReactionTypeEmoji["emoji"][];
/** Custom emoji currently present in this user's reaction */
customEmoji: string[];
/** Custom emoji newly added to this user's reaction */
customEmojiAdded: string[];
/** Custom emoji not changed by the update to this user's reaction */
customEmojiKept: string[];
/** Custom emoji removed from this user's reaction */
customEmojiRemoved: string[];
} {
const emoji: ReactionTypeEmoji["emoji"][] = [];
const emojiAdded: ReactionTypeEmoji["emoji"][] = [];
const emojiKept: ReactionTypeEmoji["emoji"][] = [];
const emojiRemoved: ReactionTypeEmoji["emoji"][] = [];
const customEmoji: string[] = [];
const customEmojiAdded: string[] = [];
const customEmojiKept: string[] = [];
const customEmojiRemoved: string[] = [];
const r = this.messageReaction;
if (r !== undefined) {
const { old_reaction, new_reaction } = r;
// group all current emoji in `emoji` and `customEmoji`
for (const reaction of new_reaction) {
if (reaction.type === "emoji") {
emoji.push(reaction.emoji);
} else if (reaction.type === "custom_emoji") {
customEmoji.push(reaction.custom_emoji_id);
}
}
// temporarily move all old emoji to the *Removed arrays
for (const reaction of old_reaction) {
if (reaction.type === "emoji") {
emojiRemoved.push(reaction.emoji);
} else if (reaction.type === "custom_emoji") {
customEmojiRemoved.push(reaction.custom_emoji_id);
}
}
// temporarily move all new emoji to the *Added arrays
emojiAdded.push(...emoji);
customEmojiAdded.push(...customEmoji);
// drop common emoji from both lists and add them to `emojiKept`
for (let i = 0; i < emojiRemoved.length; i++) {
const len = emojiAdded.length;
if (len === 0) break;
const rem = emojiRemoved[i];
for (let j = 0; j < len; j++) {
if (rem === emojiAdded[j]) {
emojiKept.push(rem);
emojiRemoved.splice(i, 1);
emojiAdded.splice(j, 1);
i--;
break;
}
}
}
// drop common custom emoji from both lists and add them to `customEmojiKept`
for (let i = 0; i < customEmojiRemoved.length; i++) {
const len = customEmojiAdded.length;
if (len === 0) break;
const rem = customEmojiRemoved[i];
for (let j = 0; j < len; j++) {
if (rem === customEmojiAdded[j]) {
customEmojiKept.push(rem);
customEmojiRemoved.splice(i, 1);
customEmojiAdded.splice(j, 1);
i--;
break;
}
}
}
}
return {
emoji,
emojiAdded,
emojiKept,
emojiRemoved,
customEmoji,
customEmojiAdded,
customEmojiKept,
customEmojiRemoved,
};
}
// PROBING SHORTCUTS
/**
* `Context.has` is an object that contains a number of useful functions for
* probing context objects. Each of these functions can generate a predicate
* function, to which you can pass context objects in order to check if a
* condition holds for the respective context object.
*
* For example, you can call `Context.has.filterQuery(":text")` to generate
* a predicate function that tests context objects for containing text:
* ```ts
* const hasText = Context.has.filterQuery(":text");
*
* if (hasText(ctx0)) {} // `ctx0` matches the filter query `:text`
* if (hasText(ctx1)) {} // `ctx1` matches the filter query `:text`
* if (hasText(ctx2)) {} // `ctx2` matches the filter query `:text`
* ```
* These predicate functions are used internally by the has-methods that are
* installed on every context object. This means that calling
* `ctx.has(":text")` is equivalent to
* `Context.has.filterQuery(":text")(ctx)`.
*/
static has = checker;
/**
* Returns `true` if this context object matches the given filter query, and
* `false` otherwise. This uses the same logic as `bot.on`.
*
* @param filter The filter query to check
*/
has<Q extends FilterQuery>(filter: Q | Q[]): this is FilterCore<Q> {
return Context.has.filterQuery(filter)(this);
}
/**
* Returns `true` if this context object contains the given text, or if it
* contains text that matches the given regular expression. It returns
* `false` otherwise. This uses the same logic as `bot.hears`.
*
* @param trigger The string or regex to match
*/
hasText(trigger: MaybeArray<string | RegExp>): this is HearsContextCore {
return Context.has.text(trigger)(this);
}
/**
* Returns `true` if this context object contains the given command, and
* `false` otherwise. This uses the same logic as `bot.command`.
*
* @param command The command to match
*/
hasCommand<S extends string>(
command: MaybeArray<
StringWithSuggestions<S | "start" | "help" | "settings">
>,
): this is CommandContextCore {
return Context.has.command(command)(this);
}
hasReaction(
reaction: MaybeArray<ReactionTypeEmoji["emoji"] | ReactionType>,
): this is ReactionContextCore {
return Context.has.reaction(reaction)(this);
}
/**
* Returns `true` if this context object belongs to a chat with the given
* chat type, and `false` otherwise. This uses the same logic as
* `bot.chatType`.
*
* @param chatType The chat type to match
*/
hasChatType<T extends Chat["type"]>(
chatType: MaybeArray<T>,
): this is ChatTypeContextCore<T> {
return Context.has.chatType(chatType)(this);
}
/**
* Returns `true` if this context object contains the given callback query,
* or if the contained callback query data matches the given regular
* expression. It returns `false` otherwise. This uses the same logic as
* `bot.callbackQuery`.
*
* @param trigger The string or regex to match
*/
hasCallbackQuery(
trigger: MaybeArray<string | RegExp>,
): this is CallbackQueryContextCore {
return Context.has.callbackQuery(trigger)(this);
}
/**
* Returns `true` if this context object contains the given game query, or
* if the contained game query matches the given regular expression. It
* returns `false` otherwise. This uses the same logic as `bot.gameQuery`.
*
* @param trigger The string or regex to match
*/
hasGameQuery(
trigger: MaybeArray<string | RegExp>,
): this is GameQueryContextCore {
return Context.has.gameQuery(trigger)(this);
}
/**
* Returns `true` if this context object contains the given inline query, or
* if the contained inline query matches the given regular expression. It
* returns `false` otherwise. This uses the same logic as `bot.inlineQuery`.
*
* @param trigger The string or regex to match
*/
hasInlineQuery(
trigger: MaybeArray<string | RegExp>,
): this is InlineQueryContextCore {
return Context.has.inlineQuery(trigger)(this);
}
/**
* Returns `true` if this context object contains the chosen inline result, or
* if the contained chosen inline result matches the given regular expression. It
* returns `false` otherwise. This uses the same logic as `bot.chosenInlineResult`.
*
* @param trigger The string or regex to match
*/
hasChosenInlineResult(
trigger: MaybeArray<string | RegExp>,
): this is ChosenInlineResultContextCore {
return Context.has.chosenInlineResult(trigger)(this);
}
// API
/**
* Context-aware alias for `api.sendMessage`. Use this method to send text messages. On success, the sent Message is returned.
*
* @param text Text of the message to be sent, 1-4096 characters after entities parsing
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#sendmessage
*/
reply(
text: string,
other?: Other<"sendMessage", "chat_id" | "text">,
signal?: AbortSignal,
) {
return this.api.sendMessage(
orThrow(this.chatId, "sendMessage"),
text,
{ business_connection_id: this.businessConnectionId, ...other },
signal,
);
}
/**
* Context-aware alias for `api.forwardMessage`. Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent Message is returned.
*
* @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#forwardmessage
*/
forwardMessage(
chat_id: number | string,
other?: Other<
"forwardMessage",
"chat_id" | "from_chat_id" | "message_id"
>,
signal?: AbortSignal,
) {
return this.api.forwardMessage(
chat_id,
orThrow(this.chatId, "forwardMessage"),
orThrow(this.msgId, "forwardMessage"),
other,
signal,
);
}
/**
* Context-aware alias for `api.forwardMessages`. Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of MessageId of the sent messages is returned.
*
* @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param message_ids A list of 1-100 identifiers of messages in the current chat to forward. The identifiers must be specified in a strictly increasing order.
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#forwardmessages
*/
forwardMessages(
chat_id: number | string,
message_ids: number[],
other?: Other<
"forwardMessages",
"chat_id" | "from_chat_id" | "message_ids"
>,
signal?: AbortSignal,
) {
return this.api.forwardMessages(
chat_id,
orThrow(this.chatId, "forwardMessages"),
message_ids,
other,
signal,
);
}
/**
* Context-aware alias for `api.copyMessage`. Use this method to copy messages of any kind. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessage, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
*
* @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#copymessage
*/
copyMessage(
chat_id: number | string,
other?: Other<"copyMessage", "chat_id" | "from_chat_id" | "message_id">,
signal?: AbortSignal,
) {
return this.api.copyMessage(
chat_id,
orThrow(this.chatId, "copyMessage"),
orThrow(this.msgId, "copyMessage"),
other,
signal,
);
}
/**
* Context-aware alias for `api.copyMessages`.Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz poll can be copied only if the value of the field correct_option_id is known to the bot. The method is analogous to the method forwardMessages, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of MessageId of the sent messages is returned.
*
* @param chat_id Unique identifier for the target chat or username of the target channel (in the format @channelusername)
* @param message_ids A list of 1-100 identifiers of messages in the current chat to copy. The identifiers must be specified in a strictly increasing order.
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#copymessages
*/
copyMessages(
chat_id: number | string,
message_ids: number[],
other?: Other<
"copyMessages",
"chat_id" | "from_chat_id" | "message_id"
>,
signal?: AbortSignal,
) {
return this.api.copyMessages(
chat_id,
orThrow(this.chatId, "copyMessages"),
message_ids,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendPhoto`. Use this method to send photos. On success, the sent Message is returned.
*
* @param photo Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20.
* @param other Optional remaining parameters, confer the official reference below
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#sendphoto
*/
replyWithPhoto(
photo: InputFile | string,
other?: Other<"sendPhoto", "chat_id" | "photo">,
signal?: AbortSignal,