Repository navigation
Expand file tree
/
Copy pathbase.js
More file actions
executable file
·1595 lines (1364 loc) · 63 KB
/
Copy pathbase.js
File metadata and controls
executable file
·1595 lines (1364 loc) · 63 KB
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
import { CallbackQuery, Chat, LinkPreviewOptions, Message, WebhookInfo, _File, User, ChatMember, ChatMemberAdministrator, ChatMemberBanned, ChatMemberMember, ChatMemberLeft, ChatMemberRestricted, ChatMemberOwner, InputFile, ChatMemberUpdated, Document, ChatFullInfo, ChatPermissions, MessageId, UserProfilePhotos, ChatInviteLink, ChatJoinRequest, MessageEntity, ForumTopic, Sticker } from "./components.js";
import { BaseHandler, CallbackQueryHandler, ChatMemberHandler, CommandHandler, ConversationHandler, MessageHandler } from "./handlers.js";
import fs from "fs";
import { FormData } from "node-fetch";
import fetch from "node-fetch";
import express from "express";
import {ChatScope, Permissions, UpdateType} from "./constants.js";
import { Queue, Schedule } from "./extra.js";
import path from "path";
import { fileURLToPath } from 'url';
import cors from "cors";
import { fetchWithTimeout } from "./utils.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
/**
* Represents the context of the bot instance.
*/
class Context {
/**
* The shared bot instance.
* @type {Bot|null}
*/
static bot = null;
/**
* Context arguments array.
* @type {Array<string>}
*/
static args = [];
/**
* Bot specific data tied to the bot context.
*/
static botData = new Map();
/**
*
* @param {Update} update
* @param {Bot} bot
*/
constructor(update, bot) {
/**
* An update.
*/
this.update = update;
/**
* The bot instance in this context.
*/
this.bot = bot;
/**
* User specific data tied to the bot context.
*/
this.userData = new Map();
/**
* Chat specific data tied to the bot context.
*/
this.chatData = new Map();
/**Array of words after a command. Quotation marks can be used to wrap multiple words together.
* @type {string[]}
* */
this.args = [];
}
/**
* Get information about a file.
* @param {Document} document
* @returns {Promise<_File>|null}
*/
async getFile(document) {
if (document.file_size > 20 * 1024) {
console.error("File size is too big.");
return;
}
const response = await fetchWithTimeout(this.bot.endpoint + "getFile", {
method: "POST",
body: JSON.stringify({
file_id: document.file_id
})
}, 30000);
return await response.json();
}
/**
* Schedule a task to run repeatedly.
* @param {{interval: number, callback: (update: Update, context: Context) => Promise<void>}} config
* @returns {Schedule} Schedule ID.
*/
schedule(config) {
const schedule = setInterval(async () => {
try {
await config.callback(this.update, this);
} catch (error) {
console.error(
`Scheduled task ${schedule} failed:`,
error
);
}
}, config.interval);
console.log(`Scheduled task ${schedule} started.`);
return new Schedule(schedule);
}
}
/**
* Represents the update object.
*/
class Update {
// /**@type {ChatMember} */
// #chat_member = null;
constructor(update) {
this.update = update;
}
/**
* Get the update type.
* @returns {'message'|'edited_message'|'channel_post'|'edited_channel_post'|'business_connection'|'business_message'|'edited_business_message'|'deleted_business_message'|'message_reaction'|'message_reaction_count'|'inline_query'|'chosen_inline_result'|'callback_query'|'shipping_query'|'pre_checkout_query'|'purchased_paid_media'|'poll'|'my_chat_member'|'chat_member'|'chat_join_request'|'chat_boost'|'removed_chat_boost'}
*/
get type() {
const types = UpdateType.ALL;
for (const type of types) {
if (this.update.hasOwnProperty(type)) {
return type;
}
}
return "Unknown Update Type";
}
/**
* @returns {number} The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using webhooks, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.
*/
get update_id() { return this.update.update_id; }
/**
* @returns {Message} New incoming message of any kind - text, photo, sticker, etc..
*/
get message() { return this.update.hasOwnProperty("message") ? new Message(this.update.message) : null; }
/**
* @returns {Message} New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
*/
get edited_message() { return this.update.hasOwnProperty("edited_message") ? new Message(this.update.edited_message) : null; }
/**
* @returns {Message} New incoming channel post of any kind - text, photo, sticker, etc..
*/
get channel_post() { return this.update.hasOwnProperty("channel_post") ? new Message(this.update.channel_post) : null; }
/**
* @returns {Message} New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.
*/
get edited_channel_post() { return this.update.hasOwnProperty("edited_channel_post") ? new Message(this.update.edited_channel_post) : null; }
/**
* @returns {CallbackQuery} New incoming callback query.
*/
get callback_query() { return this.update.hasOwnProperty("callback_query") ? new CallbackQuery(this.update.callback_query) : null; }
/**
* @returns {Chat|null} The effective chat the update comes from.
*/
get effective_chat() {
// Regular message
if (this.update?.message) {
return new Message(this.update.message).chat;
}
// Edited message
if (this.update?.edited_message) {
return new Message(this.update.edited_message).chat;
}
// Callback query
if (this.update?.callback_query?.message) {
return new Message(this.update.callback_query.message).chat;
}
// Channel post
if (this.update?.channel_post) {
return new Message(this.update.channel_post).chat;
}
// Edited channel post
if (this.update?.edited_channel_post) {
return new Message(this.update.edited_channel_post).chat;
}
// Chat member updates
if (this.update?.chat_member?.chat) {
return new Chat(this.update.chat_member.chat);
}
// Bot membership updates
if (this.update?.my_chat_member?.chat) {
return new Chat(this.update.my_chat_member.chat);
}
// Chat join requests
if (this.update?.chat_join_request?.chat) {
return new Chat(this.update.chat_join_request.chat);
}
// Business messages
if (this.update?.business_message) {
return new Message(this.update.business_message).chat;
}
// Edited business messages
if (this.update?.edited_business_message) {
return new Message(this.update.edited_business_message).chat;
}
// Deleted business messages
if (this.update?.deleted_business_messages?.chat) {
return new Chat(this.update.deleted_business_messages.chat);
}
return null;
}
/**
* @returns {User|null} The effective user the update comes from.
*/
get effective_user() {
// Message
if (this.update?.message?.from) {
return new User(this.update.message.from);
}
// Edited message
if (this.update?.edited_message?.from) {
return new User(this.update.edited_message.from);
}
// Callback query
if (this.update?.callback_query?.from) {
return new User(this.update.callback_query.from);
}
// Inline query
if (this.update?.inline_query?.from) {
return new User(this.update.inline_query.from);
}
// Chosen inline result
if (this.update?.chosen_inline_result?.from) {
return new User(this.update.chosen_inline_result.from);
}
// Chat member update actor
if (this.update?.chat_member?.from) {
return new User(this.update.chat_member.from);
}
// Bot membership update actor
if (this.update?.my_chat_member?.from) {
return new User(this.update.my_chat_member.from);
}
// Join request
if (this.update?.chat_join_request?.from) {
return new User(this.update.chat_join_request.from);
}
// Channel post author
if (this.update?.channel_post?.from) {
return new User(this.update.channel_post.from);
}
// Edited channel post author
if (this.update?.edited_channel_post?.from) {
return new User(this.update.edited_channel_post.from);
}
// Business message
if (this.update?.business_message?.from) {
return new User(this.update.business_message.from);
}
// Edited business message
if (this.update?.edited_business_message?.from) {
return new User(this.update.edited_business_message.from);
}
return null;
}
/**
* @returns {Message|null} The effective message associated with the update.
*/
get effective_message() {
// Regular message
if (this.update?.message) {
return new Message(this.update.message);
}
// Edited message
if (this.update?.edited_message) {
return new Message(this.update.edited_message);
}
// Callback query message
if (this.update?.callback_query?.message) {
return new Message(this.update.callback_query.message);
}
// Channel post
if (this.update?.channel_post) {
return new Message(this.update.channel_post);
}
// Edited channel post
if (this.update?.edited_channel_post) {
return new Message(this.update.edited_channel_post);
}
// Business message
if (this.update?.business_message) {
return new Message(this.update.business_message);
}
// Edited business message
if (this.update?.edited_business_message) {
return new Message(this.update.edited_business_message);
}
return null;
}
/**
* Optional. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify "chat_member" in the list of allowed_updates to receive these updates.
* @returns {ChatMemberUpdated}
*/
get chat_member() { return this.update?.chat_member ? new ChatMemberUpdated(this.update.chat_member) : null }
// set chat_member(value){
// this.#chat_member = value;
// }
/**
* Optional. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.
* @returns {ChatMemberUpdated}
*/
get my_chat_member() { return this.update?.my_chat_member ? new ChatMemberUpdated(this.update.my_chat_member) : null }
/**
* Optional. A request to join the chat has been sent. The bot must have the can_invite_users administrator right in the chat to receive these updates.
* @returns {ChatJoinRequest}
*/
get chat_join_request() { return this.update?.chat_join_request ? new ChatJoinRequest(this.update.chat_join_request) : null }
toJSON() {
return { ...this };
}
}
/**
* Represents the bot builder.
*/
class App {
static defaultParams = {};
#queue = new Queue();
/**
* @type {Update[]}
*/
static updateHistory = [];
/**
* Store a number of past updates.
* @param {Update} item
*/
static cache(item) {
App.updateHistory.push(item);
if (App.updateHistory.length > 40) {
App.updateHistory.shift();
}
}
constructor() {
this.api_key = null;
this.update = null;
this.context = null;
this.last_update_id = null;
this.bot = null;
// this.handlers = {
// global: [],
// conversation: null
// };
this.handlers = {
command: [],
message: [],
callback_query: [],
chat_member: [],
conversation: null
};
this.server = null;
this.express = null;
this.base_url = null;
this.ngrokTunnel = null;
this.test_mode = false;
this.update_offset = 0;
this.lastProcessedTime = 0;
this.timeout = null;
}
/**
* Configure the app.
* @param {{test: boolean}} options
*/
config(options) {
this.test_mode = options.test;
return this;
}
/**
*
* @param {{method: string, params: object|FormData, type: string}} config
* @returns
*/
static HTTP(config) {
if (config.params instanceof FormData) {
return {
method: "POST",
body: config.params,
};
} else {
let type = "application/json; charset=UTF-8";
return {
method: "POST",
headers: new Headers({
"Content-Type": config.type || type,
}),
body: JSON.stringify({
method: config.method,
...config.params,
...App.defaultParams
}),
};
}
}
/**
* Define a custom webhook endpoint response. You can integrate this with `Context`.
* @param {"POST"|"GET"} method
* @param {string} path
* @param {(req: import("express").Request, res: import("express").Response) => Promise<void>} callback
*/
addEndPoint(method = "GET", path = "/", callback) {
if (!this.express) {
console.error("Express server is uninitialised.");
return;
}
if (method === "GET") {
return this.express.get(path, callback);
}
return this.express.post(path, callback);
}
/**
* Set default values.
* @param {{parse_mode:string, link_preview_options: LinkPreviewOptions, disable_notification: boolean, protect_content: boolean}} config
* @returns
*/
defaults(config) {
App.defaultParams = config;
return this;
}
/**
* Set up a local telegram endpoint.
* @param {string} url
* @returns
*/
baseUrl(url) {
this.base_url = url;
return this;
}
/**
* API token.
* @param {string} api_key
* @returns
*/
token(api_key) {
this.api_key = api_key;
return this;
}
/**
* Initialize the app and create a bot instance in the current context.
* @returns {App}
*/
build() {
if (!this.api_key) throw new Error("API KEY needs to be passed first.");
this.bot = new Bot(this.api_key, this.test_mode);
if (this.base_url) {
this.bot.endpoint = `${this.base_url}${this.api_key}/${this.test_mode ? "test/" : ""}`;
}
Context.bot = this.bot;
return this;
}
/**
* Add an update handler.
* @param {BaseHandler} handler
* @param {Permissions} permissions
* @param {number} scope
*/
addHandler(handler, permissions = Permissions.MEMBER, scope = ChatScope.ALL) {
handler.requiredPermissions = permissions;
handler.scope = scope;
if (handler instanceof ConversationHandler && !this.handlers.conversation) {
this.handlers.conversation = handler;
return this;
}
// this.handlers.global.push(handler);
if (handler instanceof CommandHandler) {
this.handlers.command.push(handler);
}
else if (handler instanceof MessageHandler) {
this.handlers.message.push(handler);
}
else if (handler instanceof CallbackQueryHandler) {
this.handlers.callback_query.push(handler);
}
else if (handler instanceof ChatMemberHandler) {
this.handlers.chat_member.push(handler);
}
else {
throw new Error("Unknown handler type.");
}
return this;
}
getUpdateScope(update) {
const type = update.effective_chat?.type;
switch (type) {
case "private":
return ChatScope.PRIVATE;
case "group":
return ChatScope.GROUP;
case "supergroup":
return ChatScope.SUPERGROUP;
case "channel":
return ChatScope.CHANNEL;
default:
return 0;
}
}
async dispatchHandlers(handlers, update, context, stopOnHandled = true) {
const currentScope = this.getUpdateScope(update);
for (const handler of handlers) {
try {
if ((handler.scope & currentScope) === 0) {
continue;
}
const allowed = await this.checkPermissions(
update,
context,
handler.requiredPermissions
);
if (!allowed) {
continue;
}
const handled = await handler.handle(update, context);
if (handled && stopOnHandled) {
return true;
}
} catch (error) {
console.error("Handler error:", error);
}
}
return false;
}
/**
* Set up a webhook.
* @param {string} url
* @param {{url:string, drop_pending_updates: boolean, max_connections: number, certificate: InputFile, ip_address: string, secret_token: string, allowed_updates: string[]}} config
* @returns
*/
async setWebhook(config) {
let params = App.HTTP({ method: "setWebhook", params: { ...config } });
const response = await fetchWithTimeout(this.bot.endpoint, params, 20000);
const data = await response.json();
if (response.ok && data.url != '') {
return true;
}
throw new Error("Failed to set the webhook:", data);
}
/**
* Delete the webhook.
* @returns {Promise<boolean>|Promise<Error>}
*/
async deleteWebhook() {
let config = App.HTTP({ method: "deleteWebhook", params: {} });
const response = await fetchWithTimeout(this.bot.endpoint, config, 20000);
if (response.ok) {
return true;
}
throw new Error("Failed to delete the webhook.");
}
/**
* Retrieve information about the webhook.
* @returns {Promise<boolean>|Promise<WebhookInfo>}
*/
async getWebhookInfo() {
let config = App.HTTP({ method: "getWebhookInfo", params: {} });
const response = await fetchWithTimeout(this.bot.endpoint, config, 20000);
const data = await response.json();
if (response.ok) {
return new WebhookInfo(data.result);
} else {
console.warn("No webhook information:", data);
return false;
}
}
/**
* This is a convenience function. It applies a rate limit for processing updates. This is in order to avoid being timed out by your webhook provider (assuming you don't have a good plan).
*/
async _applyRateLimit() {
const now = Date.now();
// If the time between updates is too short, introduce a delay
const delay = Math.max(0, this.lastProcessedTime + 100 - now); // Delay for 1 second between updates
if (delay > 0) {
// console.log(`Rate limit exceeded, waiting for ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
}
// Update the last processed time to the current time
this.lastProcessedTime = Date.now();
}
/**
* Check if a user has enough privileges.
* @param {Update} update
* @param {Context} context
* @param {number} requiredPermissions
* @returns {Promise<boolean>}
*/
async checkPermissions(update, context, requiredPermissions) {
const userId = update.effective_user?.id;
const chatId = update.effective_chat?.id;
if (requiredPermissions === Permissions.ALL) {
return true;
}
if (update.effective_chat?.type === "channel" || update.effective_chat?.type === "private") {
if (typeof requiredPermissions === "number" && userId === requiredPermissions) {
return true
} else if (typeof requiredPermissions === "string") {
return true;
}
return false;
}
const hasPerms = (userPerms, requiredPerms) => (userPerms & requiredPerms) !== 0;
let userPermissions = Permissions.NONE;
const member = await context.bot.getChatMember({chat_id: chatId, user_id: userId});
switch (member?.status) {
case "creator":
userPermissions = Permissions.OWNER;
break;
case "administrator":
userPermissions = Permissions.ADMIN;
break;
case "member":
userPermissions = Permissions.MEMBER;
break;
case "restricted":
userPermissions = Permissions.RESTRICTED;
break;
default:
userPermissions = Permissions.NONE;
}
return hasPerms(userPermissions, requiredPermissions);
}
/**
* Retrieves the update object and passes it to the handlers.
* @param {Update} update
* @returns
*/
async getUpdates(update) {
this.update = update;
if (update.update_id === this.last_update_id) {
return;
}
this.last_update_id = update.update_id;
if (!this.bot) {
throw new Error("The bot instance does not exist.");
}
const context = new Context(update, this.bot);
this.#queue.addTask(async () => {
await this._applyRateLimit();
// Conversation handlers first
if (this.handlers.conversation) {
const handled =
await this.handlers.conversation.handle(
update,
context
);
if (this.handlers.conversation.isEnded) {
this.handlers.conversation.reset();
}
if (handled) {
return;
}
}
let handlers = [];
switch (update.type) {
case "channel_post":
case "message": {
const text = update.effective_message?.text;
await this.dispatchHandlers(
this.handlers.message,
update,
context,
false
);
if (
typeof text === "string" &&
text.startsWith("/")
) {
await this.dispatchHandlers(
this.handlers.command,
update,
context,
true
);
}
return;
}
case "callback_query":
handlers = this.handlers.callback_query;
break;
case "chat_member":
case "my_chat_member":
handlers = this.handlers.chat_member;
break;
}
await this.dispatchHandlers(
handlers,
update,
context
);
});
this.#queue.processQueue();
// if (!this.#queue.running) {
// await this.#queue.processQueue();
// }
}
/**
* Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.
* @param {{offset: number, limit: number, timeout: number, allowed_updates: string[]}} config
* @param {boolean} debug
*/
async run_polling(config, debug) {
if (this.timeout) clearTimeout(this.timeout)
try {
const params = App.HTTP({
method: "getUpdates", params: {
offset: this.update_offset,
...config
}
});
const response = await fetchWithTimeout(this.bot.endpoint, params, 20000);
if (!response.ok) {
throw new Error(`Unable to fetch updates (${response.status}): ${await response.text()}`);
}
const updates = await response.json();
if (updates.ok && updates.result.length) {
if (debug) console.log(`[${new Date().toISOString()}] Update ${updates.result.at(-1).update_id}:\n${JSON.stringify(updates.result.at(-1))}`);
for (const data of updates.result) {
const update = new Update(data);
await this.getUpdates(update);
// if (update.update_id > this.update_offset){
// }
}
this.update_offset = this.last_update_id + 1;
}
this.timeout = setTimeout(() => this.run_polling(config), 1000);
} catch (error) {
console.error("Error fetching updates:", error);
this.timeout = setTimeout(() => this.run_polling(config), 1000);
}
}
/**
* Starts up the webhook for the bot. If you don't have `.env` file set up, you will need to define these values manually.
* @param {{url: string, allowed_updates:string[], webhookPath: string, port: number, serverTimeout: number, secretToken: string, debug: boolean}} config
*/
async run(config = {}) {
if (this.server) {
console.warn("Server already running.");
return;
}
const app = express();
this.express = app;
const PORT = config.port || 3000;
app.use(express.json());
app.use(cors());
app.post(config.webhookPath || "/", async (req, res) => {
if (config?.debug) {
console.log("DEBUG:", JSON.stringify(req.body, null, 2));
}
const incomingToken = req.headers["x-telegram-bot-api-secret-token"];
if ((process.env.SECRET_TOKEN || config.secretToken) && ![process.env.SECRET_TOKEN, config.secretToken].includes(incomingToken)) {
console.warn('Invalid secret token:', incomingToken);
return res.status(403).send('Forbidden');
}
res.status(200).send("ok");
const update = new Update(req.body);
try {
// Store updates for future use.
App.cache(update);
await this.getUpdates(update);
} catch (error) {
console.error(`Error processing update:`, error);
}
});
(async () => {
this.server = app.listen(PORT, async () => {
const url = config.url || process.env.WEBHOOK_URL;
console.log(`WEBHOOK URL: ${url}`);
const webhookInfo = await this.getWebhookInfo();
// If webhook is already set at the correct URL, don't reset.
if (webhookInfo.url === url) {
console.log(`Webhook is already set at ${url}`);
return;
}
// If webhook is set to a different url, reset.
if (webhookInfo.url) {
try {
const deleted = await this.deleteWebhook();
if (deleted) {
console.log("Webhook deleted.");
}
} catch (error) {
console.error(`Unable to delete webhook:`, error);
}
}
const allowed_updates = config.allowed_updates || [UpdateType.ALL];
// If webhook is set incorrectly or unset, set it up.
await this.setWebhook({ url: url, drop_pending_updates: true, secret_token: process.env.SECRET_TOKEN, allowed_updates: allowed_updates });
console.log(`Webhook set at ${url}`);
});
this.server.timeout = config.serverTimeout || 0;
})();
}
/**
* Kills the express server.
*/
async stop() {
if (this.server) {
console.log("Stopping server...");
this.server.close(() => {
console.log("Server stopped.");
});
}
}
}
/**
* Represents a bot object.
*/
class Bot {
/**
*
* @param {string} token
*/
constructor(token, test_mode = false) {
this.token = token;
this.endpoint = `https://api.telegram.org/bot${token}/${test_mode ? "test/" : ""}`
}
/**
* Use this method to send text messages. On success, the sent `Message` is returned.
* @param {{chat_id: number|string, message_thread_id: number, text: string, parse_mode: string, entities: MessageEntity[], link_preview_options: LinkPreviewOptions|{is_disabled: boolean, url: string, prefer_small_media: boolean, prefer_large_media: boolean, show_above_text: boolean}, disable_notification: boolean, protect_content: boolean, message_effect_id: string, reply_parameters: ReplyParameters|Object, reply_markup: InlineKeyboardMarkup|Object}} config
* @returns {Promise<Message>|Promise<null>}
*/
async sendMessage(config) {
let params = App.HTTP({ method: "sendMessage", params: config });
const response = await fetchWithTimeout(this.endpoint, params, 20000);
if (!response.ok) {
console.error("Error:", await response.text());
return null;
}
const message = await response.json();
return new Message(message.result);
}
/**
* Use this method to stream a partial message to a user while the message is being generated. Note that the streamed draft is ephemeral and acts as a temporary 30-second preview - once the output is finalized, you must call sendMessage with the complete message to persist it in the user's chat. Returns True on success.
* @param {{chat_id: number|string, message_thread_id: number, draft_id: number, text: string, parse_mode: string, entities: MessageEntity[]}} config
* @returns {Promise<Boolean>|Promise<null>}
*/
async sendMessageDraft(config) {
let params = App.HTTP({ method: "sendMessageDraft", params: config });
const response = await fetchWithTimeout(this.endpoint, params, 20000);
if (!response.ok) {
console.error("Error:", await response.text());
return null;
}
const message = await response.json();
return new Boolean(message.result);
}
/**
* Use this method to send photos. On success, the sent `Message` is returned.
*
* For example:
*
* ```
* await bot.sendPhoto({chat_id: chat_id, photo: await fs.openAsBlob(path)});
* ```
*
* @param {{chat_id: number|string, message_thread_id: number, photo: InputFile|Blob|string, caption:string, parse_mode:string, caption_entities: Array<MessageEntity>, show_caption_above_media: boolean, has_spoiler:boolean, disable_notification:boolean, protect_content: boolean, message_effect_id: string, reply_parameters: ReplyParameters, reply_markup:InlineKeyboardMarkup}} config
* @returns {Promise<Message>}
*/
async sendPhoto(config) {
const formdata = new FormData();
for (const [key, val] of Object.entries({ ...config, ...App.defaultParams })) {
formdata.append(key, val);
}