@zero-bot.net/tg-bot-api 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3057 @@
1
+ // shims
2
+ require('array.prototype.findindex').shim(); // for Node.js v0.x
3
+
4
+ const errors = require('./errors');
5
+ const TelegramBotWebHook = require('./telegramWebHook');
6
+ const TelegramBotPolling = require('./telegramPolling');
7
+ const debug = require('debug')('@zero-bot.net/tg-bot-api');
8
+ const EventEmitter = require('eventemitter3');
9
+ const fileType = require('file-type');
10
+ const requestBase = require('@zero-bot.net/request');
11
+ const request = options => new Promise((resolve, reject) => {
12
+ requestBase(options, (err, response) => {
13
+ if (err) reject(err);else resolve(response);
14
+ });
15
+ });
16
+ const streamedRequest = requestBase;
17
+ const qs = require('querystring');
18
+ const stream = require('stream');
19
+ const mime = require('mime');
20
+ const path = require('path');
21
+ const URL = require('url');
22
+ const fs = require('fs');
23
+ const pump = require('pump');
24
+ const deprecate = require('./utils').deprecate;
25
+
26
+ const _messageTypes = ['text', 'animation', 'audio', 'channel_chat_created', 'contact', 'delete_chat_photo', 'dice', 'document', 'game', 'group_chat_created', 'invoice', 'left_chat_member', 'location', 'migrate_from_chat_id', 'migrate_to_chat_id', 'new_chat_members', 'new_chat_photo', 'new_chat_title', 'passport_data', 'photo', 'pinned_message', 'poll', 'sticker', 'successful_payment', 'supergroup_chat_created', 'video', 'video_note', 'voice', 'video_chat_started', 'video_chat_ended', 'video_chat_participants_invited', 'video_chat_scheduled', 'message_auto_delete_timer_changed', 'chat_invite_link', 'chat_member_updated', 'web_app_data', 'message_reaction'];
27
+
28
+ const _deprecatedMessageTypes = ['new_chat_participant', 'left_chat_participant'];
29
+
30
+ /**
31
+ * JSON-serialize data. If the provided data is already a String,
32
+ * return it as is.
33
+ * @private
34
+ * @param {*} data
35
+ * @return {String}
36
+ */
37
+ function stringify(data) {
38
+ if (typeof data === 'string') {
39
+ return data;
40
+ }
41
+ return JSON.stringify(data);
42
+ }
43
+
44
+ class TelegramBot extends EventEmitter {
45
+ /**
46
+ * The different errors the library uses.
47
+ * @type {Object}
48
+ */
49
+ static get errors() {
50
+ return errors;
51
+ }
52
+
53
+ /**
54
+ * The types of message updates the library handles.
55
+ * @type {String[]}
56
+ */
57
+ static get messageTypes() {
58
+ return _messageTypes;
59
+ }
60
+
61
+ /**
62
+ * Add listener for the specified [event](https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#events).
63
+ * This is the usual `emitter.on()` method.
64
+ * @param {String} event
65
+ * @param {Function} listener
66
+ * @see {@link https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#events|Available events}
67
+ * @see https://nodejs.org/api/events.html#events_emitter_on_eventname_listener
68
+ */
69
+ on(event, listener) {
70
+ if (_deprecatedMessageTypes.indexOf(event) !== -1) {
71
+ const url = 'https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#events';
72
+ deprecate(`Events ${_deprecatedMessageTypes.join(',')} are deprecated. See the updated list of events: ${url}`);
73
+ }
74
+ super.on(event, listener);
75
+ }
76
+
77
+ /**
78
+ * Both request method to obtain messages are implemented. To use standard polling, set `polling: true`
79
+ * on `options`. Notice that [webHook](https://core.telegram.org/bots/api#setwebhook) will need a SSL certificate.
80
+ * Emits `message` when a message arrives.
81
+ *
82
+ * @class TelegramBot
83
+ * @constructor
84
+ * @param {String} token Bot Token
85
+ * @param {Object} [options]
86
+ * @param {Boolean|Object} [options.polling=false] Set true to enable polling or set options.
87
+ * If a WebHook has been set, it will be deleted automatically.
88
+ * @param {String|Number} [options.polling.timeout=10] *Deprecated. Use `options.polling.params` instead*.
89
+ * Timeout in seconds for long polling.
90
+ * @param {Boolean} [options.testEnvironment=false] Set true to work with test enviroment.
91
+ * When working with the test environment, you may use HTTP links without TLS to test your Web App.
92
+ * @param {String|Number} [options.polling.interval=300] Interval between requests in miliseconds
93
+ * @param {Boolean} [options.polling.autoStart=true] Start polling immediately
94
+ * @param {Object} [options.polling.params] Parameters to be used in polling API requests.
95
+ * See https://core.telegram.org/bots/api#getupdates for more information.
96
+ * @param {Number} [options.polling.params.timeout=10] Timeout in seconds for long polling.
97
+ * @param {Boolean|Object} [options.webHook=false] Set true to enable WebHook or set options
98
+ * @param {String} [options.webHook.host="0.0.0.0"] Host to bind to
99
+ * @param {Number} [options.webHook.port=8443] Port to bind to
100
+ * @param {String} [options.webHook.key] Path to file with PEM private key for webHook server.
101
+ * The file is read **synchronously**!
102
+ * @param {String} [options.webHook.cert] Path to file with PEM certificate (public) for webHook server.
103
+ * The file is read **synchronously**!
104
+ * @param {String} [options.webHook.pfx] Path to file with PFX private key and certificate chain for webHook server.
105
+ * The file is read **synchronously**!
106
+ * @param {Boolean} [options.webHook.autoOpen=true] Open webHook immediately
107
+ * @param {Object} [options.webHook.https] Options to be passed to `https.createServer()`.
108
+ * Note that `options.webHook.key`, `options.webHook.cert` and `options.webHook.pfx`, if provided, will be
109
+ * used to override `key`, `cert` and `pfx` in this object, respectively.
110
+ * See https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener for more information.
111
+ * @param {String} [options.webHook.healthEndpoint="/healthz"] An endpoint for health checks that always responds with 200 OK
112
+ * @param {Boolean} [options.onlyFirstMatch=false] Set to true to stop after first match. Otherwise, all regexps are executed
113
+ * @param {Object} [options.request] Options which will be added for all requests to telegram api.
114
+ * See https://github.com/request/request#requestoptions-callback for more information.
115
+ * @param {String} [options.baseApiUrl="https://api.telegram.org"] API Base URl; useful for proxying and testing
116
+ * @param {Boolean} [options.filepath=true] Allow passing file-paths as arguments when sending files,
117
+ * such as photos using `TelegramBot#sendPhoto()`. See [usage information][usage-sending-files-performance]
118
+ * for more information on this option and its consequences.
119
+ * @param {Boolean} [options.badRejection=false] Set to `true`
120
+ * **if and only if** the Node.js version you're using terminates the
121
+ * process on unhandled rejections. This option is only for
122
+ * *forward-compatibility purposes*.
123
+ * @see https://core.telegram.org/bots/api
124
+ */
125
+ constructor(token, options = {}) {
126
+ super();
127
+ this.token = token;
128
+ this.options = options;
129
+ this.options.polling = typeof options.polling === 'undefined' ? false : options.polling;
130
+ this.options.webHook = typeof options.webHook === 'undefined' ? false : options.webHook;
131
+ this.options.baseApiUrl = options.baseApiUrl || 'https://api.telegram.org';
132
+ this.options.filepath = typeof options.filepath === 'undefined' ? true : options.filepath;
133
+ this.options.badRejection = typeof options.badRejection === 'undefined' ? false : options.badRejection;
134
+ this._textRegexpCallbacks = [];
135
+ this._replyListenerId = 0;
136
+ this._replyListeners = [];
137
+ this._polling = null;
138
+ this._webHook = null;
139
+
140
+ if (options.polling) {
141
+ const autoStart = options.polling.autoStart;
142
+ if (typeof autoStart === 'undefined' || autoStart === true) {
143
+ this.startPolling();
144
+ }
145
+ }
146
+
147
+ if (options.webHook) {
148
+ const autoOpen = options.webHook.autoOpen;
149
+ if (typeof autoOpen === 'undefined' || autoOpen === true) {
150
+ this.openWebHook();
151
+ }
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Generates url with bot token and provided path/method you want to be got/executed by bot
157
+ * @param {String} path
158
+ * @return {String} url
159
+ * @private
160
+ * @see https://core.telegram.org/bots/api#making-requests
161
+ */
162
+ _buildURL(_path) {
163
+ return `${this.options.baseApiUrl}/bot${this.token}${this.options.testEnvironment ? '/test' : ''}/${_path}`;
164
+ }
165
+
166
+ /**
167
+ * Fix 'reply_markup' parameter by making it JSON-serialized, as
168
+ * required by the Telegram Bot API
169
+ * @param {Object} obj Object; either 'form' or 'qs'
170
+ * @private
171
+ * @see https://core.telegram.org/bots/api#sendmessage
172
+ */
173
+ _fixReplyMarkup(obj) {
174
+ const replyMarkup = obj.reply_markup;
175
+ if (replyMarkup && typeof replyMarkup !== 'string') {
176
+ obj.reply_markup = stringify(replyMarkup);
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Fix 'entities' or 'caption_entities' or 'explanation_entities' parameter by making it JSON-serialized, as
182
+ * required by the Telegram Bot API
183
+ * @param {Object} obj Object;
184
+ * @private
185
+ * @see https://core.telegram.org/bots/api#sendmessage
186
+ * @see https://core.telegram.org/bots/api#copymessage
187
+ * @see https://core.telegram.org/bots/api#sendpoll
188
+ */
189
+ _fixEntitiesField(obj) {
190
+ const entities = obj.entities;
191
+ const captionEntities = obj.caption_entities;
192
+ const explanationEntities = obj.explanation_entities;
193
+ if (entities && typeof entities !== 'string') {
194
+ obj.entities = stringify(entities);
195
+ }
196
+
197
+ if (captionEntities && typeof captionEntities !== 'string') {
198
+ obj.caption_entities = stringify(captionEntities);
199
+ }
200
+
201
+ if (explanationEntities && typeof explanationEntities !== 'string') {
202
+ obj.explanation_entities = stringify(explanationEntities);
203
+ }
204
+ }
205
+
206
+ _fixAddFileThumbnail(options, opts) {
207
+ if (options.thumb) {
208
+ if (opts.formData === null) {
209
+ opts.formData = {};
210
+ }
211
+
212
+ const attachName = 'photo';
213
+ const [formData] = this._formatSendData(attachName, options.thumb.replace('attach://', ''));
214
+
215
+ if (formData) {
216
+ opts.formData[attachName] = formData[attachName];
217
+ opts.qs.thumbnail = `attach://${attachName}`;
218
+ }
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Fix 'reply_parameters' parameter by making it JSON-serialized, as
224
+ * required by the Telegram Bot API
225
+ * @param {Object} obj Object; either 'form' or 'qs'
226
+ * @private
227
+ * @see https://core.telegram.org/bots/api#sendmessage
228
+ */
229
+ _fixReplyParameters(obj) {
230
+ if (obj.hasOwnProperty('reply_parameters') && typeof obj.reply_parameters !== 'string') {
231
+ obj.reply_parameters = stringify(obj.reply_parameters);
232
+ }
233
+ }
234
+
235
+ /**
236
+ * Make request against the API
237
+ * @param {String} _path API endpoint
238
+ * @param {Object} [options]
239
+ * @private
240
+ * @return {Promise}
241
+ */
242
+ _request(_path, options = {}) {
243
+ if (!this.token) {
244
+ return Promise.reject(new errors.FatalError('Telegram Bot Token not provided!'));
245
+ }
246
+
247
+ if (this.options.request) {
248
+ Object.assign(options, this.options.request);
249
+ }
250
+
251
+ if (options.form) {
252
+ this._fixReplyMarkup(options.form);
253
+ this._fixEntitiesField(options.form);
254
+ this._fixReplyParameters(options.form);
255
+ }
256
+ if (options.qs) {
257
+ this._fixReplyMarkup(options.qs);
258
+ this._fixReplyParameters(options.qs);
259
+ }
260
+
261
+ options.method = 'POST';
262
+ options.url = this._buildURL(_path);
263
+ options.simple = false;
264
+ options.resolveWithFullResponse = true;
265
+ options.forever = true;
266
+ debug('HTTP request: %j', options);
267
+ return request(options).then(resp => {
268
+ let data;
269
+ try {
270
+ data = resp.body = JSON.parse(resp.body);
271
+ } catch (err) {
272
+ throw new errors.ParseError(`Error parsing response: ${resp.body}`, resp);
273
+ }
274
+
275
+ if (data.ok) {
276
+ return data.result;
277
+ }
278
+
279
+ throw new errors.TelegramError(`${data.error_code} ${data.description}`, resp);
280
+ }).catch(error => {
281
+ // TODO: why can't we do `error instanceof errors.BaseError`?
282
+ if (error.response) throw error;
283
+ throw new errors.FatalError(error);
284
+ });
285
+ }
286
+
287
+ /**
288
+ * Format data to be uploaded; handles file paths, streams and buffers
289
+ * @param {String} type
290
+ * @param {String|stream.Stream|Buffer} data
291
+ * @param {Object} fileOptions File options
292
+ * @param {String} [fileOptions.filename] File name
293
+ * @param {String} [fileOptions.contentType] Content type (i.e. MIME)
294
+ * @return {Array} formatted
295
+ * @return {Object} formatted[0] formData
296
+ * @return {String} formatted[1] fileId
297
+ * @throws Error if Buffer file type is not supported.
298
+ * @see https://npmjs.com/package/file-type
299
+ * @private
300
+ */
301
+ _formatSendData(type, data, fileOptions = {}) {
302
+ const deprecationMessage = 'See https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files' + ' for more information on how sending files has been improved and' + ' on how to disable this deprecation message altogether.';
303
+ let filedata = data;
304
+ let filename = fileOptions.filename;
305
+ let contentType = fileOptions.contentType;
306
+
307
+ if (data instanceof stream.Stream) {
308
+ if (!filename && data.path) {
309
+ // Will be 'null' if could not be parsed.
310
+ // For example, 'data.path' === '/?id=123' from 'request("https://example.com/?id=123")'
311
+ const url = URL.parse(path.basename(data.path.toString()));
312
+ if (url.pathname) {
313
+ filename = qs.unescape(url.pathname);
314
+ }
315
+ }
316
+ } else if (Buffer.isBuffer(data)) {
317
+ if (!filename && !process.env.NTBA_FIX_350) {
318
+ deprecate(`Buffers will have their filenames default to "filename" instead of "data". ${deprecationMessage}`);
319
+ filename = 'data';
320
+ }
321
+ if (!contentType) {
322
+ const filetype = fileType(data);
323
+ if (filetype) {
324
+ contentType = filetype.mime;
325
+ const ext = filetype.ext;
326
+ if (ext && !process.env.NTBA_FIX_350) {
327
+ filename = `${filename}.${ext}`;
328
+ }
329
+ } else if (!process.env.NTBA_FIX_350) {
330
+ deprecate(`An error will no longer be thrown if file-type of buffer could not be detected. ${deprecationMessage}`);
331
+ throw new errors.FatalError('Unsupported Buffer file-type');
332
+ }
333
+ }
334
+ } else if (data) {
335
+ if (this.options.filepath && fs.existsSync(data)) {
336
+ filedata = fs.createReadStream(data);
337
+ if (!filename) {
338
+ filename = path.basename(data);
339
+ }
340
+ } else {
341
+ return [null, data];
342
+ }
343
+ } else {
344
+ return [null, data];
345
+ }
346
+
347
+ filename = filename || 'filename';
348
+ contentType = contentType || mime.lookup(filename);
349
+ if (process.env.NTBA_FIX_350) {
350
+ contentType = contentType || 'application/octet-stream';
351
+ } else {
352
+ deprecate(`In the future, content-type of files you send will default to "application/octet-stream". ${deprecationMessage}`);
353
+ }
354
+
355
+ // TODO: Add missing file extension.
356
+
357
+ return [{
358
+ [type]: {
359
+ value: filedata,
360
+ options: {
361
+ filename,
362
+ contentType
363
+ }
364
+ }
365
+ }, null];
366
+ }
367
+
368
+ /**
369
+ * Start polling.
370
+ * Rejects returned promise if a WebHook is being used by this instance.
371
+ * @param {Object} [options]
372
+ * @param {Boolean} [options.restart=true] Consecutive calls to this method causes polling to be restarted
373
+ * @return {Promise}
374
+ */
375
+ startPolling(options = {}) {
376
+ if (this.hasOpenWebHook()) {
377
+ return Promise.reject(new errors.FatalError('Polling and WebHook are mutually exclusive'));
378
+ }
379
+ options.restart = typeof options.restart === 'undefined' ? true : options.restart;
380
+ if (!this._polling) {
381
+ this._polling = new TelegramBotPolling(this);
382
+ }
383
+ return this._polling.start(options);
384
+ }
385
+
386
+ /**
387
+ * Alias of `TelegramBot#startPolling()`. This is **deprecated**.
388
+ * @param {Object} [options]
389
+ * @return {Promise}
390
+ * @deprecated
391
+ */
392
+ initPolling() {
393
+ deprecate('TelegramBot#initPolling() is deprecated. Use TelegramBot#startPolling() instead.');
394
+ return this.startPolling();
395
+ }
396
+
397
+ /**
398
+ * Stops polling after the last polling request resolves.
399
+ * Multiple invocations do nothing if polling is already stopped.
400
+ * Returning the promise of the last polling request is **deprecated**.
401
+ * @param {Object} [options] Options
402
+ * @param {Boolean} [options.cancel] Cancel current request
403
+ * @param {String} [options.reason] Reason for stopping polling
404
+ * @return {Promise}
405
+ */
406
+ stopPolling(options) {
407
+ if (!this._polling) {
408
+ return Promise.resolve();
409
+ }
410
+ return this._polling.stop(options);
411
+ }
412
+
413
+ /**
414
+ * Get link for file.
415
+ * Use this method to get link for file for subsequent use.
416
+ * Attention: link will be valid for 1 hour.
417
+ *
418
+ * This method is a sugar extension of the (getFile)[#getfilefileid] method,
419
+ * which returns just path to file on remote server (you will have to manually build full uri after that).
420
+ *
421
+ * @param {String} fileId File identifier to get info about
422
+ * @param {Object} [options] Additional Telegram query options
423
+ * @return {Promise} Promise which will have *fileURI* in resolve callback
424
+ * @see https://core.telegram.org/bots/api#getfile
425
+ */
426
+ getFileLink(fileId, form = {}) {
427
+ return this.getFile(fileId, form).then(resp => `${this.options.baseApiUrl}/file/bot${this.token}/${resp.file_path}`);
428
+ }
429
+
430
+ /**
431
+ * Return a readable stream for file.
432
+ *
433
+ * `fileStream.path` is the specified file ID i.e. `fileId`.
434
+ * `fileStream` emits event `info` passing a single argument i.e.
435
+ * `info` with the interface `{ uri }` where `uri` is the URI of the
436
+ * file on Telegram servers.
437
+ *
438
+ * This method is a sugar extension of the [getFileLink](#TelegramBot+getFileLink) method,
439
+ * which returns the full URI to the file on remote server.
440
+ *
441
+ * @param {String} fileId File identifier to get info about
442
+ * @param {Object} [options] Additional Telegram query options
443
+ * @return {stream.Readable} fileStream
444
+ */
445
+ getFileStream(fileId, form = {}) {
446
+ const fileStream = new stream.PassThrough();
447
+ fileStream.path = fileId;
448
+ this.getFileLink(fileId, form).then(fileURI => {
449
+ fileStream.emit('info', {
450
+ uri: fileURI
451
+ });
452
+ pump(streamedRequest(Object.assign({ uri: fileURI }, this.options.request)), fileStream);
453
+ }).catch(error => {
454
+ fileStream.emit('error', error);
455
+ });
456
+ return fileStream;
457
+ }
458
+
459
+ /**
460
+ * Downloads file in the specified folder.
461
+ *
462
+ * This method is a sugar extension of the [getFileStream](#TelegramBot+getFileStream) method,
463
+ * which returns a readable file stream.
464
+ *
465
+ * @param {String} fileId File identifier to get info about
466
+ * @param {String} downloadDir Absolute path to the folder in which file will be saved
467
+ * @param {Object} [options] Additional Telegram query options
468
+ * @return {Promise} Promise, which will have *filePath* of downloaded file in resolve callback
469
+ */
470
+ downloadFile(fileId, downloadDir, form = {}) {
471
+ let resolve;
472
+ let reject;
473
+ const promise = new Promise((a, b) => {
474
+ resolve = a;
475
+ reject = b;
476
+ });
477
+ const fileStream = this.getFileStream(fileId, form);
478
+ fileStream.on('info', info => {
479
+ const fileName = info.uri.slice(info.uri.lastIndexOf('/') + 1);
480
+ // TODO: Ensure fileName doesn't contains slashes
481
+ const filePath = path.join(downloadDir, fileName);
482
+ pump(fileStream, fs.createWriteStream(filePath), error => {
483
+ if (error) {
484
+ return reject(error);
485
+ }
486
+ return resolve(filePath);
487
+ });
488
+ });
489
+ fileStream.on('error', err => {
490
+ reject(err);
491
+ });
492
+ return promise;
493
+ }
494
+
495
+ /**
496
+ * Register a RegExp to test against an incomming text message.
497
+ * @param {RegExp} regexpRexecuted with `exec`.
498
+ * @param {Function} callback Callback will be called with 2 parameters,
499
+ * the `msg` and the result of executing `regexp.exec` on message text.
500
+ */
501
+ onText(regexp, callback) {
502
+ this._textRegexpCallbacks.push({ regexp, callback });
503
+ }
504
+
505
+ /**
506
+ * Remove a listener registered with `onText()`.
507
+ * @param {RegExp} regexp RegExp used previously in `onText()`
508
+ * @return {Object} deletedListener The removed reply listener if
509
+ * found. This object has `regexp` and `callback`
510
+ * properties. If not found, returns `null`.
511
+ */
512
+ removeTextListener(regexp) {
513
+ const index = this._textRegexpCallbacks.findIndex(textListener => {
514
+ return String(textListener.regexp) === String(regexp);
515
+ });
516
+ if (index === -1) {
517
+ return null;
518
+ }
519
+ return this._textRegexpCallbacks.splice(index, 1)[0];
520
+ }
521
+
522
+ /**
523
+ * Remove all listeners registered with `onText()`.
524
+ */
525
+ clearTextListeners() {
526
+ this._textRegexpCallbacks = [];
527
+ }
528
+
529
+ /**
530
+ * Register a reply to wait for a message response.
531
+ *
532
+ * @param {Number|String} chatId The chat id where the message cames from.
533
+ * @param {Number|String} messageId The message id to be replied.
534
+ * @param {Function} callback Callback will be called with the reply
535
+ * message.
536
+ * @return {Number} id The ID of the inserted reply listener.
537
+ */
538
+ onReplyToMessage(chatId, messageId, callback) {
539
+ const id = ++this._replyListenerId;
540
+ this._replyListeners.push({
541
+ id,
542
+ chatId,
543
+ messageId,
544
+ callback
545
+ });
546
+ return id;
547
+ }
548
+
549
+ /**
550
+ * Removes a reply that has been prev. registered for a message response.
551
+ * @param {Number} replyListenerId The ID of the reply listener.
552
+ * @return {Object} deletedListener The removed reply listener if
553
+ * found. This object has `id`, `chatId`, `messageId` and `callback`
554
+ * properties. If not found, returns `null`.
555
+ */
556
+ removeReplyListener(replyListenerId) {
557
+ const index = this._replyListeners.findIndex(replyListener => {
558
+ return replyListener.id === replyListenerId;
559
+ });
560
+ if (index === -1) {
561
+ return null;
562
+ }
563
+ return this._replyListeners.splice(index, 1)[0];
564
+ }
565
+
566
+ /**
567
+ * Removes all replies that have been prev. registered for a message response.
568
+ *
569
+ * @return {Array} deletedListeners An array of removed listeners.
570
+ */
571
+ clearReplyListeners() {
572
+ this._replyListeners = [];
573
+ }
574
+
575
+ /**
576
+ * Return true if polling. Otherwise, false.
577
+ *
578
+ * @return {Boolean}
579
+ */
580
+ isPolling() {
581
+ return this._polling ? this._polling.isPolling() : false;
582
+ }
583
+
584
+ /**
585
+ * Open webhook.
586
+ * Multiple invocations do nothing if webhook is already open.
587
+ * Rejects returned promise if Polling is being used by this instance.
588
+ *
589
+ * @return {Promise}
590
+ */
591
+ openWebHook() {
592
+ if (this.isPolling()) {
593
+ return Promise.reject(new errors.FatalError('WebHook and Polling are mutually exclusive'));
594
+ }
595
+ if (!this._webHook) {
596
+ this._webHook = new TelegramBotWebHook(this);
597
+ }
598
+ return this._webHook.open();
599
+ }
600
+
601
+ /**
602
+ * Close webhook after closing all current connections.
603
+ * Multiple invocations do nothing if webhook is already closed.
604
+ *
605
+ * @return {Promise} Promise
606
+ */
607
+ closeWebHook() {
608
+ if (!this._webHook) {
609
+ return Promise.resolve();
610
+ }
611
+ return this._webHook.close();
612
+ }
613
+
614
+ /**
615
+ * Return true if using webhook and it is open i.e. accepts connections.
616
+ * Otherwise, false.
617
+ *
618
+ * @return {Boolean}
619
+ */
620
+ hasOpenWebHook() {
621
+ return this._webHook ? this._webHook.isOpen() : false;
622
+ }
623
+
624
+ /**
625
+ * Process an update; emitting the proper events and executing regexp
626
+ * callbacks. This method is useful should you be using a different
627
+ * way to fetch updates, other than those provided by TelegramBot.
628
+ *
629
+ * @param {Object} update
630
+ * @see https://core.telegram.org/bots/api#update
631
+ */
632
+ processUpdate(update) {
633
+ debug('Process Update %j', update);
634
+ const message = update.message;
635
+ const editedMessage = update.edited_message;
636
+ const channelPost = update.channel_post;
637
+ const editedChannelPost = update.edited_channel_post;
638
+ const businessConnection = update.business_connection;
639
+ const businesssMessage = update.business_message;
640
+ const editedBusinessMessage = update.edited_business_message;
641
+ const deletedBusinessMessage = update.deleted_business_messages;
642
+ const messageReaction = update.message_reaction;
643
+ const messageReactionCount = update.message_reaction_count;
644
+ const inlineQuery = update.inline_query;
645
+ const chosenInlineResult = update.chosen_inline_result;
646
+ const callbackQuery = update.callback_query;
647
+ const shippingQuery = update.shipping_query;
648
+ const preCheckoutQuery = update.pre_checkout_query;
649
+ const poll = update.poll;
650
+ const pollAnswer = update.poll_answer;
651
+ const myChatMember = update.my_chat_member;
652
+ const chatMember = update.chat_member;
653
+ const chatJoinRequest = update.chat_join_request;
654
+ const chatBoost = update.chat_boost;
655
+ const removedChatBoost = update.removed_chat_boost;
656
+
657
+ if (message) {
658
+ debug('Process Update message %j', message);
659
+ const metadata = {};
660
+ metadata.type = TelegramBot.messageTypes.find(messageType => {
661
+ return message[messageType];
662
+ });
663
+ this.emit('message', message, metadata);
664
+ if (metadata.type) {
665
+ debug('Emitting %s: %j', metadata.type, message);
666
+ this.emit(metadata.type, message, metadata);
667
+ }
668
+ if (message.text) {
669
+ debug('Text message');
670
+ this._textRegexpCallbacks.some(reg => {
671
+ debug('Matching %s with %s', message.text, reg.regexp);
672
+
673
+ if (!(reg.regexp instanceof RegExp)) {
674
+ reg.regexp = new RegExp(reg.regexp);
675
+ }
676
+
677
+ const result = reg.regexp.exec(message.text);
678
+ if (!result) {
679
+ return false;
680
+ }
681
+ // reset index so we start at the beginning of the regex each time
682
+ reg.regexp.lastIndex = 0;
683
+ debug('Matches %s', reg.regexp);
684
+ reg.callback(message, result);
685
+ // returning truthy value exits .some
686
+ return this.options.onlyFirstMatch;
687
+ });
688
+ }
689
+ if (message.reply_to_message) {
690
+ // Only callbacks waiting for this message
691
+ this._replyListeners.forEach(reply => {
692
+ // Message from the same chat
693
+ if (reply.chatId === message.chat.id) {
694
+ // Responding to that message
695
+ if (reply.messageId === message.reply_to_message.message_id) {
696
+ // Resolve the promise
697
+ reply.callback(message);
698
+ }
699
+ }
700
+ });
701
+ }
702
+ } else if (editedMessage) {
703
+ debug('Process Update edited_message %j', editedMessage);
704
+ this.emit('edited_message', editedMessage);
705
+ if (editedMessage.text) {
706
+ this.emit('edited_message_text', editedMessage);
707
+ }
708
+ if (editedMessage.caption) {
709
+ this.emit('edited_message_caption', editedMessage);
710
+ }
711
+ } else if (channelPost) {
712
+ debug('Process Update channel_post %j', channelPost);
713
+ this.emit('channel_post', channelPost);
714
+ } else if (editedChannelPost) {
715
+ debug('Process Update edited_channel_post %j', editedChannelPost);
716
+ this.emit('edited_channel_post', editedChannelPost);
717
+ if (editedChannelPost.text) {
718
+ this.emit('edited_channel_post_text', editedChannelPost);
719
+ }
720
+ if (editedChannelPost.caption) {
721
+ this.emit('edited_channel_post_caption', editedChannelPost);
722
+ }
723
+ } else if (businessConnection) {
724
+ debug('Process Update business_connection %j', businessConnection);
725
+ this.emit('business_connection', businessConnection);
726
+ } else if (businesssMessage) {
727
+ debug('Process Update business_message %j', businesssMessage);
728
+ this.emit('business_message', businesssMessage);
729
+ } else if (editedBusinessMessage) {
730
+ debug('Process Update edited_business_message %j', editedBusinessMessage);
731
+ this.emit('edited_business_message', editedBusinessMessage);
732
+ } else if (deletedBusinessMessage) {
733
+ debug('Process Update deleted_business_messages %j', deletedBusinessMessage);
734
+ this.emit('deleted_business_messages', deletedBusinessMessage);
735
+ } else if (messageReaction) {
736
+ debug('Process Update message_reaction %j', messageReaction);
737
+ this.emit('message_reaction', messageReaction);
738
+ } else if (messageReactionCount) {
739
+ debug('Process Update message_reaction_count %j', messageReactionCount);
740
+ this.emit('message_reaction_count', messageReactionCount);
741
+ } else if (inlineQuery) {
742
+ debug('Process Update inline_query %j', inlineQuery);
743
+ this.emit('inline_query', inlineQuery);
744
+ } else if (chosenInlineResult) {
745
+ debug('Process Update chosen_inline_result %j', chosenInlineResult);
746
+ this.emit('chosen_inline_result', chosenInlineResult);
747
+ } else if (callbackQuery) {
748
+ debug('Process Update callback_query %j', callbackQuery);
749
+ this.emit('callback_query', callbackQuery);
750
+ } else if (shippingQuery) {
751
+ debug('Process Update shipping_query %j', shippingQuery);
752
+ this.emit('shipping_query', shippingQuery);
753
+ } else if (preCheckoutQuery) {
754
+ debug('Process Update pre_checkout_query %j', preCheckoutQuery);
755
+ this.emit('pre_checkout_query', preCheckoutQuery);
756
+ } else if (poll) {
757
+ debug('Process Update poll %j', poll);
758
+ this.emit('poll', poll);
759
+ } else if (pollAnswer) {
760
+ debug('Process Update poll_answer %j', pollAnswer);
761
+ this.emit('poll_answer', pollAnswer);
762
+ } else if (chatMember) {
763
+ debug('Process Update chat_member %j', chatMember);
764
+ this.emit('chat_member', chatMember);
765
+ } else if (myChatMember) {
766
+ debug('Process Update my_chat_member %j', myChatMember);
767
+ this.emit('my_chat_member', myChatMember);
768
+ } else if (chatJoinRequest) {
769
+ debug('Process Update my_chat_member %j', chatJoinRequest);
770
+ this.emit('chat_join_request', chatJoinRequest);
771
+ } else if (chatBoost) {
772
+ debug('Process Update chat_boost %j', chatBoost);
773
+ this.emit('chat_boost', chatBoost);
774
+ } else if (removedChatBoost) {
775
+ debug('Process Update removed_chat_boost %j', removedChatBoost);
776
+ this.emit('removed_chat_boost', removedChatBoost);
777
+ }
778
+ }
779
+
780
+ /** Start Telegram Bot API methods */
781
+
782
+ /**
783
+ * Use this method to receive incoming updates using long polling.
784
+ * This method has an [older, compatible signature][getUpdates-v0.25.0]
785
+ * that is being deprecated.
786
+ *
787
+ * @param {Object} [options] Additional Telegram query options
788
+ * @return {Promise}
789
+ * @see https://core.telegram.org/bots/api#getupdates
790
+ */
791
+ getUpdates(form = {}) {
792
+ /* The older method signature was getUpdates(timeout, limit, offset).
793
+ * We need to ensure backwards-compatibility while maintaining
794
+ * consistency of the method signatures throughout the library */
795
+ if (typeof form !== 'object') {
796
+ /* eslint-disable no-param-reassign, prefer-rest-params */
797
+ deprecate('The method signature getUpdates(timeout, limit, offset) has been deprecated since v0.25.0');
798
+ form = {
799
+ timeout: arguments[0],
800
+ limit: arguments[1],
801
+ offset: arguments[2]
802
+ };
803
+ /* eslint-enable no-param-reassign, prefer-rest-params */
804
+ }
805
+
806
+ return this._request('getUpdates', { form });
807
+ }
808
+
809
+ /**
810
+ * Specify an url to receive incoming updates via an outgoing webHook.
811
+ * This method has an [older, compatible signature][setWebHook-v0.25.0]
812
+ * that is being deprecated.
813
+ *
814
+ * @param {String} url URL where Telegram will make HTTP Post. Leave empty to
815
+ * delete webHook.
816
+ * @param {Object} [options] Additional Telegram query options
817
+ * @param {String|stream.Stream} [options.certificate] PEM certificate key (public).
818
+ * @param {String} [options.secret_token] Optional secret token to be sent in a header `X-Telegram-Bot-Api-Secret-Token` in every webhook request.
819
+ * @param {Object} [fileOptions] Optional file related meta-data
820
+ * @return {Promise}
821
+ * @see https://core.telegram.org/bots/api#setwebhook
822
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
823
+ */
824
+ setWebHook(url, options = {}, fileOptions = {}) {
825
+ /* The older method signature was setWebHook(url, cert).
826
+ * We need to ensure backwards-compatibility while maintaining
827
+ * consistency of the method signatures throughout the library */
828
+ let cert;
829
+ // Note: 'options' could be an object, if a stream was provided (in place of 'cert')
830
+ if (typeof options !== 'object' || options instanceof stream.Stream) {
831
+ deprecate('The method signature setWebHook(url, cert) has been deprecated since v0.25.0');
832
+ cert = options;
833
+ options = {}; // eslint-disable-line no-param-reassign
834
+ } else {
835
+ cert = options.certificate;
836
+ }
837
+
838
+ const opts = {
839
+ qs: options
840
+ };
841
+ opts.qs.url = url;
842
+
843
+ if (cert) {
844
+ try {
845
+ const sendData = this._formatSendData('certificate', cert, fileOptions);
846
+ opts.formData = sendData[0];
847
+ opts.qs.certificate = sendData[1];
848
+ } catch (ex) {
849
+ return Promise.reject(ex);
850
+ }
851
+ }
852
+
853
+ return this._request('setWebHook', opts);
854
+ }
855
+
856
+ /**
857
+ * Use this method to remove webhook integration if you decide to
858
+ * switch back to getUpdates. Returns True on success.
859
+ * @param {Object} [options] Additional Telegram query options
860
+ * @return {Promise}
861
+ * @see https://core.telegram.org/bots/api#deletewebhook
862
+ */
863
+ deleteWebHook(form = {}) {
864
+ return this._request('deleteWebhook', { form });
865
+ }
866
+
867
+ /**
868
+ * Use this method to get current webhook status.
869
+ * On success, returns a [WebhookInfo](https://core.telegram.org/bots/api#webhookinfo) object.
870
+ * If the bot is using getUpdates, will return an object with the
871
+ * url field empty.
872
+ * @param {Object} [options] Additional Telegram query options
873
+ * @return {Promise}
874
+ * @see https://core.telegram.org/bots/api#getwebhookinfo
875
+ */
876
+ getWebHookInfo(form = {}) {
877
+ return this._request('getWebhookInfo', { form });
878
+ }
879
+
880
+ /**
881
+ * A simple method for testing your bot's authentication token. Requires no parameters.
882
+ *
883
+ * @param {Object} [options] Additional Telegram query options
884
+ * @return {Promise} basic information about the bot in form of a [User](https://core.telegram.org/bots/api#user) object.
885
+ * @see https://core.telegram.org/bots/api#getme
886
+ */
887
+ getMe(form = {}) {
888
+ return this._request('getMe', { form });
889
+ }
890
+
891
+ /**
892
+ * This method log out your bot from the cloud Bot API server before launching the bot locally.
893
+ * You must log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates.
894
+ * After a successful call, you will not be able to log in again using the same token for 10 minutes.
895
+ *
896
+ * @param {Object} [options] Additional Telegram query options
897
+ * @return {Promise} True on success
898
+ * @see https://core.telegram.org/bots/api#logout
899
+ */
900
+ logOut(form = {}) {
901
+ return this._request('logOut', { form });
902
+ }
903
+
904
+ /**
905
+ * This method close the bot instance before moving it from one local server to another.
906
+ * This method will return error 429 in the first 10 minutes after the bot is launched.
907
+ *
908
+ * @param {Object} [options] Additional Telegram query options
909
+ * @return {Promise} True on success
910
+ * @see https://core.telegram.org/bots/api#close
911
+ */
912
+ close(form = {}) {
913
+ return this._request('close', { form });
914
+ }
915
+
916
+ /**
917
+ * Send text message.
918
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
919
+ * @param {String} text Text of the message to be sent
920
+ * @param {Object} [options] Additional Telegram query options
921
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
922
+ * @see https://core.telegram.org/bots/api#sendmessage
923
+ */
924
+ sendMessage(chatId, text, form = {}) {
925
+ form.chat_id = chatId;
926
+ form.text = text;
927
+ return this._request('sendMessage', { form });
928
+ }
929
+
930
+ /**
931
+ * Forward messages of any kind.
932
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
933
+ * or username of the target channel (in the format `@channelusername`)
934
+ * @param {Number|String} fromChatId Unique identifier for the chat where the
935
+ * original message was sent (or channel username in the format `@channelusername`)
936
+ * @param {Number|String} messageId Unique message identifier in the chat specified in fromChatId
937
+ * @param {Object} [options] Additional Telegram query options
938
+ * @return {Promise}
939
+ * @see https://core.telegram.org/bots/api#forwardmessage
940
+ */
941
+ forwardMessage(chatId, fromChatId, messageId, form = {}) {
942
+ form.chat_id = chatId;
943
+ form.from_chat_id = fromChatId;
944
+ form.message_id = messageId;
945
+ return this._request('forwardMessage', { form });
946
+ }
947
+
948
+ /**
949
+ * Use this method to forward multiple messages of any kind.
950
+ * If some of the specified messages can't be found or forwarded, they are skipped.
951
+ *
952
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
953
+ * or username of the target channel (in the format `@channelusername`)
954
+ * @param {Number|String} fromChatId Unique identifier for the chat where the
955
+ * original message was sent (or channel username in the format `@channelusername`)
956
+ * @param {Array<Number|String>} messageIds Identifiers of 1-100 messages in the chat from_chat_id to forward.
957
+ * The identifiers must be specified in a strictly increasing order.
958
+ * @param {Object} [options] Additional Telegram query options
959
+ * @return {Promise} An array of MessageId of the sent messages on success
960
+ * @see https://core.telegram.org/bots/api#forwardmessages
961
+ */
962
+ forwardMessages(chatId, fromChatId, messageIds, form = {}) {
963
+ form.chat_id = chatId;
964
+ form.from_chat_id = fromChatId;
965
+ form.message_ids = messageIds;
966
+ return this._request('forwardMessages', { form });
967
+ }
968
+
969
+ /**
970
+ * Copy messages of any kind. **Service messages and invoice messages can't be copied.**
971
+ * The method is analogous to the method forwardMessages, but the copied message doesn't
972
+ * have a link to the original message.
973
+ * Returns the MessageId of the sent message on success.
974
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
975
+ * @param {Number|String} fromChatId Unique identifier for the chat where the
976
+ * original message was sent
977
+ * @param {Number|String} messageId Unique message identifier
978
+ * @param {Object} [options] Additional Telegram query options
979
+ * @return {Promise} The [MessageId](https://core.telegram.org/bots/api#messageid) of the sent message on success
980
+ * @see https://core.telegram.org/bots/api#copymessage
981
+ */
982
+ copyMessage(chatId, fromChatId, messageId, form = {}) {
983
+ form.chat_id = chatId;
984
+ form.from_chat_id = fromChatId;
985
+ form.message_id = messageId;
986
+ return this._request('copyMessage', { form });
987
+ }
988
+
989
+ /**
990
+ * Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped.
991
+ * Service messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied.
992
+ * Returns the MessageId of the sent message on success.
993
+ * @param {Number|String} chatId Unique identifier for the target chat
994
+ * @param {Number|String} fromChatId Unique identifier for the chat where the
995
+ * original message was sent
996
+ * @param {Array} messageIds Identifiers of 1-100 messages in the chat from_chat_id to copy.
997
+ * The identifiers must be specified in a strictly increasing order.
998
+ * @param {Object} [options] Additional Telegram query options
999
+ * @return {Promise} An array of MessageId of the sent messages
1000
+ * @see https://core.telegram.org/bots/api#copymessages
1001
+ */
1002
+ copyMessages(chatId, fromChatId, messageIds, form = {}) {
1003
+ form.chat_id = chatId;
1004
+ form.from_chat_id = fromChatId;
1005
+ form.message_ids = stringify(messageIds);
1006
+ return this._request('copyMessages', { form });
1007
+ }
1008
+
1009
+ /**
1010
+ * Send photo
1011
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1012
+ * @param {String|stream.Stream|Buffer} photo A file path or a Stream. Can
1013
+ * also be a `file_id` previously uploaded
1014
+ * @param {Object} [options] Additional Telegram query options
1015
+ * @param {Object} [fileOptions] Optional file related meta-data
1016
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1017
+ * @see https://core.telegram.org/bots/api#sendphoto
1018
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1019
+ */
1020
+ sendPhoto(chatId, photo, options = {}, fileOptions = {}) {
1021
+ const opts = {
1022
+ qs: options
1023
+ };
1024
+ opts.qs.chat_id = chatId;
1025
+ try {
1026
+ const sendData = this._formatSendData('photo', photo, fileOptions);
1027
+ opts.formData = sendData[0];
1028
+ opts.qs.photo = sendData[1];
1029
+ } catch (ex) {
1030
+ return Promise.reject(ex);
1031
+ }
1032
+ return this._request('sendPhoto', opts);
1033
+ }
1034
+
1035
+ /**
1036
+ * Send audio
1037
+ *
1038
+ * **Your audio must be in the .MP3 or .M4A format.**
1039
+ *
1040
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1041
+ * @param {String|stream.Stream|Buffer} audio A file path, Stream or Buffer.
1042
+ * Can also be a `file_id` previously uploaded.
1043
+ * @param {Object} [options] Additional Telegram query options
1044
+ * @param {Object} [fileOptions] Optional file related meta-data
1045
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1046
+ * @see https://core.telegram.org/bots/api#sendaudio
1047
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1048
+ */
1049
+ sendAudio(chatId, audio, options = {}, fileOptions = {}) {
1050
+ const opts = {
1051
+ qs: options
1052
+ };
1053
+
1054
+ opts.qs.chat_id = chatId;
1055
+
1056
+ try {
1057
+ const sendData = this._formatSendData('audio', audio, fileOptions);
1058
+ opts.formData = sendData[0];
1059
+ opts.qs.audio = sendData[1];
1060
+ this._fixAddFileThumbnail(options, opts);
1061
+ } catch (ex) {
1062
+ return Promise.reject(ex);
1063
+ }
1064
+
1065
+ return this._request('sendAudio', opts);
1066
+ }
1067
+
1068
+ /**
1069
+ * Send Document
1070
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1071
+ * @param {String|stream.Stream|Buffer} doc A file path, Stream or Buffer.
1072
+ * Can also be a `file_id` previously uploaded.
1073
+ * @param {Object} [options] Additional Telegram query options
1074
+ * @param {Object} [fileOptions] Optional file related meta-data
1075
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1076
+ * @see https://core.telegram.org/bots/api#sendDocument
1077
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1078
+ */
1079
+ sendDocument(chatId, doc, options = {}, fileOptions = {}) {
1080
+ const opts = {
1081
+ qs: options
1082
+ };
1083
+ opts.qs.chat_id = chatId;
1084
+ try {
1085
+ const sendData = this._formatSendData('document', doc, fileOptions);
1086
+ opts.formData = sendData[0];
1087
+ opts.qs.document = sendData[1];
1088
+ this._fixAddFileThumbnail(options, opts);
1089
+ } catch (ex) {
1090
+ return Promise.reject(ex);
1091
+ }
1092
+
1093
+ return this._request('sendDocument', opts);
1094
+ }
1095
+
1096
+ /**
1097
+ * Use this method to send video files, **Telegram clients support mp4 videos** (other formats may be sent as Document).
1098
+ *
1099
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1100
+ * @param {String|stream.Stream|Buffer} video A file path or Stream.
1101
+ * Can also be a `file_id` previously uploaded.
1102
+ * @param {Object} [options] Additional Telegram query options
1103
+ * @param {Object} [fileOptions] Optional file related meta-data
1104
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1105
+ * @see https://core.telegram.org/bots/api#sendvideo
1106
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1107
+ */
1108
+ sendVideo(chatId, video, options = {}, fileOptions = {}) {
1109
+ const opts = {
1110
+ qs: options
1111
+ };
1112
+ opts.qs.chat_id = chatId;
1113
+ try {
1114
+ const sendData = this._formatSendData('video', video, fileOptions);
1115
+ opts.formData = sendData[0];
1116
+ opts.qs.video = sendData[1];
1117
+ this._fixAddFileThumbnail(options, opts);
1118
+ } catch (ex) {
1119
+ return Promise.reject(ex);
1120
+ }
1121
+ return this._request('sendVideo', opts);
1122
+ }
1123
+
1124
+ /**
1125
+ * Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
1126
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1127
+ * @param {String|stream.Stream|Buffer} animation A file path, Stream or Buffer.
1128
+ * Can also be a `file_id` previously uploaded.
1129
+ * @param {Object} [options] Additional Telegram query options
1130
+ * @param {Object} [fileOptions] Optional file related meta-data
1131
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1132
+ * @see https://core.telegram.org/bots/api#sendanimation
1133
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1134
+ */
1135
+ sendAnimation(chatId, animation, options = {}, fileOptions = {}) {
1136
+ const opts = {
1137
+ qs: options
1138
+ };
1139
+ opts.qs.chat_id = chatId;
1140
+ try {
1141
+ const sendData = this._formatSendData('animation', animation, fileOptions);
1142
+ opts.formData = sendData[0];
1143
+ opts.qs.animation = sendData[1];
1144
+ } catch (ex) {
1145
+ return Promise.reject(ex);
1146
+ }
1147
+ return this._request('sendAnimation', opts);
1148
+ }
1149
+
1150
+ /**
1151
+ * Send voice
1152
+ *
1153
+ * **Your audio must be in an .OGG file encoded with OPUS**, or in .MP3 format, or in .M4A format (other formats may be sent as Audio or Document)
1154
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1155
+ * @param {String|stream.Stream|Buffer} voice A file path, Stream or Buffer.
1156
+ * Can also be a `file_id` previously uploaded.
1157
+ * @param {Object} [options] Additional Telegram query options
1158
+ * @param {Object} [fileOptions] Optional file related meta-data
1159
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1160
+ * @see https://core.telegram.org/bots/api#sendvoice
1161
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1162
+ */
1163
+ sendVoice(chatId, voice, options = {}, fileOptions = {}) {
1164
+ const opts = {
1165
+ qs: options
1166
+ };
1167
+ opts.qs.chat_id = chatId;
1168
+ try {
1169
+ const sendData = this._formatSendData('voice', voice, fileOptions);
1170
+ opts.formData = sendData[0];
1171
+ opts.qs.voice = sendData[1];
1172
+ } catch (ex) {
1173
+ return Promise.reject(ex);
1174
+ }
1175
+ return this._request('sendVoice', opts);
1176
+ }
1177
+
1178
+ /**
1179
+ * Use this method to send video messages
1180
+ * Telegram clients support **rounded square MPEG4 videos** of up to 1 minute long.
1181
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1182
+ * @param {String|stream.Stream|Buffer} videoNote A file path or Stream.
1183
+ * Can also be a `file_id` previously uploaded.
1184
+ * @param {Object} [options] Additional Telegram query options
1185
+ * @param {Object} [fileOptions] Optional file related meta-data
1186
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1187
+ * @info The length parameter is actually optional. However, the API (at time of writing) requires you to always provide it until it is fixed.
1188
+ * @see https://core.telegram.org/bots/api#sendvideonote
1189
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1190
+ */
1191
+ sendVideoNote(chatId, videoNote, options = {}, fileOptions = {}) {
1192
+ const opts = {
1193
+ qs: options
1194
+ };
1195
+ opts.qs.chat_id = chatId;
1196
+ try {
1197
+ const sendData = this._formatSendData('video_note', videoNote, fileOptions);
1198
+ opts.formData = sendData[0];
1199
+ opts.qs.video_note = sendData[1];
1200
+ this._fixAddFileThumbnail(options, opts);
1201
+ } catch (ex) {
1202
+ return Promise.reject(ex);
1203
+ }
1204
+ return this._request('sendVideoNote', opts);
1205
+ }
1206
+
1207
+ /**
1208
+ * Use this method to send a group of photos or videos as an album.
1209
+ *
1210
+ * **Documents and audio files can be only grouped in an album with messages of the same type**
1211
+ *
1212
+ * If you wish to [specify file options](https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files),
1213
+ * add a `fileOptions` property to the target input in `media`.
1214
+ *
1215
+ * @param {String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1216
+ * @param {Array} media A JSON-serialized array describing photos and videos to be sent, must include 2–10 items
1217
+ * @param {Object} [options] Additional Telegram query options
1218
+ * @return {Promise} On success, an array of the sent [Messages](https://core.telegram.org/bots/api#message)
1219
+ * is returned.
1220
+ * @see https://core.telegram.org/bots/api#sendmediagroup
1221
+ * @see https://github.com/ZeroBot-net/@zero-bot.net/tg-bot-api/blob/master/doc/usage.md#sending-files
1222
+ */
1223
+ sendMediaGroup(chatId, media, options = {}) {
1224
+ const opts = {
1225
+ qs: options
1226
+ };
1227
+ opts.qs.chat_id = chatId;
1228
+
1229
+ opts.formData = {};
1230
+ const inputMedia = [];
1231
+ let index = 0;
1232
+ for (const input of media) {
1233
+ const payload = Object.assign({}, input);
1234
+ delete payload.media;
1235
+ delete payload.fileOptions;
1236
+ try {
1237
+ const attachName = String(index);
1238
+ const [formData, fileId] = this._formatSendData(attachName, input.media, input.fileOptions);
1239
+ if (formData) {
1240
+ opts.formData[attachName] = formData[attachName];
1241
+ payload.media = `attach://${attachName}`;
1242
+ } else {
1243
+ payload.media = fileId;
1244
+ }
1245
+ } catch (ex) {
1246
+ return Promise.reject(ex);
1247
+ }
1248
+ inputMedia.push(payload);
1249
+ index++;
1250
+ }
1251
+ opts.qs.media = stringify(inputMedia);
1252
+
1253
+ return this._request('sendMediaGroup', opts);
1254
+ }
1255
+
1256
+ /**
1257
+ * Send location.
1258
+ * Use this method to send point on the map.
1259
+ *
1260
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1261
+ * @param {Float} latitude Latitude of location
1262
+ * @param {Float} longitude Longitude of location
1263
+ * @param {Object} [options] Additional Telegram query options
1264
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1265
+ * @see https://core.telegram.org/bots/api#sendlocation
1266
+ */
1267
+ sendLocation(chatId, latitude, longitude, form = {}) {
1268
+ form.chat_id = chatId;
1269
+ form.latitude = latitude;
1270
+ form.longitude = longitude;
1271
+ return this._request('sendLocation', { form });
1272
+ }
1273
+
1274
+ /**
1275
+ * Use this method to edit live location messages sent by
1276
+ * the bot or via the bot (for inline bots).
1277
+ *
1278
+ * A location **can be edited until its live_period expires or editing is explicitly disabled by a call to [stopMessageLiveLocation](https://core.telegram.org/bots/api#stopmessagelivelocation)**
1279
+ *
1280
+ * Note that you must provide one of chat_id, message_id, or
1281
+ * inline_message_id in your request.
1282
+ *
1283
+ * @param {Float} latitude Latitude of location
1284
+ * @param {Float} longitude Longitude of location
1285
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
1286
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned.
1287
+ * @see https://core.telegram.org/bots/api#editmessagelivelocation
1288
+ */
1289
+ editMessageLiveLocation(latitude, longitude, form = {}) {
1290
+ form.latitude = latitude;
1291
+ form.longitude = longitude;
1292
+ return this._request('editMessageLiveLocation', { form });
1293
+ }
1294
+
1295
+ /**
1296
+ * Use this method to stop updating a live location message sent by
1297
+ * the bot or via the bot (for inline bots) before live_period expires.
1298
+ *
1299
+ * Note that you must provide one of chat_id, message_id, or
1300
+ * inline_message_id in your request.
1301
+ *
1302
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
1303
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned.
1304
+ * @see https://core.telegram.org/bots/api#stopmessagelivelocation
1305
+ */
1306
+ stopMessageLiveLocation(form = {}) {
1307
+ return this._request('stopMessageLiveLocation', { form });
1308
+ }
1309
+
1310
+ /**
1311
+ * Send venue.
1312
+ * Use this method to send information about a venue.
1313
+ *
1314
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1315
+ * @param {Float} latitude Latitude of location
1316
+ * @param {Float} longitude Longitude of location
1317
+ * @param {String} title Name of the venue
1318
+ * @param {String} address Address of the venue
1319
+ * @param {Object} [options] Additional Telegram query options
1320
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned.
1321
+ * @see https://core.telegram.org/bots/api#sendvenue
1322
+ */
1323
+ sendVenue(chatId, latitude, longitude, title, address, form = {}) {
1324
+ form.chat_id = chatId;
1325
+ form.latitude = latitude;
1326
+ form.longitude = longitude;
1327
+ form.title = title;
1328
+ form.address = address;
1329
+ return this._request('sendVenue', { form });
1330
+ }
1331
+
1332
+ /**
1333
+ * Send contact.
1334
+ * Use this method to send phone contacts.
1335
+ *
1336
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1337
+ * @param {String} phoneNumber Contact's phone number
1338
+ * @param {String} firstName Contact's first name
1339
+ * @param {Object} [options] Additional Telegram query options
1340
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1341
+ * @see https://core.telegram.org/bots/api#sendcontact
1342
+ */
1343
+ sendContact(chatId, phoneNumber, firstName, form = {}) {
1344
+ form.chat_id = chatId;
1345
+ form.phone_number = phoneNumber;
1346
+ form.first_name = firstName;
1347
+ return this._request('sendContact', { form });
1348
+ }
1349
+
1350
+ /**
1351
+ * Send poll.
1352
+ * Use this method to send a native poll.
1353
+ *
1354
+ * @param {Number|String} chatId Unique identifier for the group/channel
1355
+ * @param {String} question Poll question, 1-300 characters
1356
+ * @param {Array} pollOptions Poll options, between 2-10 options (only 1-100 characters each)
1357
+ * @param {Object} [options] Additional Telegram query options
1358
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1359
+ * @see https://core.telegram.org/bots/api#sendpoll
1360
+ */
1361
+ sendPoll(chatId, question, pollOptions, form = {}) {
1362
+ form.chat_id = chatId;
1363
+ form.question = question;
1364
+ form.options = stringify(pollOptions);
1365
+ return this._request('sendPoll', { form });
1366
+ }
1367
+
1368
+ /**
1369
+ * Send Dice
1370
+ * Use this method to send an animated emoji that will display a random value.
1371
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1372
+ * @param {Object} [options] Additional Telegram query options
1373
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) object is returned
1374
+ * @see https://core.telegram.org/bots/api#senddice
1375
+ */
1376
+ sendDice(chatId, options = {}) {
1377
+ const opts = {
1378
+ qs: options
1379
+ };
1380
+ opts.qs.chat_id = chatId;
1381
+ try {
1382
+ const sendData = this._formatSendData('dice');
1383
+ opts.formData = sendData[0];
1384
+ } catch (ex) {
1385
+ return Promise.reject(ex);
1386
+ }
1387
+ return this._request('sendDice', opts);
1388
+ }
1389
+
1390
+ /**
1391
+ * Send chat action.
1392
+ *
1393
+ * Use this method when you need to tell the user that something is happening on the bot's side.
1394
+ * **The status is set for 5 seconds or less** (when a message arrives from your bot, Telegram clients clear its typing status).
1395
+ *
1396
+ * Action `typing` for [text messages](https://core.telegram.org/bots/api#sendmessage),
1397
+ * `upload_photo` for [photos](https://core.telegram.org/bots/api#sendphoto), `record_video` or `upload_video` for [videos](https://core.telegram.org/bots/api#sendvideo),
1398
+ * `record_voice` or `upload_voice` for [voice notes](https://core.telegram.org/bots/api#sendvoice), `upload_document` for [general files](https://core.telegram.org/bots/api#senddocument),
1399
+ * `choose_sticker` for [stickers](https://core.telegram.org/bots/api#sendsticker), `find_location` for [location data](https://core.telegram.org/bots/api#sendlocation),
1400
+ * `record_video_note` or `upload_video_note` for [video notes](https://core.telegram.org/bots/api#sendvideonote).
1401
+ *
1402
+ *
1403
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1404
+ * @param {String} action Type of action to broadcast.
1405
+ * @param {Object} [options] Additional Telegram query options
1406
+ * @return {Promise} True on success
1407
+ * @see https://core.telegram.org/bots/api#sendchataction
1408
+ */
1409
+ sendChatAction(chatId, action, form = {}) {
1410
+ form.chat_id = chatId;
1411
+ form.action = action;
1412
+ return this._request('sendChatAction', { form });
1413
+ }
1414
+
1415
+ /**
1416
+ * Use this method to change the chosen reactions on a message.
1417
+ * - Service messages can't be reacted to.
1418
+ * - Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel.
1419
+ * - In albums, bots must react to the first message.
1420
+ *
1421
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
1422
+ * @param {Number} messageId Unique identifier of the target message
1423
+ * @param {Object} [options] Additional Telegram query options
1424
+ * @return {Promise<Boolean>} True on success
1425
+ * @see https://core.telegram.org/bots/api#setmessagereaction
1426
+ */
1427
+ setMessageReaction(chatId, messageId, form = {}) {
1428
+ form.chat_id = chatId;
1429
+ form.message_id = messageId;
1430
+ if (form.reaction) {
1431
+ form.reaction = stringify(form.reaction);
1432
+ }
1433
+ return this._request('setMessageReaction', { form });
1434
+ }
1435
+
1436
+ /**
1437
+ * Use this method to get a list of profile pictures for a user.
1438
+ * Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object.
1439
+ * This method has an [older, compatible signature][getUserProfilePhotos-v0.25.0]
1440
+ * that is being deprecated.
1441
+ *
1442
+ * @param {Number} userId Unique identifier of the target user
1443
+ * @param {Object} [options] Additional Telegram query options
1444
+ * @return {Promise} Returns a [UserProfilePhotos](https://core.telegram.org/bots/api#userprofilephotos) object
1445
+ * @see https://core.telegram.org/bots/api#getuserprofilephotos
1446
+ */
1447
+ getUserProfilePhotos(userId, form = {}) {
1448
+ /* The older method signature was getUserProfilePhotos(userId, offset, limit).
1449
+ * We need to ensure backwards-compatibility while maintaining
1450
+ * consistency of the method signatures throughout the library */
1451
+ if (typeof form !== 'object') {
1452
+ /* eslint-disable no-param-reassign, prefer-rest-params */
1453
+ deprecate('The method signature getUserProfilePhotos(userId, offset, limit) has been deprecated since v0.25.0');
1454
+ form = {
1455
+ offset: arguments[1],
1456
+ limit: arguments[2]
1457
+ };
1458
+ /* eslint-enable no-param-reassign, prefer-rest-params */
1459
+ }
1460
+ form.user_id = userId;
1461
+ return this._request('getUserProfilePhotos', { form });
1462
+ }
1463
+
1464
+ /**
1465
+ * Get file.
1466
+ * Use this method to get basic info about a file and prepare it for downloading.
1467
+ *
1468
+ * Attention: **link will be valid for 1 hour.**
1469
+ *
1470
+ * @param {String} fileId File identifier to get info about
1471
+ * @param {Object} [options] Additional Telegram query options
1472
+ * @return {Promise} On success, a [File](https://core.telegram.org/bots/api#file) object is returned
1473
+ * @see https://core.telegram.org/bots/api#getfile
1474
+ */
1475
+ getFile(fileId, form = {}) {
1476
+ form.file_id = fileId;
1477
+ return this._request('getFile', { form });
1478
+ }
1479
+
1480
+ /**
1481
+ * Use this method to ban a user in a group, a supergroup or a channel.
1482
+ * In the case of supergroups and channels, the user will not be able to
1483
+ * return to the chat on their own using invite links, etc., unless unbanned first..
1484
+ *
1485
+ * The **bot must be an administrator in the group, supergroup or a channel** for this to work.
1486
+ *
1487
+ *
1488
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1489
+ * @param {Number} userId Unique identifier of the target user
1490
+ * @param {Object} [options] Additional Telegram query options
1491
+ * @return {Promise} True on success.
1492
+ * @see https://core.telegram.org/bots/api#banchatmember
1493
+ */
1494
+ banChatMember(chatId, userId, form = {}) {
1495
+ form.chat_id = chatId;
1496
+ form.user_id = userId;
1497
+ return this._request('banChatMember', { form });
1498
+ }
1499
+
1500
+ /**
1501
+ * Use this method to unban a previously kicked user in a supergroup.
1502
+ * The user will not return to the group automatically, but will be
1503
+ * able to join via link, etc.
1504
+ *
1505
+ * The **bot must be an administrator** in the supergroup or channel for this to work.
1506
+ *
1507
+ * **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.
1508
+ * 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*
1509
+ *
1510
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1511
+ * @param {Number} userId Unique identifier of the target user
1512
+ * @param {Object} [options] Additional Telegram query options
1513
+ * @return {Promise} True on success
1514
+ * @see https://core.telegram.org/bots/api#unbanchatmember
1515
+ */
1516
+ unbanChatMember(chatId, userId, form = {}) {
1517
+ form.chat_id = chatId;
1518
+ form.user_id = userId;
1519
+ return this._request('unbanChatMember', { form });
1520
+ }
1521
+
1522
+ /**
1523
+ * Use this method to restrict a user in a supergroup.
1524
+ * The bot **must be an administrator in the supergroup** for this to work
1525
+ * and must have the appropriate admin rights. Pass True for all boolean parameters
1526
+ * to lift restrictions from a user. Returns True on success.
1527
+ *
1528
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1529
+ * @param {Number} userId Unique identifier of the target user
1530
+ * @param {Object} [options] Additional Telegram query options
1531
+ * @return {Promise} True on success
1532
+ * @see https://core.telegram.org/bots/api#restrictchatmember
1533
+ */
1534
+ restrictChatMember(chatId, userId, form = {}) {
1535
+ form.chat_id = chatId;
1536
+ form.user_id = userId;
1537
+ return this._request('restrictChatMember', { form });
1538
+ }
1539
+
1540
+ /**
1541
+ * Use this method to promote or demote a user in a supergroup or a channel.
1542
+ * The bot **must be an administrator** in the chat for this to work
1543
+ * and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.
1544
+ *
1545
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1546
+ * @param {Number} userId
1547
+ * @param {Object} [options] Additional Telegram query options
1548
+ * @return {Promise} True on success.
1549
+ * @see https://core.telegram.org/bots/api#promotechatmember
1550
+ */
1551
+ promoteChatMember(chatId, userId, form = {}) {
1552
+ form.chat_id = chatId;
1553
+ form.user_id = userId;
1554
+ return this._request('promoteChatMember', { form });
1555
+ }
1556
+
1557
+ /**
1558
+ * Use this method to set a custom title for an administrator in a supergroup promoted by the bot.
1559
+ *
1560
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1561
+ * @param {Number} userId Unique identifier of the target user
1562
+ * @param {String} customTitle New custom title for the administrator; 0-16 characters, emoji are not allowed
1563
+ * @param {Object} [options] Additional Telegram query options
1564
+ * @return {Promise} True on success
1565
+ * @see https://core.telegram.org/bots/api#setchatadministratorcustomtitle
1566
+ */
1567
+ setChatAdministratorCustomTitle(chatId, userId, customTitle, form = {}) {
1568
+ form.chat_id = chatId;
1569
+ form.user_id = userId;
1570
+ form.custom_title = customTitle;
1571
+ return this._request('setChatAdministratorCustomTitle', { form });
1572
+ }
1573
+
1574
+ /**
1575
+ * Use this method to ban a channel chat in a supergroup or a channel.
1576
+ *
1577
+ * Until the chat is [unbanned](https://core.telegram.org/bots/api#unbanchatsenderchat), the owner of the banned chat won't be able to send messages on behalf of any of their channels.
1578
+ * The bot **must be an administrator in the supergroup or channel** for this to work and must have the appropriate administrator rights
1579
+ *
1580
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1581
+ * @param {Number} senderChatId Unique identifier of the target user
1582
+ * @param {Object} [options] Additional Telegram query options
1583
+ * @return {Promise} True on success.
1584
+ * @see https://core.telegram.org/bots/api#banchatsenderchat
1585
+ */
1586
+ banChatSenderChat(chatId, senderChatId, form = {}) {
1587
+ form.chat_id = chatId;
1588
+ form.sender_chat_id = senderChatId;
1589
+ return this._request('banChatSenderChat', { form });
1590
+ }
1591
+
1592
+ /**
1593
+ * Use this method to unban a previously banned channel chat in a supergroup or channel.
1594
+ *
1595
+ * The bot **must be an administrator** for this to work and must have the appropriate administrator rights.
1596
+ *
1597
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1598
+ * @param {Number} senderChatId Unique identifier of the target user
1599
+ * @param {Object} [options] Additional Telegram query options
1600
+ * @return {Promise} True on success
1601
+ * @see https://core.telegram.org/bots/api#unbanchatsenderchat
1602
+ */
1603
+ unbanChatSenderChat(chatId, senderChatId, form = {}) {
1604
+ form.chat_id = chatId;
1605
+ form.sender_chat_id = senderChatId;
1606
+ return this._request('unbanChatSenderChat', { form });
1607
+ }
1608
+
1609
+ /**
1610
+ * Use this method to set default chat permissions for all members.
1611
+ *
1612
+ * The bot **must be an administrator in the group or a supergroup** for this to
1613
+ * work and **must have the `can_restrict_members` admin rights.**
1614
+ *
1615
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1616
+ * @param {Array} chatPermissions New default chat permissions
1617
+ * @param {Object} [options] Additional Telegram query options
1618
+ * @return {Promise} True on success
1619
+ * @see https://core.telegram.org/bots/api#setchatpermissions
1620
+ */
1621
+ setChatPermissions(chatId, chatPermissions, form = {}) {
1622
+ form.chat_id = chatId;
1623
+ form.permissions = stringify(chatPermissions);
1624
+ return this._request('setChatPermissions', { form });
1625
+ }
1626
+
1627
+ /**
1628
+ * Use this method to generate a new primary invite link for a chat. **Any previously generated primary link is revoked**.
1629
+ *
1630
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate administrator rights.
1631
+ *
1632
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1633
+ * @param {Object} [options] Additional Telegram query options
1634
+ * @return {Promise} Exported invite link as String on success.
1635
+ * @see https://core.telegram.org/bots/api#exportchatinvitelink
1636
+ */
1637
+ exportChatInviteLink(chatId, form = {}) {
1638
+ form.chat_id = chatId;
1639
+ return this._request('exportChatInviteLink', { form });
1640
+ }
1641
+
1642
+ /**
1643
+ * Use this method to create an additional invite link for a chat.
1644
+ *
1645
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1646
+ *
1647
+ * The link generated with this method can be revoked using the method [revokeChatInviteLink](https://core.telegram.org/bots/api#revokechatinvitelink)
1648
+ *
1649
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1650
+ * @param {Object} [options] Additional Telegram query options
1651
+ * @return {Object} The new invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
1652
+ * @see https://core.telegram.org/bots/api#createchatinvitelink
1653
+ */
1654
+ createChatInviteLink(chatId, form = {}) {
1655
+ form.chat_id = chatId;
1656
+ return this._request('createChatInviteLink', { form });
1657
+ }
1658
+
1659
+ /**
1660
+ * Use this method to edit a non-primary invite link created by the bot.
1661
+ *
1662
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1663
+ *
1664
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1665
+ * @param {String} inviteLink Text with the invite link to edit
1666
+ * @param {Object} [options] Additional Telegram query options
1667
+ * @return {Promise} The edited invite link as a [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
1668
+ * @see https://core.telegram.org/bots/api#editchatinvitelink
1669
+ */
1670
+ editChatInviteLink(chatId, inviteLink, form = {}) {
1671
+ form.chat_id = chatId;
1672
+ form.invite_link = inviteLink;
1673
+ return this._request('editChatInviteLink', { form });
1674
+ }
1675
+
1676
+ /**
1677
+ * Use this method to revoke an invite link created by the bot.
1678
+ * Note: If the primary link is revoked, a new link is automatically generated
1679
+ *
1680
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1681
+ *
1682
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1683
+ * @param {String} inviteLink The invite link to revoke
1684
+ * @param {Object} [options] Additional Telegram query options
1685
+ * @return {Promise} The revoked invite link as [ChatInviteLink](https://core.telegram.org/bots/api#chatinvitelink) object
1686
+ * @see https://core.telegram.org/bots/api#revokechatinvitelink
1687
+ */
1688
+ revokeChatInviteLink(chatId, inviteLink, form = {}) {
1689
+ form.chat_id = chatId;
1690
+ form.invite_link = inviteLink;
1691
+ return this._request('revokeChatInviteLink', { form });
1692
+ }
1693
+
1694
+ /**
1695
+ * Use this method to approve a chat join request.
1696
+ *
1697
+ * The bot **must be an administrator in the chat** for this to work and **must have the `can_invite_users` administrator right.**
1698
+ *
1699
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1700
+ * @param {Number} userId Unique identifier of the target user
1701
+ * @param {Object} [options] Additional Telegram query options
1702
+ * @return {Promise} True on success
1703
+ * @see https://core.telegram.org/bots/api#approvechatjoinrequest
1704
+ */
1705
+ approveChatJoinRequest(chatId, userId, form = {}) {
1706
+ form.chat_id = chatId;
1707
+ form.user_id = userId;
1708
+ return this._request('approveChatJoinRequest', { form });
1709
+ }
1710
+
1711
+ /**
1712
+ * Use this method to decline a chat join request.
1713
+ *
1714
+ * The bot **must be an administrator in the chat** for this to work and **must have the `can_invite_users` administrator right**.
1715
+ *
1716
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1717
+ * @param {Number} userId Unique identifier of the target user
1718
+ * @param {Object} [options] Additional Telegram query options
1719
+ * @return {Promise} True on success
1720
+ * @see https://core.telegram.org/bots/api#declinechatjoinrequest
1721
+ */
1722
+ declineChatJoinRequest(chatId, userId, form = {}) {
1723
+ form.chat_id = chatId;
1724
+ form.user_id = userId;
1725
+ return this._request('declineChatJoinRequest', { form });
1726
+ }
1727
+
1728
+ /**
1729
+ * Use this method to set a new profile photo for the chat. **Photos can't be changed for private chats**.
1730
+ *
1731
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1732
+ *
1733
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1734
+ * @param {stream.Stream|Buffer} photo A file path or a Stream.
1735
+ * @param {Object} [options] Additional Telegram query options
1736
+ * @param {Object} [fileOptions] Optional file related meta-data
1737
+ * @return {Promise} True on success
1738
+ * @see https://core.telegram.org/bots/api#setchatphoto
1739
+ */
1740
+ setChatPhoto(chatId, photo, options = {}, fileOptions = {}) {
1741
+ const opts = {
1742
+ qs: options
1743
+ };
1744
+ opts.qs.chat_id = chatId;
1745
+ try {
1746
+ const sendData = this._formatSendData('photo', photo, fileOptions);
1747
+ opts.formData = sendData[0];
1748
+ opts.qs.photo = sendData[1];
1749
+ } catch (ex) {
1750
+ return Promise.reject(ex);
1751
+ }
1752
+ return this._request('setChatPhoto', opts);
1753
+ }
1754
+
1755
+ /**
1756
+ * Use this method to delete a chat photo. **Photos can't be changed for private chats**.
1757
+ *
1758
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1759
+ *
1760
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1761
+ * @param {Object} [options] Additional Telegram query options
1762
+ * @return {Promise} True on success
1763
+ * @see https://core.telegram.org/bots/api#deletechatphoto
1764
+ */
1765
+ deleteChatPhoto(chatId, form = {}) {
1766
+ form.chat_id = chatId;
1767
+ return this._request('deleteChatPhoto', { form });
1768
+ }
1769
+
1770
+ /**
1771
+ * Use this method to change the title of a chat. **Titles can't be changed for private chats**.
1772
+ *
1773
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1774
+ *
1775
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1776
+ * @param {String} title New chat title, 1-255 characters
1777
+ * @param {Object} [options] Additional Telegram query options
1778
+ * @return {Promise} True on success
1779
+ * @see https://core.telegram.org/bots/api#setchattitle
1780
+ */
1781
+ setChatTitle(chatId, title, form = {}) {
1782
+ form.chat_id = chatId;
1783
+ form.title = title;
1784
+ return this._request('setChatTitle', { form });
1785
+ }
1786
+
1787
+ /**
1788
+ * Use this method to change the description of a group, a supergroup or a channel.
1789
+ *
1790
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate admin rights.
1791
+ *
1792
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1793
+ * @param {String} description New chat title, 0-255 characters
1794
+ * @param {Object} [options] Additional Telegram query options
1795
+ * @return {Promise} True on success
1796
+ * @see https://core.telegram.org/bots/api#setchatdescription
1797
+ */
1798
+ setChatDescription(chatId, description, form = {}) {
1799
+ form.chat_id = chatId;
1800
+ form.description = description;
1801
+ return this._request('setChatDescription', { form });
1802
+ }
1803
+
1804
+ /**
1805
+ * Use this method to pin a message in a supergroup.
1806
+ *
1807
+ * 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
1808
+ * right in a supergroup or `can_edit_messages` administrator right in a channel.
1809
+ *
1810
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1811
+ * @param {Number} messageId Identifier of a message to pin
1812
+ * @param {Object} [options] Additional Telegram query options
1813
+ * @return {Promise} True on success
1814
+ * @see https://core.telegram.org/bots/api#pinchatmessage
1815
+ */
1816
+ pinChatMessage(chatId, messageId, form = {}) {
1817
+ form.chat_id = chatId;
1818
+ form.message_id = messageId;
1819
+ return this._request('pinChatMessage', { form });
1820
+ }
1821
+
1822
+ /**
1823
+ * Use this method to remove a message from the list of pinned messages in a chat
1824
+ *
1825
+ * 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
1826
+ * right in a supergroup or `can_edit_messages` administrator right in a channel.
1827
+ *
1828
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1829
+ * @param {Object} [options] Additional Telegram query options
1830
+ * @return {Promise} True on success
1831
+ * @see https://core.telegram.org/bots/api#unpinchatmessage
1832
+ */
1833
+ unpinChatMessage(chatId, form = {}) {
1834
+ form.chat_id = chatId;
1835
+ return this._request('unpinChatMessage', { form });
1836
+ }
1837
+
1838
+ /**
1839
+ * Use this method to clear the list of pinned messages in a chat.
1840
+ *
1841
+ * 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
1842
+ * right in a supergroup or `can_edit_messages` administrator right in a channel.
1843
+ *
1844
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1845
+ * @param {Object} [options] Additional Telegram query options
1846
+ * @return {Promise} True on success
1847
+ * @see https://core.telegram.org/bots/api#unpinallchatmessages
1848
+ */
1849
+ unpinAllChatMessages(chatId, form = {}) {
1850
+ form.chat_id = chatId;
1851
+ return this._request('unpinAllChatMessages', { form });
1852
+ }
1853
+
1854
+ /**
1855
+ * Use this method for your bot to leave a group, supergroup or channel
1856
+ *
1857
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
1858
+ * @param {Object} [options] Additional Telegram query options
1859
+ * @return {Promise} True on success
1860
+ * @see https://core.telegram.org/bots/api#leavechat
1861
+ */
1862
+ leaveChat(chatId, form = {}) {
1863
+ form.chat_id = chatId;
1864
+ return this._request('leaveChat', { form });
1865
+ }
1866
+
1867
+ /**
1868
+ * Use this method to get up to date information about the chat
1869
+ * (current name of the user for one-on-one conversations, current
1870
+ * username of a user, group or channel, etc.).
1871
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`) or channel
1872
+ * @param {Object} [options] Additional Telegram query options
1873
+ * @return {Promise} [ChatFullInfo](https://core.telegram.org/bots/api#chatfullinfo) object on success
1874
+ * @see https://core.telegram.org/bots/api#getchat
1875
+ */
1876
+ getChat(chatId, form = {}) {
1877
+ form.chat_id = chatId;
1878
+ return this._request('getChat', { form });
1879
+ }
1880
+
1881
+ /**
1882
+ * Use this method to get a list of administrators in a chat
1883
+ *
1884
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
1885
+ * @param {Object} [options] Additional Telegram query options
1886
+ * @return {Promise} On success, returns an Array of [ChatMember](https://core.telegram.org/bots/api#chatmember) objects that contains information about all chat administrators except other bots.
1887
+ * If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned
1888
+ * @see https://core.telegram.org/bots/api#getchatadministrators
1889
+ */
1890
+ getChatAdministrators(chatId, form = {}) {
1891
+ form.chat_id = chatId;
1892
+ return this._request('getChatAdministrators', { form });
1893
+ }
1894
+
1895
+ /**
1896
+ * Use this method to get the number of members in a chat.
1897
+ *
1898
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
1899
+ * @param {Object} [options] Additional Telegram query options
1900
+ * @return {Promise} Int on success
1901
+ * @see https://core.telegram.org/bots/api#getchatmembercount
1902
+ */
1903
+ getChatMemberCount(chatId, form = {}) {
1904
+ form.chat_id = chatId;
1905
+ return this._request('getChatMemberCount', { form });
1906
+ }
1907
+
1908
+ /**
1909
+ * Use this method to get information about a member of a chat.
1910
+ *
1911
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup
1912
+ * @param {Number} userId Unique identifier of the target user
1913
+ * @param {Object} [options] Additional Telegram query options
1914
+ * @return {Promise} [ChatMember](https://core.telegram.org/bots/api#chatmember) object on success
1915
+ * @see https://core.telegram.org/bots/api#getchatmember
1916
+ */
1917
+ getChatMember(chatId, userId, form = {}) {
1918
+ form.chat_id = chatId;
1919
+ form.user_id = userId;
1920
+ return this._request('getChatMember', { form });
1921
+ }
1922
+
1923
+ /**
1924
+ * Use this method to set a new group sticker set for a supergroup.
1925
+ *
1926
+ * The bot **must be an administrator in the chat** for this to work and must have the appropriate administrator rights.
1927
+ *
1928
+ * **Note:** Use the field `can_set_sticker_set` optionally returned in [getChat](https://core.telegram.org/bots/api#getchat) requests to check if the bot can use this method.
1929
+ *
1930
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
1931
+ * @param {String} stickerSetName Name of the sticker set to be set as the group sticker set
1932
+ * @param {Object} [options] Additional Telegram query options
1933
+ * @return {Promise} True on success
1934
+ * @see https://core.telegram.org/bots/api#setchatstickerset
1935
+ */
1936
+ setChatStickerSet(chatId, stickerSetName, form = {}) {
1937
+ form.chat_id = chatId;
1938
+ form.sticker_set_name = stickerSetName;
1939
+ return this._request('setChatStickerSet', { form });
1940
+ }
1941
+
1942
+ /**
1943
+ * Use this method to delete a group sticker set from a supergroup.
1944
+ *
1945
+ * Use the field `can_set_sticker_set` optionally returned in [getChat](https://core.telegram.org/bots/api#getchat) requests to check if the bot can use this method.
1946
+ *
1947
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
1948
+ * @param {Object} [options] Additional Telegram query options
1949
+ * @return {Promise} True on success
1950
+ * @see https://core.telegram.org/bots/api#deletechatstickerset
1951
+ */
1952
+ deleteChatStickerSet(chatId, form = {}) {
1953
+ form.chat_id = chatId;
1954
+ return this._request('deleteChatStickerSet', { form });
1955
+ }
1956
+
1957
+ /**
1958
+ * Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user.
1959
+ *
1960
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
1961
+ * @param {Object} [options] Additional Telegram query options
1962
+ * @return {Promise} Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects
1963
+ * @see https://core.telegram.org/bots/api#getforumtopiciconstickers
1964
+ */
1965
+ getForumTopicIconStickers(chatId, form = {}) {
1966
+ form.chat_id = chatId;
1967
+ return this._request('getForumTopicIconStickers', { form });
1968
+ }
1969
+
1970
+ /**
1971
+ * Use this method to create a topic in a forum supergroup chat.
1972
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
1973
+ *
1974
+ * Returns information about the created topic as a [ForumTopic](https://core.telegram.org/bots/api#forumtopic) object.
1975
+ *
1976
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
1977
+ * @param {String} name Topic name, 1-128 characters
1978
+ * @param {Object} [options] Additional Telegram query options
1979
+ * @see https://core.telegram.org/bots/api#createforumtopic
1980
+ */
1981
+ createForumTopic(chatId, name, form = {}) {
1982
+ form.chat_id = chatId;
1983
+ form.name = name;
1984
+ return this._request('createForumTopic', { form });
1985
+ }
1986
+
1987
+ /**
1988
+ * Use this method to edit name and icon of a topic in a forum supergroup chat.
1989
+ * 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.
1990
+ *
1991
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
1992
+ * @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
1993
+ * @param {Object} [options] Additional Telegram query options
1994
+ * @return {Promise} True on success
1995
+ * @see https://core.telegram.org/bots/api#editforumtopic
1996
+ */
1997
+ editForumTopic(chatId, messageThreadId, form = {}) {
1998
+ form.chat_id = chatId;
1999
+ form.message_thread_id = messageThreadId;
2000
+ return this._request('editForumTopic', { form });
2001
+ }
2002
+
2003
+ /**
2004
+ * Use this method to close an open topic in a forum supergroup chat.
2005
+ * 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.
2006
+ *
2007
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2008
+ * @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
2009
+ * @param {Object} [options] Additional Telegram query options
2010
+ * @return {Promise} True on success
2011
+ * @see https://core.telegram.org/bots/api#closeforumtopic
2012
+ */
2013
+ closeForumTopic(chatId, messageThreadId, form = {}) {
2014
+ form.chat_id = chatId;
2015
+ form.message_thread_id = messageThreadId;
2016
+ return this._request('closeForumTopic', { form });
2017
+ }
2018
+
2019
+ /**
2020
+ * Use this method to reopen a closed topic in a forum supergroup chat.
2021
+ * 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.
2022
+ *
2023
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2024
+ * @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
2025
+ * @param {Object} [options] Additional Telegram query options
2026
+ * @return {Promise} True on success
2027
+ * @see https://core.telegram.org/bots/api#reopenforumtopic
2028
+ */
2029
+ reopenForumTopic(chatId, messageThreadId, form = {}) {
2030
+ form.chat_id = chatId;
2031
+ form.message_thread_id = messageThreadId;
2032
+ return this._request('reopenForumTopic', { form });
2033
+ }
2034
+
2035
+ /**
2036
+ * Use this method to delete a forum topic along with all its messages in a forum supergroup chat.
2037
+ * The bot must be an administrator in the chat for this to work and must have the can_delete_messages administrator rights.
2038
+ *
2039
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2040
+ * @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
2041
+ * @param {Object} [options] Additional Telegram query options
2042
+ * @return {Promise} True on success
2043
+ * @see https://core.telegram.org/bots/api#deleteforumtopic
2044
+ */
2045
+ deleteForumTopic(chatId, messageThreadId, form = {}) {
2046
+ form.chat_id = chatId;
2047
+ form.message_thread_id = messageThreadId;
2048
+ return this._request('deleteForumTopic', { form });
2049
+ }
2050
+
2051
+ /**
2052
+ * Use this method to clear the list of pinned messages in a forum topic.
2053
+ * 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.
2054
+ *
2055
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2056
+ * @param {Number} messageThreadId Unique identifier for the target message thread of the forum topic
2057
+ * @param {Object} [options] Additional Telegram query options
2058
+ * @return {Promise} True on success
2059
+ * @see https://core.telegram.org/bots/api#unpinallforumtopicmessages
2060
+ */
2061
+ unpinAllForumTopicMessages(chatId, messageThreadId, form = {}) {
2062
+ form.chat_id = chatId;
2063
+ form.message_thread_id = messageThreadId;
2064
+ return this._request('unpinAllForumTopicMessages', { form });
2065
+ }
2066
+
2067
+ /**
2068
+ * Use this method to edit the name of the 'General' topic in a forum supergroup chat.
2069
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
2070
+ * The topic will be automatically unhidden if it was hidden.
2071
+ *
2072
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2073
+ * @param {String} name New topic name, 1-128 characters
2074
+ * @param {Object} [options] Additional Telegram query options
2075
+ * @return {Promise} True on success
2076
+ * @see https://core.telegram.org/bots/api#editgeneralforumtopic
2077
+ */
2078
+ editGeneralForumTopic(chatId, name, form = {}) {
2079
+ form.chat_id = chatId;
2080
+ form.name = name;
2081
+ return this._request('editGeneralForumTopic', { form });
2082
+ }
2083
+
2084
+ /**
2085
+ * Use this method to close an open 'General' topic in a forum supergroup chat.
2086
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
2087
+ * The topic will be automatically unhidden if it was hidden.
2088
+ *
2089
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2090
+ * @param {Object} [options] Additional Telegram query options
2091
+ * @return {Promise} True on success
2092
+ * @see https://core.telegram.org/bots/api#closegeneralforumtopic
2093
+ */
2094
+ closeGeneralForumTopic(chatId, form = {}) {
2095
+ form.chat_id = chatId;
2096
+ return this._request('closeGeneralForumTopic', { form });
2097
+ }
2098
+
2099
+ /**
2100
+ * Use this method to reopen a closed 'General' topic in a forum supergroup chat.
2101
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
2102
+ * The topic will be automatically unhidden if it was hidden.
2103
+ *
2104
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2105
+ * @param {Object} [options] Additional Telegram query options
2106
+ * @return {Promise} True on success
2107
+ * @see https://core.telegram.org/bots/api#reopengeneralforumtopic
2108
+ */
2109
+ reopenGeneralForumTopic(chatId, form = {}) {
2110
+ form.chat_id = chatId;
2111
+ return this._request('reopenGeneralForumTopic', { form });
2112
+ }
2113
+
2114
+ /**
2115
+ * Use this method to hide the 'General' topic in a forum supergroup chat.
2116
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights.
2117
+ * The topic will be automatically closed if it was open.
2118
+ *
2119
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2120
+ * @param {Object} [options] Additional Telegram query options
2121
+ * @return {Promise} True on success
2122
+ * @see https://core.telegram.org/bots/api#hidegeneralforumtopic
2123
+ */
2124
+ hideGeneralForumTopic(chatId, form = {}) {
2125
+ form.chat_id = chatId;
2126
+ return this._request('hideGeneralForumTopic', { form });
2127
+ }
2128
+
2129
+ /**
2130
+ * Use this method to unhide the 'General' topic in a forum supergroup chat.
2131
+ * The bot must be an administrator in the chat for this to work and must have the can_manage_topics administrator rights
2132
+ *
2133
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2134
+ * @param {Object} [options] Additional Telegram query options
2135
+ * @return {Promise} True on success
2136
+ * @see https://core.telegram.org/bots/api#unhidegeneralforumtopic
2137
+ */
2138
+ unhideGeneralForumTopic(chatId, form = {}) {
2139
+ form.chat_id = chatId;
2140
+ return this._request('unhideGeneralForumTopic', { form });
2141
+ }
2142
+
2143
+ /**
2144
+ * Use this method to clear the list of pinned messages in a General forum topic.
2145
+ * 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.
2146
+ *
2147
+ * @param {Number|String} chatId Unique identifier for the target group or username of the target supergroup (in the format @supergroupusername)
2148
+ * @param {Object} [options] Additional Telegram query options
2149
+ * @return {Promise} True on success
2150
+ * @see https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages
2151
+ */
2152
+ unpinAllGeneralForumTopicMessages(chatId, form = {}) {
2153
+ form.chat_id = chatId;
2154
+ return this._request('unhideGeneralForumTopic', { form });
2155
+ }
2156
+
2157
+ /**
2158
+ * Use this method to send answers to callback queries sent from
2159
+ * [inline keyboards](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating).
2160
+ *
2161
+ * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
2162
+ *
2163
+ * This method has **older, compatible signatures ([1][answerCallbackQuery-v0.27.1])([2][answerCallbackQuery-v0.29.0])**
2164
+ * that are being deprecated.
2165
+ *
2166
+ * @param {String} callbackQueryId Unique identifier for the query to be answered
2167
+ * @param {Object} [options] Additional Telegram query options
2168
+ * @return {Promise} True on success
2169
+ * @see https://core.telegram.org/bots/api#answercallbackquery
2170
+ */
2171
+ answerCallbackQuery(callbackQueryId, form = {}) {
2172
+ /* The older method signature (in/before v0.27.1) was answerCallbackQuery(callbackQueryId, text, showAlert).
2173
+ * We need to ensure backwards-compatibility while maintaining
2174
+ * consistency of the method signatures throughout the library */
2175
+ if (typeof form !== 'object') {
2176
+ /* eslint-disable no-param-reassign, prefer-rest-params */
2177
+ deprecate('The method signature answerCallbackQuery(callbackQueryId, text, showAlert) has been deprecated since v0.27.1');
2178
+ form = {
2179
+ callback_query_id: arguments[0],
2180
+ text: arguments[1],
2181
+ show_alert: arguments[2]
2182
+ };
2183
+ /* eslint-enable no-param-reassign, prefer-rest-params */
2184
+ }
2185
+ /* The older method signature (in/before v0.29.0) was answerCallbackQuery([options]).
2186
+ * We need to ensure backwards-compatibility while maintaining
2187
+ * consistency of the method signatures throughout the library. */
2188
+ if (typeof callbackQueryId === 'object') {
2189
+ /* eslint-disable no-param-reassign, prefer-rest-params */
2190
+ deprecate('The method signature answerCallbackQuery([options]) has been deprecated since v0.29.0');
2191
+ form = callbackQueryId;
2192
+ /* eslint-enable no-param-reassign, prefer-rest-params */
2193
+ } else {
2194
+ form.callback_query_id = callbackQueryId;
2195
+ }
2196
+ return this._request('answerCallbackQuery', { form });
2197
+ }
2198
+
2199
+ /**
2200
+ * Use this method to get the list of boosts added to a chat by a use.
2201
+ * Requires administrator rights in the chat
2202
+ *
2203
+ * @param {Number|String} chatId Unique identifier for the group/channel
2204
+ * @param {Number} user_id Unique identifier of the target user
2205
+ * @param {Object} [options] Additional Telegram query options
2206
+ * @return {Promise} On success, returns a [UserChatBoosts](https://core.telegram.org/bots/api#userchatboosts) object
2207
+ * @see https://core.telegram.org/bots/api#getuserchatboosts
2208
+ */
2209
+ getUserChatBoosts(chatId, pollId, form = {}) {
2210
+ form.chat_id = chatId;
2211
+ form.message_id = pollId;
2212
+ return this._request('getUserChatBoosts', { form });
2213
+ }
2214
+
2215
+ /**
2216
+ * Use this method to get information about the connection of the bot with a business account
2217
+ *
2218
+ * @param {Number|String} businessConnectionId Unique identifier for the group/channel
2219
+ * @param {Object} [options] Additional Telegram query options
2220
+ * @return {Promise} On success, returns [BusinessConnection](https://core.telegram.org/bots/api#businessconnection) object
2221
+ * @see https://core.telegram.org/bots/api#getbusinessconnection
2222
+ */
2223
+ getBusinessConnection(businessConnectionId, form = {}) {
2224
+ form.business_connection_id = businessConnectionId;
2225
+ return this._request('getBusinessConnection', { form });
2226
+ }
2227
+
2228
+ /**
2229
+ * Use this method to change the list of the bot's commands.
2230
+ *
2231
+ * See https://core.telegram.org/bots#commands for more details about bot commands
2232
+ *
2233
+ * @param {Array} commands List of bot commands to be set as the list of the [bot's commands](https://core.telegram.org/bots/api#botcommand). At most 100 commands can be specified.
2234
+ * @param {Object} [options] Additional Telegram query options
2235
+ * @return {Promise} True on success
2236
+ * @see https://core.telegram.org/bots/api#setmycommands
2237
+ */
2238
+ setMyCommands(commands, form = {}) {
2239
+ form.commands = stringify(commands);
2240
+
2241
+ if (form.scope) {
2242
+ form.scope = stringify(form.scope);
2243
+ }
2244
+
2245
+ return this._request('setMyCommands', { form });
2246
+ }
2247
+
2248
+ /**
2249
+ * Use this method to delete the list of the bot's commands for the given scope and user language.
2250
+ *
2251
+ * After deletion, [higher level commands](https://core.telegram.org/bots/api#determining-list-of-commands) will be shown to affected users.
2252
+ *
2253
+ * @param {Object} [options] Additional Telegram query options
2254
+ * @return {Promise} True on success
2255
+ * @see https://core.telegram.org/bots/api#deletemycommands
2256
+ */
2257
+ deleteMyCommands(form = {}) {
2258
+ return this._request('deleteMyCommands', { form });
2259
+ }
2260
+
2261
+ /**
2262
+ * Use this method to get the current list of the bot's commands for the given scope and user language.
2263
+ *
2264
+ * @param {Object} [options] Additional Telegram query options
2265
+ * @return {Promise} Array of [BotCommand](https://core.telegram.org/bots/api#botcommand) on success. If commands aren't set, an empty list is returned.
2266
+ * @see https://core.telegram.org/bots/api#getmycommands
2267
+ */
2268
+ getMyCommands(form = {}) {
2269
+ if (form.scope) {
2270
+ form.scope = stringify(form.scope);
2271
+ }
2272
+ return this._request('getMyCommands', { form });
2273
+ }
2274
+
2275
+ /**
2276
+ * Use this method to change the bot's name.
2277
+ *
2278
+ * @param {Object} [options] Additional Telegram query options
2279
+ * @return {Promise} True on success
2280
+ * @see https://core.telegram.org/bots/api#setmyname
2281
+ */
2282
+ setMyName(form = {}) {
2283
+ return this._request('setMyName', { form });
2284
+ }
2285
+
2286
+ /**
2287
+ * Use this method to get the current bot name for the given user language.
2288
+ *
2289
+ * @param {Object} [options] Additional Telegram query options
2290
+ * @return {Promise} [BotName](https://core.telegram.org/bots/api#botname) on success
2291
+ * @see https://core.telegram.org/bots/api#getmyname
2292
+ */
2293
+ getMyName(form = {}) {
2294
+ return this._request('getMyName', { form });
2295
+ }
2296
+
2297
+ /**
2298
+ * Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty.
2299
+ *
2300
+ * Returns True on success.
2301
+ *
2302
+ * @param {Object} [options] Additional Telegram query options
2303
+ * @return {Promise} True on success
2304
+ * @see https://core.telegram.org/bots/api#setmydescription
2305
+ */
2306
+ setMyDescription(form = {}) {
2307
+ return this._request('setMyDescription', { form });
2308
+ }
2309
+
2310
+ /**
2311
+ * Use this method to get the current bot description for the given user language.
2312
+ *
2313
+ * @param {Object} [options] Additional Telegram query options
2314
+ * @return {Promise} Returns [BotDescription](https://core.telegram.org/bots/api#botdescription) on success.
2315
+ * @see https://core.telegram.org/bots/api#getmydescription
2316
+ */
2317
+ getMyDescription(form = {}) {
2318
+ return this._request('getMyDescription', { form });
2319
+ }
2320
+
2321
+ /**
2322
+ * Use this method to change the bot's short description, which is shown on the bot's profile page
2323
+ * and is sent together with the link when users share the bot.
2324
+ *
2325
+ * @param {Object} [options] Additional Telegram query options
2326
+ * @return {Promise} Returns True on success.
2327
+ * @see https://core.telegram.org/bots/api#setmyshortdescription
2328
+ */
2329
+ setMyShortDescription(form = {}) {
2330
+ return this._request('setMyShortDescription', { form });
2331
+ }
2332
+
2333
+ /**
2334
+ * Use this method to get the current bot short description for the given user language.
2335
+ *
2336
+ * @param {Object} [options] Additional Telegram query options
2337
+ * @return {Promise} Returns [BotShortDescription](https://core.telegram.org/bots/api#botshortdescription) on success.
2338
+ * @see https://core.telegram.org/bots/api#getmyshortdescription
2339
+ */
2340
+ getMyShortDescription(form = {}) {
2341
+ return this._request('getMyShortDescription', { form });
2342
+ }
2343
+
2344
+ /**
2345
+ * Use this method to change the bot's menu button in a private chat, or the default menu button.
2346
+ *
2347
+ * @param {Object} [options] Additional Telegram query options
2348
+ * @return {Promise} True on success
2349
+ * @see https://core.telegram.org/bots/api#setchatmenubutton
2350
+ */
2351
+ setChatMenuButton(form = {}) {
2352
+ return this._request('setChatMenuButton', { form });
2353
+ }
2354
+
2355
+ /**
2356
+ * Use this method to get the current value of the bot's menu button in a private chat, or the default menu button.
2357
+ *
2358
+ * @param {Object} [options] Additional Telegram query options
2359
+ * @return {Promise} [MenuButton](https://core.telegram.org/bots/api#menubutton) on success
2360
+ * @see https://core.telegram.org/bots/api#getchatmenubutton
2361
+ */
2362
+ getChatMenuButton(form = {}) {
2363
+ return this._request('getChatMenuButton', { form });
2364
+ }
2365
+
2366
+ /**
2367
+ * Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels.
2368
+ *
2369
+ * These rights will be suggested to users, but they are are free to modify the list before adding the bot.
2370
+ *
2371
+ * @param {Object} [options] Additional Telegram query options
2372
+ * @return {Promise} True on success
2373
+ * @see https://core.telegram.org/bots/api#getchatmenubutton
2374
+ */
2375
+ setMyDefaultAdministratorRights(form = {}) {
2376
+ return this._request('setMyDefaultAdministratorRights', { form });
2377
+ }
2378
+
2379
+ /**
2380
+ * Use this method to get the current default administrator rights of the bot.
2381
+ *
2382
+ * @param {Object} [options] Additional Telegram query options
2383
+ * @return {Promise} [ChatAdministratorRights](https://core.telegram.org/bots/api#chatadministratorrights) on success
2384
+ * @see https://core.telegram.org/bots/api#getmydefaultadministratorrights
2385
+ */
2386
+ getMyDefaultAdministratorRights(form = {}) {
2387
+ return this._request('getMyDefaultAdministratorRights', { form });
2388
+ }
2389
+
2390
+ /**
2391
+ * Use this method to edit text or [game](https://core.telegram.org/bots/api#games) messages sent by the bot or via the bot (for inline bots).
2392
+ *
2393
+ * Note: that **you must provide one of chat_id, message_id, or inline_message_id** in your request.
2394
+ *
2395
+ * @param {String} text New text of the message
2396
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
2397
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
2398
+ * @see https://core.telegram.org/bots/api#editmessagetext
2399
+ */
2400
+ editMessageText(text, form = {}) {
2401
+ form.text = text;
2402
+ return this._request('editMessageText', { form });
2403
+ }
2404
+
2405
+ /**
2406
+ * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
2407
+ *
2408
+ * Note: You **must provide one of chat_id, message_id, or inline_message_id** in your request.
2409
+ *
2410
+ * @param {String} caption New caption of the message
2411
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
2412
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
2413
+ * @see https://core.telegram.org/bots/api#editmessagecaption
2414
+ */
2415
+ editMessageCaption(caption, form = {}) {
2416
+ form.caption = caption;
2417
+ return this._request('editMessageCaption', { form });
2418
+ }
2419
+
2420
+ /**
2421
+ * Use this method to edit animation, audio, document, photo, or video messages.
2422
+ *
2423
+ * If a message is a part of a message album, then it can be edited only to a photo or a video.
2424
+ *
2425
+ * Otherwise, message type can be changed arbitrarily. When inline message is edited, new file can't be uploaded.
2426
+ * Use previously uploaded file via its file_id or specify a URL.
2427
+ *
2428
+ * Note: You **must provide one of chat_id, message_id, or inline_message_id** in your request.
2429
+ *
2430
+ * @param {Object} media A JSON-serialized object for a new media content of the message
2431
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
2432
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
2433
+ * @see https://core.telegram.org/bots/api#editmessagemedia
2434
+ */
2435
+ editMessageMedia(media, form = {}) {
2436
+ const regexAttach = /attach:\/\/.+/;
2437
+
2438
+ if (typeof media.media === 'string' && regexAttach.test(media.media)) {
2439
+ const opts = {
2440
+ qs: form
2441
+ };
2442
+
2443
+ opts.formData = {};
2444
+
2445
+ const payload = Object.assign({}, media);
2446
+ delete payload.media;
2447
+
2448
+ try {
2449
+ const attachName = String(0);
2450
+ const [formData] = this._formatSendData(attachName, media.media.replace('attach://', ''), media.fileOptions);
2451
+
2452
+ if (formData) {
2453
+ opts.formData[attachName] = formData[attachName];
2454
+ payload.media = `attach://${attachName}`;
2455
+ } else {
2456
+ throw new errors.FatalError(`Failed to process the replacement action for your ${media.type}`);
2457
+ }
2458
+ } catch (ex) {
2459
+ return Promise.reject(ex);
2460
+ }
2461
+
2462
+ opts.qs.media = stringify(payload);
2463
+
2464
+ return this._request('editMessageMedia', opts);
2465
+ }
2466
+
2467
+ form.media = stringify(media);
2468
+
2469
+ return this._request('editMessageMedia', { form });
2470
+ }
2471
+
2472
+ /**
2473
+ * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
2474
+ *
2475
+ * Note: You **must provide one of chat_id, message_id, or inline_message_id** in your request.
2476
+ *
2477
+ * @param {Object} replyMarkup A JSON-serialized object for an inline keyboard.
2478
+ * @param {Object} [options] Additional Telegram query options (provide either one of chat_id, message_id, or inline_message_id here)
2479
+ * @return {Promise} On success, if the edited message is not an inline message, the edited [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
2480
+ * @see https://core.telegram.org/bots/api#editmessagetext
2481
+ */
2482
+ editMessageReplyMarkup(replyMarkup, form = {}) {
2483
+ form.reply_markup = replyMarkup;
2484
+ return this._request('editMessageReplyMarkup', { form });
2485
+ }
2486
+
2487
+ /**
2488
+ * Use this method to stop a poll which was sent by the bot.
2489
+ *
2490
+ * @param {Number|String} chatId Unique identifier for the group/channel
2491
+ * @param {Number} pollId Identifier of the original message with the poll
2492
+ * @param {Object} [options] Additional Telegram query options
2493
+ * @return {Promise} On success, the stopped [Poll](https://core.telegram.org/bots/api#poll) is returned
2494
+ * @see https://core.telegram.org/bots/api#stoppoll
2495
+ */
2496
+ stopPoll(chatId, pollId, form = {}) {
2497
+ form.chat_id = chatId;
2498
+ form.message_id = pollId;
2499
+ return this._request('stopPoll', { form });
2500
+ }
2501
+
2502
+ /**
2503
+ * Use this method to send static .WEBP, [animated](https://telegram.org/blog/animated-stickers) .TGS,
2504
+ * or [video](https://telegram.org/blog/video-stickers-better-reactions) .WEBM stickers.
2505
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
2506
+ * @param {String|stream.Stream|Buffer} sticker A file path, Stream or Buffer.
2507
+ * Can also be a `file_id` previously uploaded. Stickers are WebP format files.
2508
+ * @param {Object} [options] Additional Telegram query options
2509
+ * @param {Object} [fileOptions] Optional file related meta-data
2510
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
2511
+ * @see https://core.telegram.org/bots/api#sendsticker
2512
+ */
2513
+ sendSticker(chatId, sticker, options = {}, fileOptions = {}) {
2514
+ const opts = {
2515
+ qs: options
2516
+ };
2517
+ opts.qs.chat_id = chatId;
2518
+ try {
2519
+ const sendData = this._formatSendData('sticker', sticker, fileOptions);
2520
+ opts.formData = sendData[0];
2521
+ opts.qs.sticker = sendData[1];
2522
+ } catch (ex) {
2523
+ return Promise.reject(ex);
2524
+ }
2525
+ return this._request('sendSticker', opts);
2526
+ }
2527
+
2528
+ /**
2529
+ * Use this method to get a sticker set.
2530
+ *
2531
+ * @param {String} name Name of the sticker set
2532
+ * @param {Object} [options] Additional Telegram query options
2533
+ * @return {Promise} On success, a [StickerSet](https://core.telegram.org/bots/api#stickerset) object is returned
2534
+ * @see https://core.telegram.org/bots/api#getstickerset
2535
+ */
2536
+ getStickerSet(name, form = {}) {
2537
+ form.name = name;
2538
+ return this._request('getStickerSet', { form });
2539
+ }
2540
+
2541
+ /**
2542
+ * Use this method to get information about custom emoji stickers by their identifiers.
2543
+ *
2544
+ * @param {Array} custom_emoji_ids List of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.
2545
+ * @param {Object} [options] Additional Telegram query options
2546
+ * @return {Promise} Array of [Sticker](https://core.telegram.org/bots/api#sticker) objects.
2547
+ * @see https://core.telegram.org/bots/api#getcustomemojistickers
2548
+ */
2549
+ getCustomEmojiStickers(customEmojiIds, form = {}) {
2550
+ form.custom_emoji_ids = stringify(customEmojiIds);
2551
+ return this._request('getCustomEmojiStickers', { form });
2552
+ }
2553
+
2554
+ /**
2555
+ * Use this method to upload a file with a sticker for later use in *createNewStickerSet* and *addStickerToSet* methods (can be used multiple
2556
+ * times).
2557
+ *
2558
+ * @param {Number} userId User identifier of sticker file owner
2559
+ * @param {String|stream.Stream|Buffer} sticker A file path or a Stream with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. Can also be a `file_id` previously uploaded.
2560
+ * @param {String} stickerFormat Allow values: `static`, `animated` or `video`
2561
+ * @param {Object} [options] Additional Telegram query options
2562
+ * @param {Object} [fileOptions] Optional file related meta-data
2563
+ * @return {Promise} On success, a [File](https://core.telegram.org/bots/api#file) object is returned
2564
+ * @see https://core.telegram.org/bots/api#uploadstickerfile
2565
+ */
2566
+ uploadStickerFile(userId, sticker, stickerFormat = 'static', options = {}, fileOptions = {}) {
2567
+ const opts = {
2568
+ qs: options
2569
+ };
2570
+ opts.qs.user_id = userId;
2571
+ opts.qs.sticker_format = stickerFormat;
2572
+
2573
+ try {
2574
+ const sendData = this._formatSendData('sticker', sticker, fileOptions);
2575
+ opts.formData = sendData[0];
2576
+ opts.qs.sticker = sendData[1];
2577
+ } catch (ex) {
2578
+ return Promise.reject(ex);
2579
+ }
2580
+ return this._request('uploadStickerFile', opts);
2581
+ }
2582
+
2583
+ /**
2584
+ * Use this method to create new sticker set owned by a user.
2585
+ *
2586
+ * The bot will be able to edit the created sticker set.
2587
+ *
2588
+ * You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
2589
+ *
2590
+ * @param {Number} userId User identifier of created sticker set owner
2591
+ * @param {String} name Short name of sticker set, to be used in `t.me/addstickers/` URLs (e.g., *"animals"*). Can contain only english letters, digits and underscores.
2592
+ * Must begin with a letter, can't contain consecutive underscores and must end in `"_by_<bot_username>"`. `<bot_username>` is case insensitive. 1-64 characters.
2593
+ * @param {String} title Sticker set title, 1-64 characters
2594
+ * @param {String|stream.Stream|Buffer} pngSticker Png image with the sticker, must be up to 512 kilobytes in size,
2595
+ * dimensions must not exceed 512px, and either width or height must be exactly 512px.
2596
+ * @param {String} emojis One or more emoji corresponding to the sticker
2597
+ * @param {Object} [options] Additional Telegram query options
2598
+ * @param {Object} [fileOptions] Optional file related meta-data
2599
+ * @return {Promise} True on success
2600
+ * @see https://core.telegram.org/bots/api#createnewstickerset
2601
+ */
2602
+ createNewStickerSet(userId, name, title, pngSticker, emojis, options = {}, fileOptions = {}) {
2603
+ const opts = {
2604
+ qs: options
2605
+ };
2606
+ opts.qs.user_id = userId;
2607
+ opts.qs.name = name;
2608
+ opts.qs.title = title;
2609
+ opts.qs.emojis = emojis;
2610
+ opts.qs.mask_position = stringify(options.mask_position);
2611
+ try {
2612
+ const sendData = this._formatSendData('png_sticker', pngSticker, fileOptions);
2613
+ opts.formData = sendData[0];
2614
+ opts.qs.png_sticker = sendData[1];
2615
+ } catch (ex) {
2616
+ return Promise.reject(ex);
2617
+ }
2618
+ return this._request('createNewStickerSet', opts);
2619
+ }
2620
+
2621
+ /**
2622
+ * Use this method to add a new sticker to a set created by the bot.
2623
+ *
2624
+ * You must use exactly one of the fields *png_sticker*, *tgs_sticker*, or *webm_sticker*
2625
+ *
2626
+ * Animated stickers can be added to animated sticker sets and only to them
2627
+ *
2628
+ * Note:
2629
+ * - Emoji sticker sets can have up to 200 sticker
2630
+ * - Static or Animated sticker sets can have up to 120 stickers
2631
+ *
2632
+ * @param {Number} userId User identifier of sticker set owner
2633
+ * @param {String} name Sticker set name
2634
+ * @param {String|stream.Stream|Buffer} sticker Png image with the sticker (must be up to 512 kilobytes in size,
2635
+ * dimensions must not exceed 512px, and either width or height must be exactly 512px, [TGS animation](https://core.telegram.org/stickers#animated-sticker-requirements)
2636
+ * with the sticker or [WEBM video](https://core.telegram.org/stickers#video-sticker-requirements) with the sticker.
2637
+ * @param {String} emojis One or more emoji corresponding to the sticker
2638
+ * @param {String} stickerType Allow values: `png_sticker`, `tgs_sticker`, or `webm_sticker`.
2639
+ * @param {Object} [options] Additional Telegram query options
2640
+ * @param {Object} [fileOptions] Optional file related meta-data
2641
+ * @return {Promise} True on success
2642
+ * @see https://core.telegram.org/bots/api#addstickertoset
2643
+ */
2644
+ addStickerToSet(userId, name, sticker, emojis, stickerType = 'png_sticker', options = {}, fileOptions = {}) {
2645
+ const opts = {
2646
+ qs: options
2647
+ };
2648
+ opts.qs.user_id = userId;
2649
+ opts.qs.name = name;
2650
+ opts.qs.emojis = emojis;
2651
+ opts.qs.mask_position = stringify(options.mask_position);
2652
+
2653
+ if (typeof stickerType !== 'string' || ['png_sticker', 'tgs_sticker', 'webm_sticker'].indexOf(stickerType) === -1) {
2654
+ return Promise.reject(new Error('stickerType must be a string and the allow types is: png_sticker, tgs_sticker, webm_sticker'));
2655
+ }
2656
+
2657
+ try {
2658
+ const sendData = this._formatSendData(stickerType, sticker, fileOptions);
2659
+ opts.formData = sendData[0];
2660
+ opts.qs[stickerType] = sendData[1];
2661
+ } catch (ex) {
2662
+ return Promise.reject(ex);
2663
+ }
2664
+ return this._request('addStickerToSet', opts);
2665
+ }
2666
+
2667
+ /**
2668
+ * Use this method to move a sticker in a set created by the bot to a specific position.
2669
+ *
2670
+ * @param {String} sticker File identifier of the sticker
2671
+ * @param {Number} position New sticker position in the set, zero-based
2672
+ * @param {Object} [options] Additional Telegram query options
2673
+ * @return {Promise} True on success
2674
+ * @see https://core.telegram.org/bots/api#setstickerpositioninset
2675
+ */
2676
+ setStickerPositionInSet(sticker, position, form = {}) {
2677
+ form.sticker = sticker;
2678
+ form.position = position;
2679
+ return this._request('setStickerPositionInSet', { form });
2680
+ }
2681
+
2682
+ /**
2683
+ * Use this method to delete a sticker from a set created by the bot.
2684
+ *
2685
+ * @param {String} sticker File identifier of the sticker
2686
+ * @param {Object} [options] Additional Telegram query options
2687
+ * @return {Promise} True on success
2688
+ * @see https://core.telegram.org/bots/api#deletestickerfromset
2689
+ * @todo Add tests for this method!
2690
+ */
2691
+ deleteStickerFromSet(sticker, form = {}) {
2692
+ form.sticker = sticker;
2693
+ return this._request('deleteStickerFromSet', { form });
2694
+ }
2695
+
2696
+ /**
2697
+ * Use this method to replace an existing sticker in a sticker set with a new one
2698
+ *
2699
+ * @param {Number} user_id User identifier of the sticker set owner
2700
+ * @param {String} name Sticker set name
2701
+ * @param {String} sticker File identifier of the sticker
2702
+ * @param {Object} [options] Additional Telegram query options
2703
+ * @return {Promise} True on success
2704
+ * @see https://core.telegram.org/bots/api#replacestickerinset
2705
+ * @todo Add tests for this method!
2706
+ */
2707
+ replaceStickerInSet(userId, name, oldSticker, form = {}) {
2708
+ form.user_id = userId;
2709
+ form.name = name;
2710
+ form.old_sticker = oldSticker;
2711
+ return this._request('deleteStickerFromSet', { form });
2712
+ }
2713
+
2714
+ /**
2715
+ * Use this method to change the list of emoji assigned to a regular or custom emoji sticker.
2716
+ *
2717
+ * The sticker must belong to a sticker set created by the bot.
2718
+ *
2719
+ * @param {String} sticker File identifier of the sticker
2720
+ * @param { Array } emojiList A JSON-serialized list of 1-20 emoji associated with the sticker
2721
+ * @param {Object} [options] Additional Telegram query options
2722
+ * @return {Promise} True on success
2723
+ * @see https://core.telegram.org/bots/api#setstickeremojilist
2724
+ */
2725
+ setStickerEmojiList(sticker, emojiList, form = {}) {
2726
+ form.sticker = sticker;
2727
+ form.emoji_list = stringify(emojiList);
2728
+ return this._request('setStickerEmojiList', { form });
2729
+ }
2730
+
2731
+ /**
2732
+ * Use this method to change the list of emoji assigned to a `regular` or `custom emoji` sticker.
2733
+ *
2734
+ * The sticker must belong to a sticker set created by the bot.
2735
+ *
2736
+ * @param {String} sticker File identifier of the sticker
2737
+ * @param {Object} [options] Additional Telegram query options
2738
+ * @return {Promise} True on success
2739
+ * @see https://core.telegram.org/bots/api#setstickerkeywords
2740
+ */
2741
+ setStickerKeywords(sticker, form = {}) {
2742
+ form.sticker = sticker;
2743
+ if (form.keywords) {
2744
+ form.keywords = stringify(form.keywords);
2745
+ }
2746
+ return this._request('setStickerKeywords', { form });
2747
+ }
2748
+
2749
+ /**
2750
+ * Use this method to change the [mask position](https://core.telegram.org/bots/api#maskposition) of a mask sticker.
2751
+ *
2752
+ * The sticker must belong to a sticker set created by the bot.
2753
+ *
2754
+ * @param {String} sticker File identifier of the sticker
2755
+ * @param {Object} [options] Additional Telegram query options
2756
+ * @return {Promise} True on success
2757
+ * @see https://core.telegram.org/bots/api#setstickermaskposition
2758
+ */
2759
+ setStickerMaskPosition(sticker, form = {}) {
2760
+ form.sticker = sticker;
2761
+ if (form.mask_position) {
2762
+ form.mask_position = stringify(form.mask_position);
2763
+ }
2764
+ return this._request('setStickerMaskPosition', { form });
2765
+ }
2766
+
2767
+ /**
2768
+ * Use this method to set the title of a created sticker set.
2769
+ *
2770
+ * The sticker must belong to a sticker set created by the bot.
2771
+ *
2772
+ * @param {String} name Sticker set name
2773
+ * @param {String} title Sticker set title, 1-64 characters
2774
+ * @param {Object} [options] Additional Telegram query options
2775
+ * @return {Promise} True on success
2776
+ * @see https://core.telegram.org/bots/api#setstickersettitle
2777
+ */
2778
+ setStickerSetTitle(name, title, form = {}) {
2779
+ form.name = name;
2780
+ form.title = title;
2781
+ return this._request('setStickerSetTitle', { form });
2782
+ }
2783
+
2784
+ /**
2785
+ * Use this method to add a thumb to a set created by the bot.
2786
+ *
2787
+ * Animated thumbnails can be set for animated sticker sets only. Video thumbnails can be set only for video sticker sets only
2788
+ *
2789
+ * @param {Number} userId User identifier of sticker set owner
2790
+ * @param {String} name Sticker set name
2791
+ * @param {String|stream.Stream|Buffer} thumbnail A .WEBP or .PNG image with the thumbnail,
2792
+ * must be up to 128 kilobytes in size and have width and height exactly 100px,
2793
+ * a TGS animation with the thumbnail up to 32 kilobytes in size or a WEBM video with the thumbnail up to 32 kilobytes in size.
2794
+ *
2795
+ * Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram
2796
+ * to get a file from the Internet, or upload a new one. Animated sticker set thumbnails can't be uploaded via HTTP URL.
2797
+ * @param {Object} [options] Additional Telegram query options
2798
+ * @param {Object} [fileOptions] Optional file related meta-data
2799
+ * @return {Promise} True on success
2800
+ * @see https://core.telegram.org/bots/api#setstickersetthumbnail
2801
+ */
2802
+ setStickerSetThumbnail(userId, name, thumbnail, options = {}, fileOptions = {}) {
2803
+ const opts = {
2804
+ qs: options
2805
+ };
2806
+ opts.qs.user_id = userId;
2807
+ opts.qs.name = name;
2808
+ opts.qs.mask_position = stringify(options.mask_position);
2809
+ try {
2810
+ const sendData = this._formatSendData('thumbnail', thumbnail, fileOptions);
2811
+ opts.formData = sendData[0];
2812
+ opts.qs.thumbnail = sendData[1];
2813
+ } catch (ex) {
2814
+ return Promise.reject(ex);
2815
+ }
2816
+ return this._request('setStickerSetThumbnail', opts);
2817
+ }
2818
+
2819
+ /**
2820
+ * Use this method to set the thumbnail of a custom emoji sticker set.
2821
+ *
2822
+ * The sticker must belong to a sticker set created by the bot.
2823
+ *
2824
+ * @param {String} name Sticker set name
2825
+ * @param {Object} [options] Additional Telegram query options
2826
+ * @return {Promise} True on success
2827
+ * @see https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail
2828
+ */
2829
+ setCustomEmojiStickerSetThumbnail(name, form = {}) {
2830
+ form.name = name;
2831
+ return this._request('setCustomEmojiStickerSetThumbnail', { form });
2832
+ }
2833
+
2834
+ /**
2835
+ * Use this method to delete a sticker set that was created by the bot.
2836
+ *
2837
+ * The sticker must belong to a sticker set created by the bot.
2838
+ *
2839
+ * @param {String} name Sticker set name
2840
+ * @param {Object} [options] Additional Telegram query options
2841
+ * @return {Promise} True on success
2842
+ * @see https://core.telegram.org/bots/api#deletestickerset
2843
+ */
2844
+ deleteStickerSet(name, form = {}) {
2845
+ form.name = name;
2846
+ return this._request('deleteStickerSet', { form });
2847
+ }
2848
+
2849
+ /**
2850
+ * Send answers to an inline query.
2851
+ *
2852
+ * Note: No more than 50 results per query are allowed.
2853
+ *
2854
+ * @param {String} inlineQueryId Unique identifier of the query
2855
+ * @param {InlineQueryResult[]} results An array of results for the inline query
2856
+ * @param {Object} [options] Additional Telegram query options
2857
+ * @return {Promise} On success, True is returned
2858
+ * @see https://core.telegram.org/bots/api#answerinlinequery
2859
+ */
2860
+ answerInlineQuery(inlineQueryId, results, form = {}) {
2861
+ form.inline_query_id = inlineQueryId;
2862
+ form.results = stringify(results);
2863
+ return this._request('answerInlineQuery', { form });
2864
+ }
2865
+
2866
+ /**
2867
+ * Use this method to set the result of an interaction with a [Web App](https://core.telegram.org/bots/webapps)
2868
+ * and send a corresponding message on behalf of the user to the chat from which the query originated.
2869
+ *
2870
+ * @param {String} webAppQueryId Unique identifier for the query to be answered
2871
+ * @param {InlineQueryResult} result object that represents one result of an inline query
2872
+ * @param {Object} [options] Additional Telegram query options
2873
+ * @return {Promise} On success, a [SentWebAppMessage](https://core.telegram.org/bots/api#sentwebappmessage) object is returned
2874
+ * @see https://core.telegram.org/bots/api#answerwebappquery
2875
+ */
2876
+ answerWebAppQuery(webAppQueryId, result, form = {}) {
2877
+ form.web_app_query_id = webAppQueryId;
2878
+ form.result = stringify(result);
2879
+ return this._request('answerWebAppQuery', { form });
2880
+ }
2881
+
2882
+ /**
2883
+ * Use this method to send an invoice.
2884
+ *
2885
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
2886
+ * @param {String} title Product name, 1-32 characters
2887
+ * @param {String} description Product description, 1-255 characters
2888
+ * @param {String} payload Bot defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.
2889
+ * @param {String} providerToken Payments provider token, obtained via `@BotFather`
2890
+ * @param {String} currency Three-letter ISO 4217 currency code
2891
+ * @param {Array} prices Breakdown of prices
2892
+ * @param {Object} [options] Additional Telegram query options
2893
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
2894
+ * @see https://core.telegram.org/bots/api#sendinvoice
2895
+ */
2896
+ sendInvoice(chatId, title, description, payload, providerToken, currency, prices, form = {}) {
2897
+ form.chat_id = chatId;
2898
+ form.title = title;
2899
+ form.description = description;
2900
+ form.payload = payload;
2901
+ form.provider_token = providerToken;
2902
+ form.currency = currency;
2903
+ form.prices = stringify(prices);
2904
+ form.provider_data = stringify(form.provider_data);
2905
+ if (form.suggested_tip_amounts) {
2906
+ form.suggested_tip_amounts = stringify(form.suggested_tip_amounts);
2907
+ }
2908
+ return this._request('sendInvoice', { form });
2909
+ }
2910
+
2911
+ /**
2912
+ * Use this method to create a link for an invoice.
2913
+ *
2914
+ * @param {String} title Product name, 1-32 characters
2915
+ * @param {String} description Product description, 1-255 characters
2916
+ * @param {String} payload Bot defined invoice payload
2917
+ * @param {String} providerToken Payment provider token
2918
+ * @param {String} currency Three-letter ISO 4217 currency code
2919
+ * @param {Array} prices Breakdown of prices
2920
+ * @param {Object} [options] Additional Telegram query options
2921
+ * @returns {Promise} The created invoice link as String on success.
2922
+ * @see https://core.telegram.org/bots/api#createinvoicelink
2923
+ */
2924
+ createInvoiceLink(title, description, payload, providerToken, currency, prices, form = {}) {
2925
+ form.title = title;
2926
+ form.description = description;
2927
+ form.payload = payload;
2928
+ form.provider_token = providerToken;
2929
+ form.currency = currency;
2930
+ form.prices = stringify(prices);
2931
+ return this._request('createInvoiceLink', { form });
2932
+ }
2933
+
2934
+ /**
2935
+ * Use this method to reply to shipping queries.
2936
+ *
2937
+ * If you sent an invoice requesting a shipping address and the parameter is_flexible was specified,
2938
+ * the Bot API will send an [Update](https://core.telegram.org/bots/api#update) with a shipping_query field to the bot
2939
+ *
2940
+ * @param {String} shippingQueryId Unique identifier for the query to be answered
2941
+ * @param {Boolean} ok Specify if delivery of the product is possible
2942
+ * @param {Object} [options] Additional Telegram query options
2943
+ * @return {Promise} On success, True is returned
2944
+ * @see https://core.telegram.org/bots/api#answershippingquery
2945
+ */
2946
+ answerShippingQuery(shippingQueryId, ok, form = {}) {
2947
+ form.shipping_query_id = shippingQueryId;
2948
+ form.ok = ok;
2949
+ form.shipping_options = stringify(form.shipping_options);
2950
+ return this._request('answerShippingQuery', { form });
2951
+ }
2952
+
2953
+ /**
2954
+ * Use this method to respond to such pre-checkout queries
2955
+ *
2956
+ * Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of
2957
+ * an [Update](https://core.telegram.org/bots/api#update) with the field *pre_checkout_query*.
2958
+ *
2959
+ * **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent.
2960
+ *
2961
+ * @param {String} preCheckoutQueryId Unique identifier for the query to be answered
2962
+ * @param {Boolean} ok Specify if every order details are ok
2963
+ * @param {Object} [options] Additional Telegram query options
2964
+ * @return {Promise} On success, True is returned
2965
+ * @see https://core.telegram.org/bots/api#answerprecheckoutquery
2966
+ */
2967
+ answerPreCheckoutQuery(preCheckoutQueryId, ok, form = {}) {
2968
+ form.pre_checkout_query_id = preCheckoutQueryId;
2969
+ form.ok = ok;
2970
+ return this._request('answerPreCheckoutQuery', { form });
2971
+ }
2972
+
2973
+ /**
2974
+ * Use this method to send a game.
2975
+ *
2976
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format `@channelusername`)
2977
+ * @param {String} gameShortName name of the game to be sent. Set up your games via `@BotFather`.
2978
+ * @param {Object} [options] Additional Telegram query options
2979
+ * @return {Promise} On success, the sent [Message](https://core.telegram.org/bots/api#message) is returned
2980
+ * @see https://core.telegram.org/bots/api#sendgame
2981
+ */
2982
+ sendGame(chatId, gameShortName, form = {}) {
2983
+ form.chat_id = chatId;
2984
+ form.game_short_name = gameShortName;
2985
+ return this._request('sendGame', { form });
2986
+ }
2987
+
2988
+ /**
2989
+ * Use this method to set the score of the specified user in a game message.
2990
+ *
2991
+ * @param {Number} userId Unique identifier of the target user
2992
+ * @param {Number} score New score value, must be non-negative
2993
+ * @param {Object} [options] Additional Telegram query options
2994
+ * @return {Promise} On success, if the message is not an inline message, the [Message](https://core.telegram.org/bots/api#message) is returned, otherwise True is returned
2995
+ * @see https://core.telegram.org/bots/api#setgamescore
2996
+ */
2997
+ setGameScore(userId, score, form = {}) {
2998
+ form.user_id = userId;
2999
+ form.score = score;
3000
+ return this._request('setGameScore', { form });
3001
+ }
3002
+
3003
+ /**
3004
+ * Use this method to get data for high score tables.
3005
+ *
3006
+ * Will return the score of the specified user and several of their neighbors in a game.
3007
+ *
3008
+ * @param {Number} userId Unique identifier of the target user
3009
+ * @param {Object} [options] Additional Telegram query options
3010
+ * @return {Promise} On success, returns an Array of [GameHighScore](https://core.telegram.org/bots/api#gamehighscore) objects
3011
+ * @see https://core.telegram.org/bots/api#getgamehighscores
3012
+ */
3013
+ getGameHighScores(userId, form = {}) {
3014
+ form.user_id = userId;
3015
+ return this._request('getGameHighScores', { form });
3016
+ }
3017
+
3018
+ /**
3019
+ * Use this method to delete a message, including service messages, with the following limitations:
3020
+ * - A message can only be deleted if it was sent less than 48 hours ago.
3021
+ * - A dice message can only be deleted if it was sent more than 24 hours ago.
3022
+ * - Bots can delete outgoing messages in groups and supergroups.
3023
+ * - Bots can delete incoming messages in groups, supergroups and channels.
3024
+ * - Bots granted `can_post_messages` permissions can delete outgoing messages in channels.
3025
+ * - If the bot is an administrator of a group, it can delete any message there.
3026
+ * - If the bot has `can_delete_messages` permission in a supergroup, it can delete any message there.
3027
+ *
3028
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
3029
+ * @param {Number} messageId Unique identifier of the target message
3030
+ * @param {Object} [options] Additional Telegram query options
3031
+ * @return {Promise} True on success
3032
+ * @see https://core.telegram.org/bots/api#deletemessage
3033
+ */
3034
+ deleteMessage(chatId, messageId, form = {}) {
3035
+ form.chat_id = chatId;
3036
+ form.message_id = messageId;
3037
+ return this._request('deleteMessage', { form });
3038
+ }
3039
+
3040
+ /**
3041
+ * Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped.
3042
+ *
3043
+ * @param {Number|String} chatId Unique identifier for the target chat or username of the target channel (in the format @channelusername)
3044
+ * @param {Array<Number|String>} messageIds Identifiers of 1-100 messages to delete. See deleteMessage for limitations on which messages can be deleted
3045
+ * @param {Object} [options] Additional Telegram query options
3046
+ * @return {Promise<Boolean>} True on success
3047
+ * @see https://core.telegram.org/bots/api#deletemessages
3048
+ */
3049
+ deleteMessages(chatId, messageIds, form = {}) {
3050
+ form.chat_id = chatId;
3051
+ form.message_ids = stringify(messageIds);
3052
+ return this._request('deleteMessages', { form });
3053
+ }
3054
+
3055
+ }
3056
+
3057
+ module.exports = TelegramBot;