deno.land / x / grammy@v1.22.4 / 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
// deno-lint-ignore-file camelcaseimport { 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 ReactionType, type ReactionTypeEmoji, type Update, type User, type UserFromGetMe,} from "./types.ts";
// === Util typesexport type MaybeArray<T> = T | T[];export type StringWithSuggestions<S extends string> = | (string & Record<never, never>) | S; // permits `string` but gives hintstype 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 logicinterface 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; } /** * 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.chat, "sendMessage").id, 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.chat, "forwardMessage").id, 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.chat, "forwardMessages").id, 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.chat, "copyMessage").id, 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.chat, "copyMessages").id, 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, ) { return this.api.sendPhoto( orThrow(this.chat, "sendPhoto").id, photo, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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.msgId, "editMessageLiveLocation"), 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.msgId, "stopMessageLiveLocation"), 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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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, { business_connection_id: this.businessConnectionId, ...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 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#sendchataction */ replyWithChatAction( action: | "typing" | "upload_photo" | "record_video" | "upload_video" | "record_voice" | "upload_voice" | "upload_document" | "choose_sticker" | "find_location" | "record_video_note" | "upload_video_note", other?: Other<"sendChatAction", "chat_id" | "action">, signal?: AbortSignal, ) { return this.api.sendChatAction( orThrow(this.chat, "sendChatAction").id, action, { business_connection_id: this.businessConnectionId, ...other }, signal, ); } /** * Context-aware alias for `api.setMessageReaction`. Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. In albums, bots must react to the first message. Returns True on success. * * @param reaction A list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. * @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#setmessagereaction */ react( reaction: MaybeArray<ReactionTypeEmoji["emoji"] | ReactionType>, other?: Other< "setMessageReaction", "chat_id" | "message_id" | "reaction" >, signal?: AbortSignal, ) { return this.api.setMessageReaction( orThrow(this.chat, "setMessageReaction").id, orThrow(this.msgId, "setMessageReaction"), typeof reaction === "string" ? [{ type: "emoji", emoji: reaction }] : (Array.isArray(reaction) ? reaction : [reaction]) .map((emoji) => typeof emoji === "string" ? { type: "emoji", emoji } : emoji ), other, 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, signal, ); } /** * Context-aware alias for `api.getUserChatBoosts`. Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a UserChatBoosts object. * * @param chat_id Unique identifier for the chat or username of the channel (in the format @channelusername) * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getuserchatboosts */ getUserChatBoosts(chat_id: number | string, signal?: AbortSignal) { return this.api.getUserChatBoosts( chat_id, orThrow(this.from, "getUserChatBoosts").id, signal, ); } /** * Context-aware alias for `api.getBusinessConnection`. Use this method to get information about the connection of the bot with a business account. Returns a BusinessConnection object on success. * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getbusinessconnection */ getBusinessConnection(signal?: AbortSignal) { return this.api.getBusinessConnection( orThrow(this.businessConnectionId, "getBusinessConnection"), signal, ); } /** * Context-aware alias for `api.getFile`. Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. * * Note: This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getfile */ getFile(signal?: AbortSignal) { const m = orThrow(this.msg, "getFile"); const file = m.photo !== undefined ? m.photo[m.photo.length - 1] : m.animation ?? m.audio ?? m.document ?? m.video ?? m.video_note ?? m.voice ?? m.sticker; return this.api.getFile(orThrow(file, "getFile").file_id, signal); } /** @deprecated Use `banAuthor` instead. */ kickAuthor(...args: Parameters<Context["banAuthor"]>) { return this.banAuthor(...args); } /** * Context-aware alias for `api.banChatMember`. Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @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#banchatmember */ banAuthor( other?: Other<"banChatMember", "chat_id" | "user_id">, signal?: AbortSignal, ) { return this.api.banChatMember( orThrow(this.chat, "banAuthor").id, orThrow(this.from, "banAuthor").id, other, signal, ); } /** @deprecated Use `banChatMember` instead. */ kickChatMember(...args: Parameters<Context["banChatMember"]>) { return this.banChatMember(...args); } /** * Context-aware alias for `api.banChatMember`. Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless unbanned first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @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#banchatmember */ banChatMember( user_id: number, other?: Other<"banChatMember", "chat_id" | "user_id">, signal?: AbortSignal, ) { return this.api.banChatMember( orThrow(this.chat, "banChatMember").id, user_id, other, signal, ); } /** * Context-aware alias for `api.unbanChatMember`. Use this method to unban a previously banned user in a supergroup or channel. The user will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be removed from the chat. If you don't want this, use the parameter only_if_banned. Returns True on success. * * @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#unbanchatmember */ unbanChatMember( user_id: number, other?: Other<"unbanChatMember", "chat_id" | "user_id">, signal?: AbortSignal, ) { return this.api.unbanChatMember( orThrow(this.chat, "unbanChatMember").id, user_id, other, signal, ); } /** * Context-aware alias for `api.restrictChatMember`. Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. * * @param permissions An object for new user permissions * @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#restrictchatmember */ restrictAuthor( permissions: ChatPermissions, other?: Other< "restrictChatMember", "chat_id" | "user_id" | "permissions" >, signal?: AbortSignal, ) { return this.api.restrictChatMember( orThrow(this.chat, "restrictAuthor").id, orThrow(this.from, "restrictAuthor").id, permissions, other, signal, ); } /** * Context-aware alias for `api.restrictChatMember`. Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass True for all permissions to lift restrictions from a user. Returns True on success. * * @param user_id Unique identifier of the target user * @param permissions An object for new user permissions * @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#restrictchatmember */ restrictChatMember( user_id: number, permissions: ChatPermissions, other?: Other< "restrictChatMember", "chat_id" | "user_id" | "permissions" >, signal?: AbortSignal, ) { return this.api.restrictChatMember( orThrow(this.chat, "restrictChatMember").id, user_id, permissions, other, signal, ); } /** * Context-aware alias for `api.promoteChatMember`. Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. * * @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#promotechatmember */ promoteAuthor( other?: Other<"promoteChatMember", "chat_id" | "user_id">, signal?: AbortSignal, ) { return this.api.promoteChatMember( orThrow(this.chat, "promoteAuthor").id, orThrow(this.from, "promoteAuthor").id, other, signal, ); } /** * Context-aware alias for `api.promoteChatMember`. Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass False for all boolean parameters to demote a user. Returns True on success. * * @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#promotechatmember */ promoteChatMember( user_id: number, other?: Other<"promoteChatMember", "chat_id" | "user_id">, signal?: AbortSignal, ) { return this.api.promoteChatMember( orThrow(this.chat, "promoteChatMember").id, user_id, other, signal, ); } /** * Context-aware alias for `api.setChatAdministratorCustomTitle`. Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. * * @param custom_title New custom title for the administrator; 0-16 characters, emoji are not allowed * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatadministratorcustomtitle */ setChatAdministratorAuthorCustomTitle( custom_title: string, signal?: AbortSignal, ) { return this.api.setChatAdministratorCustomTitle( orThrow(this.chat, "setChatAdministratorAuthorCustomTitle").id, orThrow(this.from, "setChatAdministratorAuthorCustomTitle").id, custom_title, signal, ); } /** * Context-aware alias for `api.setChatAdministratorCustomTitle`. Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success. * * @param user_id Unique identifier of the target user * @param custom_title New custom title for the administrator; 0-16 characters, emoji are not allowed * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatadministratorcustomtitle */ setChatAdministratorCustomTitle( user_id: number, custom_title: string, signal?: AbortSignal, ) { return this.api.setChatAdministratorCustomTitle( orThrow(this.chat, "setChatAdministratorCustomTitle").id, user_id, custom_title, signal, ); } /** * Context-aware alias for `api.banChatSenderChat`. Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success. * * @param sender_chat_id Unique identifier of the target sender chat * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#banchatsenderchat */ banChatSenderChat(sender_chat_id: number, signal?: AbortSignal) { return this.api.banChatSenderChat( orThrow(this.chat, "banChatSenderChat").id, sender_chat_id, signal, ); } /** * Context-aware alias for `api.unbanChatSenderChat`. Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success. * * @param sender_chat_id Unique identifier of the target sender chat * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unbanchatsenderchat */ unbanChatSenderChat( sender_chat_id: number, signal?: AbortSignal, ) { return this.api.unbanChatSenderChat( orThrow(this.chat, "unbanChatSenderChat").id, sender_chat_id, signal, ); } /** * Context-aware alias for `api.setChatPermissions`. Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members administrator rights. Returns True on success. * * @param permissions New default chat permissions * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatpermissions */ setChatPermissions(permissions: ChatPermissions, signal?: AbortSignal) { return this.api.setChatPermissions( orThrow(this.chat, "setChatPermissions").id, permissions, signal, ); } /** * Context-aware alias for `api.exportChatInviteLink`. Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as String on success. * * Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using exportChatInviteLink or by calling the getChat method. If your bot needs to generate a new primary invite link replacing its previous one, use exportChatInviteLink again. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#exportchatinvitelink */ exportChatInviteLink(signal?: AbortSignal) { return this.api.exportChatInviteLink( orThrow(this.chat, "exportChatInviteLink").id, signal, ); } /** * Context-aware alias for `api.createChatInviteLink`. Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object. * * @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#createchatinvitelink */ createChatInviteLink( other?: Other<"createChatInviteLink", "chat_id">, signal?: AbortSignal, ) { return this.api.createChatInviteLink( orThrow(this.chat, "createChatInviteLink").id, other, signal, ); } /** * Context-aware alias for `api.editChatInviteLink`. Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a ChatInviteLink object. * * @param invite_link The invite link to edit * @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#editchatinvitelink */ editChatInviteLink( invite_link: string, other?: Other<"editChatInviteLink", "chat_id" | "invite_link">, signal?: AbortSignal, ) { return this.api.editChatInviteLink( orThrow(this.chat, "editChatInviteLink").id, invite_link, other, signal, ); } /** * Context-aware alias for `api.revokeChatInviteLink`. Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as ChatInviteLink object. * * @param invite_link The invite link to revoke * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#revokechatinvitelink */ revokeChatInviteLink(invite_link: string, signal?: AbortSignal) { return this.api.revokeChatInviteLink( orThrow(this.chat, "editChatInviteLink").id, invite_link, signal, ); } /** * Context-aware alias for `api.approveChatJoinRequest`. Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. * * @param user_id Unique identifier of the target user * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#approvechatjoinrequest */ approveChatJoinRequest( user_id: number, signal?: AbortSignal, ) { return this.api.approveChatJoinRequest( orThrow(this.chat, "approveChatJoinRequest").id, user_id, signal, ); } /** * Context-aware alias for `api.declineChatJoinRequest`. Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success. * * @param user_id Unique identifier of the target user * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#declinechatjoinrequest */ declineChatJoinRequest( user_id: number, signal?: AbortSignal, ) { return this.api.declineChatJoinRequest( orThrow(this.chat, "declineChatJoinRequest").id, user_id, signal, ); } /** * Context-aware alias for `api.setChatPhoto`. Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @param photo New chat photo, uploaded using multipart/form-data * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatphoto */ setChatPhoto(photo: InputFile, signal?: AbortSignal) { return this.api.setChatPhoto( orThrow(this.chat, "setChatPhoto").id, photo, signal, ); } /** * Context-aware alias for `api.deleteChatPhoto`. Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#deletechatphoto */ deleteChatPhoto(signal?: AbortSignal) { return this.api.deleteChatPhoto( orThrow(this.chat, "deleteChatPhoto").id, signal, ); } /** * Context-aware alias for `api.setChatTitle`. Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @param title New chat title, 1-255 characters * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchattitle */ setChatTitle(title: string, signal?: AbortSignal) { return this.api.setChatTitle( orThrow(this.chat, "setChatTitle").id, title, signal, ); } /** * Context-aware alias for `api.setChatDescription`. Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns True on success. * * @param description New chat description, 0-255 characters * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatdescription */ setChatDescription(description: string | undefined, signal?: AbortSignal) { return this.api.setChatDescription( orThrow(this.chat, "setChatDescription").id, description, signal, ); } /** * Context-aware alias for `api.pinChatMessage`. Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. * * @param message_id Identifier of a message to pin * @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#pinchatmessage */ pinChatMessage( message_id: number, other?: Other<"pinChatMessage", "chat_id" | "message_id">, signal?: AbortSignal, ) { return this.api.pinChatMessage( orThrow(this.chat, "pinChatMessage").id, message_id, other, signal, ); } /** * Context-aware alias for `api.unpinChatMessage`. Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. * * @param message_id Identifier of a message to unpin. If not specified, the most recent pinned message (by sending date) will be unpinned. * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unpinchatmessage */ unpinChatMessage(message_id?: number, signal?: AbortSignal) { return this.api.unpinChatMessage( orThrow(this.chat, "unpinChatMessage").id, message_id, signal, ); } /** * Context-aware alias for `api.unpinAllChatMessages`. Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unpinallchatmessages */ unpinAllChatMessages(signal?: AbortSignal) { return this.api.unpinAllChatMessages( orThrow(this.chat, "unpinAllChatMessages").id, signal, ); } /** * Context-aware alias for `api.leaveChat`. Use this method for your bot to leave a group, supergroup or channel. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#leavechat */ leaveChat(signal?: AbortSignal) { return this.api.leaveChat(orThrow(this.chat, "leaveChat").id, signal); } /** * Context-aware alias for `api.getChat`. Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getchat */ getChat(signal?: AbortSignal) { return this.api.getChat(orThrow(this.chat, "getChat").id, signal); } /** * Context-aware alias for `api.getChatAdministrators`. Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of ChatMember objects. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getchatadministrators */ getChatAdministrators(signal?: AbortSignal) { return this.api.getChatAdministrators( orThrow(this.chat, "getChatAdministrators").id, signal, ); } /** @deprecated Use `getChatMembersCount` instead. */ getChatMembersCount(...args: Parameters<Context["getChatMemberCount"]>) { return this.getChatMemberCount(...args); } /** * Context-aware alias for `api.getChatMemberCount`. Use this method to get the number of members in a chat. Returns Int on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getchatmembercount */ getChatMemberCount(signal?: AbortSignal) { return this.api.getChatMemberCount( orThrow(this.chat, "getChatMemberCount").id, signal, ); } /** * Context-aware alias for `api.getChatMember`. Use this method to get information about a member of a chat. The method is guaranteed to work only if the bot is an administrator in the chat. Returns a ChatMember object on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getchatmember */ getAuthor(signal?: AbortSignal) { return this.api.getChatMember( orThrow(this.chat, "getAuthor").id, orThrow(this.from, "getAuthor").id, signal, ); } /** * Context-aware alias for `api.getChatMember`. Use this method to get information about a member of a chat. The method is guaranteed to work only if the bot is an administrator in the chat. Returns a ChatMember object on success. * * @param user_id Unique identifier of the target user * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getchatmember */ getChatMember(user_id: number, signal?: AbortSignal) { return this.api.getChatMember( orThrow(this.chat, "getChatMember").id, user_id, signal, ); } /** * Context-aware alias for `api.setChatStickerSet`. Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success. * * @param sticker_set_name Name of the sticker set to be set as the group sticker set * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setchatstickerset */ setChatStickerSet(sticker_set_name: string, signal?: AbortSignal) { return this.api.setChatStickerSet( orThrow(this.chat, "setChatStickerSet").id, sticker_set_name, signal, ); } /** * Context-aware alias for `api.deleteChatStickerSet`. Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field can_set_sticker_set ly returned in getChat requests to check if the bot can use this method. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#deletechatstickerset */ deleteChatStickerSet(signal?: AbortSignal) { return this.api.deleteChatStickerSet( orThrow(this.chat, "deleteChatStickerSet").id, signal, ); } /** * Context-aware alias for `api.createForumTopic`. Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns information about the created topic as a ForumTopic object. * * @param name Topic name, 1-128 characters * @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#createforumtopic */ createForumTopic( name: string, other?: Other<"createForumTopic", "chat_id" | "name">, signal?: AbortSignal, ) { return this.api.createForumTopic( orThrow(this.chat, "createForumTopic").id, name, other, signal, ); } /** * Context-aware alias for `api.editForumTopic`. Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. * * @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#editforumtopic */ editForumTopic( other?: Other<"editForumTopic", "chat_id" | "message_thread_id">, signal?: AbortSignal, ) { const message = orThrow(this.msg, "editForumTopic"); const thread = orThrow(message.message_thread_id, "editForumTopic"); return this.api.editForumTopic(message.chat.id, thread, other, signal); } /** * Context-aware alias for `api.closeForumTopic`. Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#closeforumtopic */ closeForumTopic(signal?: AbortSignal) { const message = orThrow(this.msg, "closeForumTopic"); const thread = orThrow(message.message_thread_id, "closeForumTopic"); return this.api.closeForumTopic(message.chat.id, thread, signal); } /** * Context-aware alias for `api.reopenForumTopic`. Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights, unless it is the creator of the topic. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#reopenforumtopic */ reopenForumTopic(signal?: AbortSignal) { const message = orThrow(this.msg, "reopenForumTopic"); const thread = orThrow(message.message_thread_id, "reopenForumTopic"); return this.api.reopenForumTopic(message.chat.id, thread, signal); } /** * Context-aware alias for `api.deleteForumTopic`. Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#deleteforumtopic */ deleteForumTopic(signal?: AbortSignal) { const message = orThrow(this.msg, "deleteForumTopic"); const thread = orThrow(message.message_thread_id, "deleteForumTopic"); return this.api.deleteForumTopic(message.chat.id, thread, signal); } /** * Context-aware alias for `api.unpinAllForumTopicMessages`. Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unpinallforumtopicmessages */ unpinAllForumTopicMessages(signal?: AbortSignal) { const message = orThrow(this.msg, "unpinAllForumTopicMessages"); const thread = orThrow( message.message_thread_id, "unpinAllForumTopicMessages", ); return this.api.unpinAllForumTopicMessages( message.chat.id, thread, signal, ); } /** * Context-aware alias for `api.editGeneralForumTopic`. Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have can_manage_topics administrator rights. Returns True on success. * * @param name New topic name, 1-128 characters * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#editgeneralforumtopic */ editGeneralForumTopic(name: string, signal?: AbortSignal) { return this.api.editGeneralForumTopic( orThrow(this.chat, "editGeneralForumTopic").id, name, signal, ); } /** * Context-aware alias for `api.closeGeneralForumTopic`. Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#closegeneralforumtopic */ closeGeneralForumTopic(signal?: AbortSignal) { return this.api.closeGeneralForumTopic( orThrow(this.chat, "closeGeneralForumTopic").id, signal, ); } /** * Context-aware alias for `api.reopenGeneralForumTopic`. Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically unhidden if it was hidden. Returns True on success. * * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#reopengeneralforumtopic */ reopenGeneralForumTopic(signal?: AbortSignal) { return this.api.reopenGeneralForumTopic( orThrow(this.chat, "reopenGeneralForumTopic").id, signal, ); } /** * Context-aware alias for `api.hideGeneralForumTopic`. Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. The topic will be automatically closed if it was open. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#hidegeneralforumtopic */ hideGeneralForumTopic(signal?: AbortSignal) { return this.api.hideGeneralForumTopic( orThrow(this.chat, "hideGeneralForumTopic").id, signal, ); } /** * Context-aware alias for `api.unhideGeneralForumTopic`. Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unhidegeneralforumtopic */ unhideGeneralForumTopic(signal?: AbortSignal) { return this.api.unhideGeneralForumTopic( orThrow(this.chat, "unhideGeneralForumTopic").id, signal, ); } /** * Context-aware alias for `api.unpinAllGeneralForumTopicMessages`. Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the can_pin_messages administrator right in the supergroup. Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages */ unpinAllGeneralForumTopicMessages(signal?: AbortSignal) { return this.api.unpinAllGeneralForumTopicMessages( orThrow(this.chat, "unpinAllGeneralForumTopicMessages").id, signal, ); } /** * Context-aware alias for `api.answerCallbackQuery`. Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned. * * Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via @BotFather and accept the terms. Otherwise, you may use links like t.me/your_bot?start=XXXX that open your bot with a parameter. * * @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#answercallbackquery */ answerCallbackQuery( other?: string | Other<"answerCallbackQuery", "callback_query_id">, signal?: AbortSignal, ) { return this.api.answerCallbackQuery( orThrow(this.callbackQuery, "answerCallbackQuery").id, typeof other === "string" ? { text: other } : other, signal, ); } /** * Context-aware alias for `api.setChatMenuButton`. Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success. * * @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#setchatmenubutton */ setChatMenuButton( other?: Other<"setChatMenuButton">, signal?: AbortSignal, ) { return this.api.setChatMenuButton(other, signal); } /** * Context-aware alias for `api.getChatMenuButton`. Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success. * * @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#setchatmenubutton */ getChatMenuButton( other?: Other<"getChatMenuButton">, signal?: AbortSignal, ) { return this.api.getChatMenuButton(other, signal); } /** * Context-aware alias for `api.setMyDefaultAdministratorRights`. Use this method to the change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success. * * @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#setmydefaultadministratorrights */ setMyDefaultAdministratorRights( other?: Other<"setMyDefaultAdministratorRights">, signal?: AbortSignal, ) { return this.api.setMyDefaultAdministratorRights(other, signal); } /** * Context-aware alias for `api.getMyDefaultAdministratorRights`. Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success. * * @param other Optional remaining parameters, confer the official reference below * @param signal Optional `AbortSignal` to cancel the request */ getMyDefaultAdministratorRights( other?: Other<"getMyDefaultAdministratorRights">, signal?: AbortSignal, ) { return this.api.getMyDefaultAdministratorRights(other, signal); } /** * Context-aware alias for `api.editMessageText`. Use this method to edit text and game messages. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. * * @param text New text of the message, 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#editmessagetext */ editMessageText( text: string, other?: Other< "editMessageText", "chat_id" | "message_id" | "inline_message_id" | "text" >, signal?: AbortSignal, ) { const inlineId = this.inlineMessageId; return inlineId !== undefined ? this.api.editMessageTextInline(inlineId, text, other) : this.api.editMessageText( orThrow(this.chat, "editMessageText").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageText", ), text, other, signal, ); } /** * Context-aware alias for `api.editMessageCaption`. Use this method to edit captions of messages. On success, if the edited 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#editmessagecaption */ editMessageCaption( other?: Other< "editMessageCaption", "chat_id" | "message_id" | "inline_message_id" >, signal?: AbortSignal, ) { const inlineId = this.inlineMessageId; return inlineId !== undefined ? this.api.editMessageCaptionInline(inlineId, other) : this.api.editMessageCaption( orThrow(this.chat, "editMessageCaption").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageCaption", ), other, signal, ); } /** * Context-aware alias for `api.editMessageMedia`. Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited Message is returned, otherwise True is returned. * * @param media An object for a new media content of the message * @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#editmessagemedia */ editMessageMedia( media: InputMedia, other?: Other< "editMessageMedia", "chat_id" | "message_id" | "inline_message_id" | "media" >, signal?: AbortSignal, ) { const inlineId = this.inlineMessageId; return inlineId !== undefined ? this.api.editMessageMediaInline(inlineId, media, other) : this.api.editMessageMedia( orThrow(this.chat, "editMessageMedia").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageMedia", ), media, other, signal, ); } /** * Context-aware alias for `api.editMessageReplyMarkup`. Use this method to edit only the reply markup of messages. On success, if the edited 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#editmessagereplymarkup */ editMessageReplyMarkup( other?: Other< "editMessageReplyMarkup", "chat_id" | "message_id" | "inline_message_id" >, signal?: AbortSignal, ) { const inlineId = this.inlineMessageId; return inlineId !== undefined ? this.api.editMessageReplyMarkupInline(inlineId, other) : this.api.editMessageReplyMarkup( orThrow(this.chat, "editMessageReplyMarkup").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "editMessageReplyMarkup", ), other, signal, ); } /** * Context-aware alias for `api.stopPoll`. Use this method to stop a poll which was sent by the bot. On success, the stopped Poll 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#stoppoll */ stopPoll( other?: Other<"stopPoll", "chat_id" | "message_id">, signal?: AbortSignal, ) { return this.api.stopPoll( orThrow(this.chat, "stopPoll").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "stopPoll", ), other, signal, ); } /** * Context-aware alias for `api.deleteMessage`. Use this method to delete a message, including service messages, with the following limitations: * - A message can only be deleted if it was sent less than 48 hours ago. * - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. * - Bots can delete outgoing messages in private chats, groups, and supergroups. * - Bots can delete incoming messages in private chats. * - Bots granted can_post_messages permissions can delete outgoing messages in channels. * - If the bot is an administrator of a group, it can delete any message there. * - If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. * Returns True on success. * * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#deletemessage */ deleteMessage(signal?: AbortSignal) { return this.api.deleteMessage( orThrow(this.chat, "deleteMessage").id, orThrow( this.msg?.message_id ?? this.messageReaction?.message_id ?? this.messageReactionCount?.message_id, "deleteMessage", ), signal, ); } /** * Context-aware alias for `api.deleteMessages`. Use this method to delete multiple messages simultaneously. Returns True on success. * * @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 to delete. See deleteMessage for limitations on which messages can be deleted * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#deletemessages */ deleteMessages(message_ids: number[], signal?: AbortSignal) { return this.api.deleteMessages( orThrow(this.chat, "deleteMessages").id, message_ids, signal, ); } /** * Context-aware alias for `api.sendSticker`. Use this method to send static .WEBP, animated .TGS, or video .WEBM stickers. On success, the sent Message is returned. * * @param sticker Sticker 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 .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. Video and animated stickers can't be sent via an HTTP URL. * @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#sendsticker */ replyWithSticker( sticker: InputFile | string, other?: Other<"sendSticker", "chat_id" | "sticker">, signal?: AbortSignal, ) { return this.api.sendSticker( orThrow(this.chat, "sendSticker").id, sticker, { business_connection_id: this.businessConnectionId, ...other }, signal, ); } /** * Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects. * * @param custom_emoji_ids A list of custom emoji identifiers * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#getcustomemojistickers */ getCustomEmojiStickers(signal?: AbortSignal) { type Emoji = MessageEntity.CustomEmojiMessageEntity; return this.api.getCustomEmojiStickers( (this.msg?.entities ?? []) .filter((e): e is Emoji => e.type === "custom_emoji") .map((e) => e.custom_emoji_id), signal, ); } /** * Context-aware alias for `api.answerInlineQuery`. Use this method to send answers to an inline query. On success, True is returned. * No more than 50 results per query are allowed. * * Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a 'Connect your YouTube account' button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an OAuth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot's inline capabilities. * * @param results An array of results for the inline query * @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#answerinlinequery */ answerInlineQuery( results: readonly InlineQueryResult[], other?: Other<"answerInlineQuery", "inline_query_id" | "results">, signal?: AbortSignal, ) { return this.api.answerInlineQuery( orThrow(this.inlineQuery, "answerInlineQuery").id, results, other, signal, ); } /** * Context-aware alias for `api.sendInvoice`. Use this method to send invoices. On success, the sent Message is returned. * * @param title Product name, 1-32 characters * @param description Product description, 1-255 characters * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. * @param provider_token Payment provider token, obtained via @BotFather * @param currency Three-letter ISO 4217 currency code, see more on currencies * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) * @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#sendinvoice */ replyWithInvoice( title: string, description: string, payload: string, provider_token: string, currency: string, prices: readonly LabeledPrice[], other?: Other< "sendInvoice", | "chat_id" | "title" | "description" | "payload" | "provider_token" | "currency" | "prices" >, signal?: AbortSignal, ) { return this.api.sendInvoice( orThrow(this.chat, "sendInvoice").id, title, description, payload, provider_token, currency, prices, other, signal, ); } /** * Context-aware alias for `api.answerShippingQuery`. If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. * * @param shipping_query_id Unique identifier for the query to be answered * @param ok Pass True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) * @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#answershippingquery */ answerShippingQuery( ok: boolean, other?: Other<"answerShippingQuery", "shipping_query_id" | "ok">, signal?: AbortSignal, ) { return this.api.answerShippingQuery( orThrow(this.shippingQuery, "answerShippingQuery").id, ok, other, signal, ); } /** * Context-aware alias for `api.answerPreCheckoutQuery`. Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True is returned. Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. * * @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. * @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#answerprecheckoutquery */ answerPreCheckoutQuery( ok: boolean, other?: | string | Other<"answerPreCheckoutQuery", "pre_checkout_query_id" | "ok">, signal?: AbortSignal, ) { return this.api.answerPreCheckoutQuery( orThrow(this.preCheckoutQuery, "answerPreCheckoutQuery").id, ok, typeof other === "string" ? { error_message: other } : other, signal, ); } /** * Context-aware alias for `api.setPassportDataErrors`. Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. * * Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. * * @param errors An array describing the errors * @param signal Optional `AbortSignal` to cancel the request * * **Official reference:** https://core.telegram.org/bots/api#setpassportdataerrors */ setPassportDataErrors( errors: readonly PassportElementError[], signal?: AbortSignal, ) { return this.api.setPassportDataErrors( orThrow(this.from, "setPassportDataErrors").id, errors, signal, ); } /** * Context-aware alias for `api.sendGame`. Use this method to send a game. On success, the sent Message is returned. * * @param game_short_name Short name of the game, serves as the unique identifier for the game. Set up your games via BotFather. * @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#sendgame */ replyWithGame( game_short_name: string, other?: Other<"sendGame", "chat_id" | "game_short_name">, signal?: AbortSignal, ) { return this.api.sendGame( orThrow(this.chat, "sendGame").id, game_short_name, { business_connection_id: this.businessConnectionId, ...other }, signal, ); }}
// === Filtered context typestype HearsContextCore = & FilterCore<":text" | ":caption"> & NarrowMatchCore<string | RegExpMatchArray>;/** * Type of the context object that is available inside the handlers for * `bot.hears`. * * This helper type can be used to narrow down context objects the same way how * `bot.hears` does it. This allows you to annotate context objects in * middleware that is not directly passed to `bot.hears`, hence not inferring * the correct type automatically. That way, handlers can be defined in separate * files and still have the correct types. */export type HearsContext<C extends Context> = Filter< NarrowMatch<C, string | RegExpMatchArray>, ":text" | ":caption">;type CommandContextCore = & FilterCore<":entities:bot_command"> & NarrowMatchCore<string>;/** * Type of the context object that is available inside the handlers for * `bot.command`. * * This helper type can be used to narrow down context objects the same way how * `bot.command` does it. This allows you to annotate context objects in * middleware that is not directly passed to `bot.command`, hence not inferring * the correct type automatically. That way, handlers can be defined in separate * files and still have the correct types. */export type CommandContext<C extends Context> = Filter< NarrowMatch<C, string>, ":entities:bot_command">;type NarrowMatchCore<T extends Context["match"]> = { match: T };type NarrowMatch<C extends Context, T extends C["match"]> = { [K in keyof C]: K extends "match" ? (T extends C[K] ? T : never) : C[K];};
type CallbackQueryContextCore = FilterCore<"callback_query:data">;/** * Type of the context object that is available inside the handlers for * `bot.callbackQuery`. * * This helper type can be used to annotate narrow down context objects the same * way `bot.callbackQuery` does it. This allows you to how context objects in * middleware that is not directly passed to `bot.callbackQuery`, hence not * inferring the correct type automatically. That way, handlers can be defined * in separate files and still have the correct types. */export type CallbackQueryContext<C extends Context> = Filter< NarrowMatch<C, string | RegExpMatchArray>, "callback_query:data">;type GameQueryContextCore = FilterCore<"callback_query:game_short_name">;/** * Type of the context object that is available inside the handlers for * `bot.gameQuery`. * * This helper type can be used to narrow down context objects the same way how * `bot.gameQuery` does it. This allows you to annotate context objects in * middleware that is not directly passed to `bot.gameQuery`, hence not * inferring the correct type automatically. That way, handlers can be defined * in separate files and still have the correct types. */export type GameQueryContext<C extends Context> = Filter< C, "callback_query:game_short_name">;type InlineQueryContextCore = FilterCore<"inline_query">;/** * Type of the context object that is available inside the handlers for * `bot.inlineQuery`. * * This helper type can be used to narrow down context objects the same way how * annotate `bot.inlineQuery` does it. This allows you to context objects in * middleware that is not directly passed to `bot.inlineQuery`, hence not * inferring the correct type automatically. That way, handlers can be defined * in separate files and still have the correct types. */export type InlineQueryContext<C extends Context> = Filter<C, "inline_query">;
type ReactionContextCore = FilterCore<"message_reaction">;/** * Type of the context object that is available inside the handlers for * `bot.reaction`. * * This helper type can be used to narrow down context objects the same way how * annotate `bot.reaction` does it. This allows you to context objects in * middleware that is not directly passed to `bot.reaction`, hence not inferring * the correct type automatically. That way, handlers can be defined in separate * files and still have the correct types. */export type ReactionContext<C extends Context> = Filter<C, "message_reaction">;
type ChosenInlineResultContextCore = FilterCore<"chosen_inline_result">;/** * Type of the context object that is available inside the handlers for * `bot.chosenInlineResult`. * * This helper type can be used to narrow down context objects the same way how * annotate `bot.chosenInlineResult` does it. This allows you to context objects in * middleware that is not directly passed to `bot.chosenInlineResult`, hence not * inferring the correct type automatically. That way, handlers can be defined * in separate files and still have the correct types. */export type ChosenInlineResultContext<C extends Context> = Filter< C, "chosen_inline_result">;type ChatTypeContextCore<T extends Chat["type"]> = & Record<"update", ChatTypeUpdate<T>> // ctx.update & ChatType<T> // ctx.chat & ChatFrom<T> // ctx.from & ChatTypeRecord<"msg", T> // ctx.msg & AliasProps<ChatTypeUpdate<T>>; // ctx.message etc/** * Type of the context object that is available inside the handlers for * `bot.chatType`. * * This helper type can be used to narrow down context objects the same way how * `bot.chatType` does it. This allows you to annotate context objects in * middleware that is not directly passed to `bot.chatType`, hence not inferring * the correct type automatically. That way, handlers can be defined in separate * files and still have the correct types. */export type ChatTypeContext<C extends Context, T extends Chat["type"]> = & C & ChatTypeContextCore<T>;type ChatTypeUpdate<T extends Chat["type"]> = & ChatTypeRecord< | "message" | "edited_message" | "channel_post" | "edited_channel_post" | "my_chat_member" | "chat_member" | "chat_join_request", T > & Partial<Record<"callback_query", ChatTypeRecord<"message", T>>> & ConstrainUpdatesByChatType<T>;type ConstrainUpdatesByChatType<T extends Chat["type"]> = Record< [T] extends ["channel"] ? "message" | "edited_message" : "channel_post" | "edited_channel_post", undefined>;type ChatTypeRecord<K extends string, T extends Chat["type"]> = Partial< Record<K, ChatType<T>>>;interface ChatType<T extends Chat["type"]> { chat: { type: T };}interface ChatFrom<T extends Chat["type"]> { // deno-lint-ignore ban-types from: [T] extends ["private"] ? {} : unknown;}
// === Util functionsfunction orThrow<T>(value: T | undefined, method: string): T { if (value === undefined) { throw new Error(`Missing information for API call to ${method}`); } return value;}
function triggerFn(trigger: MaybeArray<string | RegExp>) { return toArray(trigger).map((t) => typeof t === "string" ? (txt: string) => (txt === t ? t : null) : (txt: string) => txt.match(t) );}
function match<C extends Context>( ctx: C, content: string, triggers: Array<(content: string) => string | RegExpMatchArray | null>,): boolean { for (const t of triggers) { const res = t(content); if (res) { ctx.match = res; return true; } } return false;}function toArray<E>(e: MaybeArray<E>): E[] { return Array.isArray(e) ? e : [e];}
grammy

Version Info

Tagged at
a month ago