-
Notifications
You must be signed in to change notification settings - Fork 3
/
bot_api.js
2113 lines (2012 loc) · 77.5 KB
/
bot_api.js
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
// https://core.telegram.org/bots/api
const stream = require('stream')
const fs = require('fs')
const fsp = fs.promises
const path = require('path')
const crypto = require('crypto')
const { TdClientActor } = require('./td_client_actor')
const _util = require('./util')
/**
* @typedef BotOptions
* @property {boolean} [encrypt_callback_query]
* @property {boolean} [debug_encrypt_callback_query]
* @property {number} [username_cache_period]
* @property {string} [database_directory] The path to the directory for the persistent database; if empty, the current working directory will be used.
* @property {string} [files_directory] The path to the directory for storing files; if empty, database_directory will be used.
* @property {boolean} [use_file_database] If set to true, information about downloaded and uploaded files will be saved between application restarts.
* @property {boolean} [use_chat_info_database] If set to true, the library will maintain a cache of users, basic groups, supergroups, channels and secret chats. Implies use_file_database.
* @property {boolean} [use_message_database] If set to true, the library will maintain a cache of chats and messages. Implies use_chat_info_database.
* @property {boolean} [use_secret_chats] If set to true, support for secret chats will be enabled.
* @property {string} [system_language_code] IETF language tag of the user's operating system language; must be non-empty.
* @property {string} [device_model] Model of the device the application is being run on; must be non-empty.
* @property {string} [system_version] Version of the operating system the application is being run on; must be non-empty.
* @property {string} [application_version] Application version; must be non-empty.
* @property {boolean} [enable_storage_optimizer] If set to true, old files will automatically be deleted.
* @property {boolean} [ignore_file_names] If set to true, original file names will be ignored. Otherwise, downloaded files will be saved under names as close as possible to the original name.
* @property {string} [database_encryption_key] The database encryption key. Usually the encryption key is never changed and is stored in some OS keychain.
* @property {number} [poll_timeout]
* @property {"sync"|"async"|"fdpipe"} [polling_mode]
* @property {boolean} [use_cache]
*/
/**
* Bot API Interface
*/
class Bot extends TdClientActor {
/**
*
* @param {number} api_id
* @param {string} api_hash
* @param {string} bot_token
* @param {boolean} [use_test_dc]
* @param {string} [identifier]
* @param {BotOptions} [options]
*/
constructor(api_id, api_hash, bot_token, use_test_dc = false, identifier = null, options = {}) {
if (!api_id || !api_hash) throw new Error('missing api_id, api_hash')
if (identifier === null) identifier = `bot${bot_token.split(':')[0]}`
const ignore_file_names = 'ignore_file_names' in options ? options.ignore_file_names : true
// @ts-ignore
super(Object.assign({
api_id,
api_hash,
identifier,
use_test_dc,
use_message_database: false,
use_secret_chats: false,
use_chat_info_database: false,
use_file_database: false,
ignore_file_names
}, options))
this.bot_id = parseInt(bot_token.split(':')[0])
this._identifier = identifier
if (options.encrypt_callback_query) {
// @ts-ignore
this._encrypt_callback_query = crypto.scryptSync(bot_token, this._encryption_key, 32)
} else {
this._encrypt_callback_query = false
}
this._debug_encrypt_callback_query = !!options.debug_encrypt_callback_query
this._username_cache_period = options.username_cache_period || 30 * 60 * 1000
this._username_cache = new Map()
let self = this
this.ready = false
this._inited_chat = new Set()
if (bot_token) {
this.on('__updateAuthorizationState', async (/** @type {TdTypes.updateAuthorizationState} */ update) => {
switch (update.authorization_state['@type']) {
case 'authorizationStateWaitPhoneNumber':
return this.run('checkAuthenticationBotToken', {
token: bot_token
})
}
})
}
this.on('__updateMessageSendSucceeded', (/** @type {TdTypes.updateMessageSendSucceeded} */ update) => {
this.emit(`_sendMsg:${update.message.chat_id}:${update.old_message_id}`, {
ok: true,
message: update.message
})
})
this.on('__updateMessageSendFailed', (/** @type {TdTypes.updateMessageSendFailed} */ update) => {
this.emit(`_sendMsg:${update.message.chat_id}:${update.old_message_id}`, {
ok: false,
code: update.error_code,
error_message: update.error_message,
message: update.message
})
})
this.on('__updateNewMessage', (/** @type {TdTypes.updateNewMessage} */ update) => {
this._processIncomingUpdate.call(self, update.message)
})
this.on('__updateMessageEdited', (/** @type {TdTypes.updateMessageEdited} */ update) => {
this._processIncomingEdit.call(self, update)
})
this.on('__updateNewInlineQuery', (/** @type {TdTypes.updateNewInlineQuery} */ update) => {
this._processIncomingInlineQuery.call(self, update)
})
this.on('__updateNewCallbackQuery', (/** @type {TdTypes.updateNewCallbackQuery} */ update) => {
this._processIncomingCallbackQuery.call(self, update)
})
this.on('__updateNewInlineCallbackQuery', (/** @type {TdTypes.updateNewInlineCallbackQuery} */ update) => {
this._processIncomingCallbackQuery.call(self, update)
})
this.on('__updateNewChosenInlineResult', (update) => {
this._processIncomingChosenInlineResult.call(self, update)
})
this.on('__updatePoll', (/** @type {TdTypes.updateNewMessage} */ update) => {
this._processIncomingPoll.call(self, update.message)
})
// setInterval(() => {
// if (!self._closed) {
// return this.run('setOption', {
// name: 'online',
// value: {
// '@type': 'optionValueBoolean',
// value: true
// }
// })
// }
// }, 30000)
this.once('ready', () => this.ready = true)
this.once('ready', () => {
this.run('setOption', {
name: 'ignore_inline_thumbnails',
value: {
'@type': 'optionValueBoolean',
value: true
}
})
this.run('setOption', {
name: 'use_storage_optimizer',
value: {
'@type': 'optionValueBoolean',
value: true
}
})
})
this.conversion = new (require('./bot_types'))(this)
}
/**
*
* @returns {Promise<BotAPITypes.User & BotAPITypes$Extended.User>}
*/
async getMe() {
if (!this.ready) throw new Error('Not ready.')
let me = await this.run('getMe', {})
return this.conversion.buildUser(me, true)
}
async sendMessage(chat_id, text, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageText',
disable_web_page_preview: options.disable_web_page_preview,
text: await this._generateFormattedText(text, options.parse_mode)
}
return this._sendMessage(chat_id, media, options)
}
async forwardMessage(chat_id, from_chat_id, message_ids, options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (!Array.isArray(message_ids)) message_ids = [message_ids]
chat_id = await this._checkChatId(chat_id)
from_chat_id = await this._checkChatId(from_chat_id)
message_ids = message_ids.map((id) => _util.get_tdlib_message_id(id))
let opt = {
chat_id,
from_chat_id,
message_ids,
disable_notification: !!options.disable_notification,
from_background: true
}
await this._initChatIfNeeded(chat_id)
await this._initChatIfNeeded(from_chat_id)
let ret = await this.run('forwardMessages', opt)
if (ret.total_count === 1) {
return this._waitMessageTillSent(chat_id, ret.messages[0].id)
} else {
return Promise.all(ret.messages.map(m => this._waitMessageTillSent(chat_id, m.id)))
}
}
async sendPhoto(chat_id, photo, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessagePhoto',
photo: await this._prepareUploadFile(photo)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.ttl)
media.ttl = options.ttl
return this._sendMessage(chat_id, media, options)
}
async sendAudio(chat_id, audio, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageAudio',
audio: await this._prepareUploadFile(audio, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.duration)
media.duration = options.duration
if (options.title)
media.title = options.title
if (options.performer)
media.performer = options.performer
if (options.thumb)
media.thumbnail = {
thumbnail: await this._prepareUploadFile(options.thumb),
width: 0,
height: 0
}
return this._sendMessage(chat_id, media, options)
}
async sendDocument(chat_id, document, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageDocument',
document: await this._prepareUploadFile(document, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.thumb)
media.thumbnail = {
thumbnail: await this._prepareUploadFile(options.thumb),
width: 0,
height: 0
}
return this._sendMessage(chat_id, media, options)
}
async sendAnimation(chat_id, animation, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageAnimation',
animation: await this._prepareUploadFile(animation, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.duration)
media.duration = options.duration
if (options.width)
media.width = options.width
if (options.height)
media.height = options.height
if (options.thumb)
media.thumbnail = {
thumbnail: await this._prepareUploadFile(options.thumb),
width: 0,
height: 0
}
return this._sendMessage(chat_id, media, options)
}
async sendVideo(chat_id, video, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageVideo',
video: await this._prepareUploadFile(video, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.duration)
media.duration = options.duration
if (options.width)
media.width = options.width
if (options.height)
media.height = options.height
if ('supports_streaming' in options)
media.supports_streaming = options.supports_streaming
if (options.ttl)
media.ttl = options.ttl
if (options.thumb)
media.thumbnail = {
thumbnail: await this._prepareUploadFile(options.thumb),
width: 0,
height: 0
}
return this._sendMessage(chat_id, media, options)
}
async sendVoice(chat_id, voice, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageVoiceNote',
voice_note: await this._prepareUploadFile(voice, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.duration)
media.duration = options.duration
return this._sendMessage(chat_id, media, options)
}
async sendVideoNote(chat_id, video_note, options = {}, file_options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageVideoNote',
video_note: await this._prepareUploadFile(video_note, file_options.filename)
}
if (options.caption)
media.caption = await this._generateFormattedText(options.caption, options.parse_mode)
if (options.duration)
media.duration = options.duration
if (options.length)
media.length = options.length
if (options.thumb)
media.thumbnail = {
thumbnail: await this._prepareUploadFile(options.thumb),
width: 0,
height: 0
}
return this._sendMessage(chat_id, media, options)
}
async sendMediaGroup(chat_id, medias, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let _medias = []
for (let md of medias) {
if (md.type == 'photo') {
let _md = {
'@type': 'inputMessagePhoto',
photo: await this._prepareUploadFile(md.media)
}
if (md.caption)
_md.caption = await this._generateFormattedText(md.caption, md.parse_mode)
_medias.push(_md)
} else if (md.type == 'video') {
let _md = {
'@type': 'inputMessageVideo',
video: await this._prepareUploadFile(_md.media)
}
if (md.caption)
_md.caption = await this._generateFormattedText(md.caption, md.parse_mode)
if (md.duration)
_md.duration = md.duration
if (md.width)
_md.width = md.width
if (md.height)
_md.height = md.height
if ('supports_streaming' in md)
_md.supports_streaming = md.supports_streaming
_medias.push(_md)
}
}
if (_medias.length < 2 || _medias.length > 10) throw new Error('Medias must include 2-10 items.')
return this._sendMessageAlbum(chat_id, _medias, options)
}
async sendLocation(chat_id, lat, long, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageLocation',
location: {
'@type': 'location',
latitude: lat,
longitude: long
}
}
if (options.live_period) {
media.live_period = options.live_period
} else {
media.live_period = 0
}
return this._sendMessage(chat_id, media, options)
}
async editMessageLiveLocation(latitude, longitude, options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (options.chat_id && options.message_id) {
options.chat_id = await this._checkChatId(options.chat_id)
await this._initChatIfNeeded(options.chat_id)
let orig_msg = await this.run('getMessage', {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id)
})
if (orig_msg.content['@type'] != 'messageLocation') throw new Error('Target message is not a live location.')
if (orig_msg.content.expires_in <= 0) throw new Error('Target live location is expired.')
let _opt = {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id),
location: {
latitude,
longitude
}
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
} else if (options.preserve_reply_markup) {
if (orig_msg.reply_markup) {
_opt.reply_markup = orig_msg.reply_markup
}
}
let ret = await this.run('editMessageLiveLocation', _opt)
return this.conversion.buildMessage(ret)
} else if (options.inline_message_id) {
let _opt = {
inline_message_id: options.inline_message_id,
location: {
latitude,
longitude
}
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
}
let ret = await this.run('editMessageLiveLocation', _opt)
if (ret['@type'] == 'ok')
return true
else throw ret
} else {
throw new Error('Please specify chat_id and message_id or inline_message_id.')
}
}
async stopMessageLiveLocation(options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (options.chat_id && options.message_id) {
options.chat_id = await this._checkChatId(options.chat_id)
await this._initChatIfNeeded(options.chat_id)
let orig_msg = await this.run('getMessage', {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id)
})
if (orig_msg.content['@type'] != 'messageLocation') throw new Error('Target message is not a live location.')
if (orig_msg.content.expires_in <= 0) throw new Error('Target live location is expired.')
let _opt = {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id),
location: null
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
} else if (options.preserve_reply_markup) {
if (orig_msg.reply_markup) {
_opt.reply_markup = orig_msg.reply_markup
}
}
let ret = await this.run('editMessageLiveLocation', _opt)
return this.conversion.buildMessage(ret)
} else if (options.inline_message_id) {
let _opt = {
inline_message_id: options.inline_message_id,
location: null
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
}
let ret = await this.run('editMessageLiveLocation', _opt)
if (ret['@type'] == 'ok')
return true
else throw ret
} else {
throw new Error('Please specify chat_id and message_id or inline_message_id.')
}
}
async sendVenue(chat_id, lat, long, title, address, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageVenue',
venue: {
location: {
'@type': 'location',
latitude: lat,
longitude: long
},
title,
address,
provider: 'foursquare',
id: options.foursquare_id || 0
}
}
return this._sendMessage(chat_id, media, options)
}
async sendContact(chat_id, phone_number, first_name, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let media = {
'@type': 'inputMessageContact',
contact: {
phone_number,
first_name,
last_name: options.last_name || ''
}
}
if (options.vcard) media.contact.vcard = options.vcard
return this._sendMessage(chat_id, media, options)
}
async sendPoll(chat_id, question, poll_options, options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (chat_id > 0) throw new Error('A native poll can\'t be sent to a private chat. ')
let media = {
'@type': 'inputMessagePoll',
question,
options: poll_options
}
return this._sendMessage(chat_id, media, options)
}
async stopPoll(chat_id, message_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let orig_msg = await this.run('getMessage', {
chat_id: chat_id,
message_id: _util.get_tdlib_message_id(message_id)
})
if (orig_msg.content['@type'] != 'messagePoll') throw new Error('Target message is not a poll.')
let _opt = {
chat_id: chat_id,
message_id: _util.get_tdlib_message_id(message_id)
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
} else if (options.preserve_reply_markup) {
if (orig_msg.reply_markup) {
_opt.reply_markup = orig_msg.reply_markup
}
}
let ret = await this.run('stopPoll', _opt)
if (ret['@type'] == 'ok') {
let fin_msg = await this.run('getMessage', {
chat_id: chat_id,
message_id: _util.get_tdlib_message_id(message_id)
})
return this.conversion.buildPoll(fin_msg.content.poll)
}
else throw ret
}
async sendChatAction(chat_id, action) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
action: await this.conversion.buildTdlibChatAction(action)
}
let ret = await this.run('sendChatAction', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async getUserProfilePhotos(user_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
let opt = {
user_id,
offset: options.offset || 0,
limit: options.limit || 100
}
let ret = await this.run('getUserProfilePhotos', opt)
return this.conversion.buildUserProfilePhotos(ret)
}
async kickChatMember(chat_id, user_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
user_id = await this._checkChatId(user_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
user_id,
status: {
'@type': options.kick_only ? 'chatMemberStatusLeft' : 'chatMemberStatusBanned',
banned_until_date: 0
}
}
if (options.until_date && !options.kick_only) {
opt.status.banned_until_date = parseInt(options.until_date)
}
let ret = await this.run('setChatMemberStatus', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async unbanChatMember(chat_id, user_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
user_id = await this._checkChatId(user_id)
await this._initChatIfNeeded(chat_id)
const is_member = await this._checkIsMember(chat_id, user_id)
let opt = {
chat_id,
user_id,
status: {
'@type': is_member ? 'chatMemberStatusMember' : 'chatMemberStatusLeft'
}
}
let ret = await this.run('setChatMemberStatus', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async restrictChatMember(chat_id, user_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
user_id = await this._checkChatId(user_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
user_id,
status: {
'@type': 'chatMemberStatusRestricted',
}
}
if (options.until_date) {
opt.status.restricted_until_date = options.until_date
}
if ('can_send_message' in options) opt.status.can_send_messages = options.can_send_messages
if ('can_send_media_messages' in options) opt.status.can_send_media_messages = options.can_send_media_messages
if ('can_send_other_messages' in options) opt.status.can_send_other_messages = options.can_send_other_messages
if ('can_add_web_page_previews' in options) opt.status.can_add_web_page_previews = options.can_add_web_page_previews
let ret = await this.run('setChatMemberStatus', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async promoteChatMember(chat_id, user_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
user_id = await this._checkChatId(user_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
user_id,
status: {
'@type': 'chatMemberStatusAdministrator',
}
}
if ('can_change_info' in options) opt.status.can_change_info = options.can_change_info
if ('can_post_messages' in options) opt.status.can_post_messages = options.can_post_messages
if ('can_edit_messages' in options) opt.status.can_edit_messages = options.can_edit_messages
if ('can_delete_messages' in options) opt.status.can_delete_messages = options.can_delete_messages
if ('can_invite_users' in options) opt.status.can_invite_users = options.can_invite_users
if ('can_restrict_members' in options) opt.status.can_restrict_members = options.can_restrict_members
if ('can_pin_messages' in options) opt.status.can_pin_messages = options.can_pin_messages
if ('can_promote_members' in options) opt.status.can_promote_members = options.can_promote_members
let ret = await this.run('setChatMemberStatus', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async exportChatInviteLink(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id
}
let ret = await this.run('generateChatInviteLink', opt)
return ret.invite_link
}
async setChatPhoto(chat_id, photo) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
photo: this._prepareUploadFile(photo)
}
let ret = await this.run('setChatPhoto', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async deleteChatPhoto(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
photo: this._prepareUploadFile(0)
}
let ret = await this.run('setChatPhoto', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async setChatTitle(chat_id, title) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id,
title
}
let ret = await this.run('setChatTitle', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async setChatDescription(chat_id, description) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
if (chat_id > -Math.pow(10, 12)) throw new Error('Not a supergroup or channel.')
await this._initChatIfNeeded(chat_id)
let opt = {
supergroup_id: Math.abs(chat_id) - Math.pow(10, 12),
description
}
let ret = await this.run('setSupergroupDescription', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async pinChatMessage(chat_id, message_id, options = {}) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
message_id = _util.get_tdlib_message_id(message_id)
let opt = {
chat_id,
message_id,
disable_notification: !!options.disable_notification
}
let ret = await this.run('pinChatMessage', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async unpinChatMessage(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id
}
let ret = await this.run('unpinChatMessage', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async leaveChat(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id
}
let ret = await this.run('leaveChat', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async getUser(user_id) {
if (!this.ready) throw new Error('Not ready.')
return this._getUser(user_id)
}
async getChat(chat_id, full = true) {
if (!this.ready) throw new Error('Not ready.')
return this._getChat(chat_id, full)
}
async getChatAdministrators(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
chat_id
}
if (chat_id < -Math.pow(10, 12)) {
let supergroup_id = Math.abs(chat_id) - Math.pow(10, 12)
let admin_members = await this.run('getSupergroupMembers', {
supergroup_id,
filter: {
'@type': 'supergroupMembersFilterAdministrators'
},
offset: 0,
limit: 200
})
let admins = []
for (let a of admin_members.members) {
admins.push(await this.conversion.buildChatMember(a))
}
return admins
} else if (chat_id < 0) {
let ret = await this.run('getChatAdministrators', opt)
let admins = []
for (let a of ret.user_ids) {
let member = await this._getChatMember(chat_id, a)
admins.push(member)
}
return admins
} else {
throw new Error('Not a chat')
}
}
async getChatMembersCount(chat_id) {
if (!this.ready) throw new Error('Not ready.')
try {
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let chat = await this.run('getChat', {
chat_id
})
if (chat.type['@type'] == 'chatTypeSupergroup') {
let additional_full = await this.run('getSupergroupFullInfo', {
supergroup_id: chat.type.supergroup_id
})
return additional_full.member_count
} else if (chat.type['@type'] == 'chatTypeBasicGroup') {
let additional = await this.run('getBasicGroup', {
basic_group_id: chat.type.basic_group_id
})
return additional.member_count
} else if (chat.type['@type'] == 'chatTypePrivate') {
throw new Error('Not a group or a channel.')
} else {
throw new Error('Unknown Chat Type.')
}
} catch (e) {
throw new Error(e.message)
}
}
async getChatMember(chat_id, user_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
return this._getChatMember(chat_id, user_id)
}
async setChatStickerSet(chat_id, sticker_set) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let pack_id
if (isNaN(sticker_set)) {
// is Name
pack_id = await this.run('searchStickerSet', {
sticker_set
})
pack_id = pack_id.id
} else {
// is ID
pack_id = sticker_set
}
let opt = {
supergroup_id: Math.abs(chat_id) - Math.pow(10, 12),
sticker_set_id: pack_id
}
let ret = await this.run('setSupergroupStickerSet', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async deleteChatStickerSet(chat_id) {
if (!this.ready) throw new Error('Not ready.')
chat_id = await this._checkChatId(chat_id)
await this._initChatIfNeeded(chat_id)
let opt = {
supergroup_id: Math.abs(chat_id) - Math.pow(10, 12),
sticker_set_id: 0
}
let ret = await this.run('setSupergroupStickerSet', opt)
if (ret['@type'] == 'ok') return true
else throw ret
}
async answerCallbackQuery(callback_query_id, options = {}) {
/* The older method signature (in/before v0.27.1) was answerCallbackQuery(callbackQueryId, text, showAlert).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library */
if (typeof options !== 'object') {
options = {
callback_query_id: arguments[0],
text: arguments[1],
show_alert: arguments[2],
}
}
/* The older method signature (in/before v0.29.0) was answerCallbackQuery([options]).
* We need to ensure backwards-compatibility while maintaining
* consistency of the method signatures throughout the library. */
if (typeof callback_query_id === 'object') {
options = callback_query_id
} else {
options.callback_query_id = callback_query_id
}
let ret = await this.run('answerCallbackQuery', options)
if (ret['@type'] == 'ok') return true
else throw ret
}
async editMessageText(text, options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (options.chat_id && options.message_id) {
options.chat_id = await this._checkChatId(options.chat_id)
await this._initChatIfNeeded(options.chat_id)
let orig_msg = await this.run('getMessage', {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id)
})
if (orig_msg.content['@type'] != 'messageText') throw new Error('Target message is not a text message.')
let _opt = {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id),
input_message_content: {
'@type': 'inputMessageText',
text: await this._generateFormattedText(text, options.parse_mode),
disable_web_page_preview: !!options.disable_web_page_preview
}
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
} else if (options.preserve_reply_markup) {
if (orig_msg.reply_markup) {
_opt.reply_markup = orig_msg.reply_markup
}
}
let ret = await this.run('editMessageText', _opt)
return this.conversion.buildMessage(ret)
} else if (options.inline_message_id) {
let _opt = {
inline_message_id: options.inline_message_id,
input_message_content: {
'@type': 'inputMessageText',
text: await this._generateFormattedText(text, options.parse_mode),
disable_web_page_preview: !!options.disable_web_page_preview
}
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
}
let ret = await this.run('editInlineMessageText', _opt)
if (ret['@type'] == 'ok')
return true
else throw ret
} else {
throw new Error('Please specify chat_id and message_id or inline_message_id.')
}
}
async editMessageCaption(caption, options = {}) {
if (!this.ready) throw new Error('Not ready.')
if (options.chat_id && options.message_id) {
options.chat_id = await this._checkChatId(options.chat_id)
await this._initChatIfNeeded(options.chat_id)
let orig_msg = await this.run('getMessage', {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id)
})
let _opt = {
chat_id: options.chat_id,
message_id: _util.get_tdlib_message_id(options.message_id),
caption: await this._generateFormattedText(caption, options.parse_mode)
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
} else if (options.preserve_reply_markup) {
if (orig_msg.reply_markup) {
_opt.reply_markup = orig_msg.reply_markup
}
}
let ret = await this.run('editMessageCaption', _opt)
return this.conversion.buildMessage(ret)
} else if (options.inline_message_id) {
let _opt = {
inline_message_id: options.inline_message_id,
caption: await this._generateFormattedText(caption, options.parse_mode)
}
if (options.reply_markup) {
_opt.reply_markup = this._parseReplyMarkup(options.reply_markup)
}
let ret = await this.run('editInlineMessageCaption', _opt)
if (ret['@type'] == 'ok')
return true
else throw ret
} else {
throw new Error('Please specify chat_id and message_id or inline_message_id.')
}
}