/
context.ts
2230 lines (2132 loc) · 94 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 LabeledPrice,
type Message,
type MessageEntity,
type PassportElementError,
type Update,
type User,
type UserFromGetMe,
} from "./types.ts";
// === Util types
export type MaybeArray<T> = T | T[];
// deno-lint-ignore ban-types
export type StringWithSuggestions<S extends string> = (string & {}) | 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;
export 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
* 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>;
}
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.indexOf("@") === -1 ? noAtCommands : atCommands;
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);
if (atTarget !== ctx.me.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;
});
};
},
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);
},
};
// === 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.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;
}
// AGGREGATION SHORTCUTS
/**
* Get message object from wherever possible. Alias for `ctx.message ??
* ctx.editedMessage ?? ctx.callbackQuery?.message ?? ctx.channelPost ??
* ctx.editedChannelPost`
*/
get msg(): Message | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.message ??
this.editedMessage ??
this.callbackQuery?.message ??
this.channelPost ??
this.editedChannelPost
);
}
/**
* Get chat object from wherever possible. Alias for `(ctx.msg ??
* ctx.myChatMember ?? ctx.chatMember ?? ctx.chatJoinRequest)?.chat`
*/
get chat(): Chat | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.msg ??
this.myChatMember ??
this.chatMember ??
this.chatJoinRequest
)?.chat;
}
/**
* Get sender chat object from wherever possible. Alias for
* `ctx.msg?.sender_chat`.
*/
get senderChat(): Chat | undefined {
return this.msg?.sender_chat;
}
/**
* Get message author from wherever possible. Alias for
* `(ctx.callbackQuery?? ctx.inlineQuery ?? ctx.shippingQuery ??
* ctx.preCheckoutQuery ?? ctx.chosenInlineResult ?? ctx.msg ??
* ctx.myChatMember ?? ctx.chatMember ?? ctx.chatJoinRequest)?.from`
*/
get from(): User | undefined {
// Keep in sync with types in `filter.ts`.
return (
this.callbackQuery ??
this.inlineQuery ??
this.shippingQuery ??
this.preCheckoutQuery ??
this.chosenInlineResult ??
this.msg ??
this.myChatMember ??
this.chatMember ??
this.chatJoinRequest
)?.from;
}
/**
* Get inline message ID 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
);
}
// 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);
}
/**
* 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);
}
// 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.chat, "sendMessage").id,
text,
other,
signal,
);
}
/**
* Context-aware alias for `api.forwardMessage`. Use this method to forward messages of any kind. Service messages 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.chat, "forwardMessage").id,
orThrow(this.msg, "forwardMessage").message_id,
other,
signal,
);
}
/**
* Context-aware alias for `api.copyMessage`. Use this method to copy messages of any kind. Service 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.chat, "copyMessage").id,
orThrow(this.msg, "copyMessage").message_id,
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,
) {
return this.api.sendPhoto(
orThrow(this.chat, "sendPhoto").id,
photo,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendAudio`. Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
*
* For sending voice messages, use the sendVoice method instead.
*
* @param audio Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data.
* @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#sendaudio
*/
replyWithAudio(
audio: InputFile | string,
other?: Other<"sendAudio", "chat_id" | "audio">,
signal?: AbortSignal,
) {
return this.api.sendAudio(
orThrow(this.chat, "sendAudio").id,
audio,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendDocument`. Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
*
* @param document File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
* @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#senddocument
*/
replyWithDocument(
document: InputFile | string,
other?: Other<"sendDocument", "chat_id" | "document">,
signal?: AbortSignal,
) {
return this.api.sendDocument(
orThrow(this.chat, "sendDocument").id,
document,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendVideo`. Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
*
* @param video Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data.
* @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#sendvideo
*/
replyWithVideo(
video: InputFile | string,
other?: Other<"sendVideo", "chat_id" | "video">,
signal?: AbortSignal,
) {
return this.api.sendVideo(
orThrow(this.chat, "sendVideo").id,
video,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendAnimation`. Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
*
* @param animation Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data.
* @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#sendanimation
*/
replyWithAnimation(
animation: InputFile | string,
other?: Other<"sendAnimation", "chat_id" | "animation">,
signal?: AbortSignal,
) {
return this.api.sendAnimation(
orThrow(this.chat, "sendAnimation").id,
animation,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendVoice`. Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS (other formats may be sent as Audio or Document). On success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
*
* @param voice Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data.
* @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#sendvoice
*/
replyWithVoice(
voice: InputFile | string,
other?: Other<"sendVoice", "chat_id" | "voice">,
signal?: AbortSignal,
) {
return this.api.sendVoice(
orThrow(this.chat, "sendVoice").id,
voice,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendVideoNote`. Use this method to send video messages. On success, the sent Message is returned.
* As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.
*
* @param video_note Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data.. Sending video notes by a URL is currently unsupported
* @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#sendvideonote
*/
replyWithVideoNote(
video_note: InputFile | string,
other?: Other<"sendVideoNote", "chat_id" | "video_note">,
signal?: AbortSignal,
) {
return this.api.sendVideoNote(
orThrow(this.chat, "sendVideoNote").id,
video_note,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendMediaGroup`. Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of Messages that were sent is returned.
*
* @param media An array describing messages to be sent, must include 2-10 items
* @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#sendmediagroup
*/
replyWithMediaGroup(
media: ReadonlyArray<
| InputMediaAudio
| InputMediaDocument
| InputMediaPhoto
| InputMediaVideo
>,
other?: Other<"sendMediaGroup", "chat_id" | "media">,
signal?: AbortSignal,
) {
return this.api.sendMediaGroup(
orThrow(this.chat, "sendMediaGroup").id,
media,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendLocation`. Use this method to send point on the map. On success, the sent Message is returned.
*
* @param latitude Latitude of the location
* @param longitude Longitude of the location
* @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#sendlocation
*/
replyWithLocation(
latitude: number,
longitude: number,
other?: Other<"sendLocation", "chat_id" | "latitude" | "longitude">,
signal?: AbortSignal,
) {
return this.api.sendLocation(
orThrow(this.chat, "sendLocation").id,
latitude,
longitude,
other,
signal,
);
}
/**
* Context-aware alias for `api.editMessageLiveLocation`. Use this method to edit live location messages. A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned.
*
* @param latitude Latitude of new location
* @param longitude Longitude of new location
* @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#editmessagelivelocation
*/
editMessageLiveLocation(
latitude: number,
longitude: number,
other?: Other<
"editMessageLiveLocation",
| "chat_id"
| "message_id"
| "inline_message_id"
| "latitude"
| "longitude"
>,
signal?: AbortSignal,
) {
const inlineId = this.inlineMessageId;
return inlineId !== undefined
? this.api.editMessageLiveLocationInline(
inlineId,
latitude,
longitude,
other,
)
: this.api.editMessageLiveLocation(
orThrow(this.chat, "editMessageLiveLocation").id,
orThrow(this.msg, "editMessageLiveLocation").message_id,
latitude,
longitude,
other,
signal,
);
}
/**
* Context-aware alias for `api.stopMessageLiveLocation`. Use this method to stop updating a live location message before live_period expires. On success, if the message is not an inline message, the edited Message is returned, otherwise True is returned.
*
* @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#stopmessagelivelocation
*/
stopMessageLiveLocation(
other?: Other<
"stopMessageLiveLocation",
"chat_id" | "message_id" | "inline_message_id"
>,
signal?: AbortSignal,
) {
const inlineId = this.inlineMessageId;
return inlineId !== undefined
? this.api.stopMessageLiveLocationInline(inlineId, other)
: this.api.stopMessageLiveLocation(
orThrow(this.chat, "stopMessageLiveLocation").id,
orThrow(this.msg, "stopMessageLiveLocation").message_id,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendVenue`. Use this method to send information about a venue. On success, the sent Message is returned.
*
* @param latitude Latitude of the venue
* @param longitude Longitude of the venue
* @param title Name of the venue
* @param address Address of the venue
* @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#sendvenue
*/
replyWithVenue(
latitude: number,
longitude: number,
title: string,
address: string,
other?: Other<
"sendVenue",
"chat_id" | "latitude" | "longitude" | "title" | "address"
>,
signal?: AbortSignal,
) {
return this.api.sendVenue(
orThrow(this.chat, "sendVenue").id,
latitude,
longitude,
title,
address,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendContact`. Use this method to send phone contacts. On success, the sent Message is returned.
*
* @param phone_number Contact's phone number
* @param first_name Contact's first name
* @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#sendcontact
*/
replyWithContact(
phone_number: string,
first_name: string,
other?: Other<"sendContact", "chat_id" | "phone_number" | "first_name">,
signal?: AbortSignal,
) {
return this.api.sendContact(
orThrow(this.chat, "sendContact").id,
phone_number,
first_name,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendPoll`. Use this method to send a native poll. On success, the sent Message is returned.
*
* @param question Poll question, 1-300 characters
* @param options A list of answer options, 2-10 strings 1-100 characters each
* @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#sendpoll
*/
replyWithPoll(
question: string,
options: readonly string[],
other?: Other<"sendPoll", "chat_id" | "question" | "options">,
signal?: AbortSignal,
) {
return this.api.sendPoll(
orThrow(this.chat, "sendPoll").id,
question,
options,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendDice`. Use this method to send an animated emoji that will display a random value. On success, the sent Message is returned.
*
* @param emoji Emoji on which the dice throw animation is based. Currently, must be one of “🎲”, “🎯”, “🏀”, “⚽”, or “🎰”. Dice can have values 1-6 for “🎲” and “🎯”, values 1-5 for “🏀” and “⚽”, and values 1-64 for “🎰”. Defaults to “🎲”
* @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#senddice
*/
replyWithDice(
emoji: string,
other?: Other<"sendDice", "chat_id" | "emoji">,
signal?: AbortSignal,
) {
return this.api.sendDice(
orThrow(this.chat, "sendDice").id,
emoji,
other,
signal,
);
}
/**
* Context-aware alias for `api.sendChatAction`. Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
*
* Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot.
*
* We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive.
*
* @param action Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_voice or upload_voice for voice notes, upload_document for general files, choose_sticker for stickers, find_location for location data, record_video_note or upload_video_note for video notes.
* @param signal Optional `AbortSignal` to cancel the request
*
* **Official reference:** https://core.telegram.org/bots/api#sendchataction
*/
replyWithChatAction(
action:
| "typing"
| "upload_photo"
| "record_video"
| "upload_video"
| "record_voice"
| "upload_voice"
| "upload_document"
| "find_location"
| "record_video_note"
| "upload_video_note",
signal?: AbortSignal,
) {
return this.api.sendChatAction(
orThrow(this.chat, "sendChatAction").id,
action,
signal,
);
}
/**
* Context-aware alias for `api.getUserProfilePhotos`. Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
*
* @param user_id Unique identifier of the target user
* @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#getuserprofilephotos
*/
getUserProfilePhotos(
other?: Other<"getUserProfilePhotos", "user_id">,
signal?: AbortSignal,
) {
return this.api.getUserProfilePhotos(
orThrow(this.from, "getUserProfilePhotos").id,
other,