UNPKG

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