diff --git a/src/telegram.js b/src/telegram.js index a54a447..ce6bf46 100644 --- a/src/telegram.js +++ b/src/telegram.js @@ -32,6 +32,7 @@ var requestPromise = Promise.promisify(request); */ var TelegramBot = function (token, options) { options = options || {}; + this.options = options; this.token = token; this.messageTypes = [ 'text', 'audio', 'document', 'photo', 'sticker', 'video', 'voice', 'contact', @@ -39,19 +40,27 @@ var TelegramBot = function (token, options) { 'new_chat_photo', 'delete_chat_photo', 'group_chat_created' ]; // Telegram message events - var processUpdate = this._processUpdate.bind(this); + this.processUpdate = this._processUpdate.bind(this); if (options.polling) { - this._polling = new TelegramBotPolling(token, options.polling, processUpdate); + this.initPolling(); } if (options.webHook) { - this._WebHook = new TelegramBotWebHook(token, options.webHook, processUpdate); + this._WebHook = new TelegramBotWebHook(token, options.webHook, this.processUpdate); } }; util.inherits(TelegramBot, EventEmitter); +TelegramBot.prototype.initPolling = function() { + if (this._polling) { + this._polling.abort = true; + this._polling.lastRequest.cancel("Polling restart"); + } + this._polling = new TelegramBotPolling(this.token, this.options.polling, this.processUpdate); +}; + TelegramBot.prototype._processUpdate = function (update) { debug('Process Update %j', update); var message = update.message; diff --git a/src/telegramPolling.js b/src/telegramPolling.js index 2436590..abd5708 100644 --- a/src/telegramPolling.js +++ b/src/telegramPolling.js @@ -16,13 +16,17 @@ var TelegramBotPolling = function (token, options, callback) { this.callback = callback; this.timeout = options.timeout || 0; this.interval = options.interval || 2000; + this.lastUpdate = 0; + this.lastRequest = null; + this.abort = false; this._polling(); }; TelegramBotPolling.prototype._polling = function () { var self = this; - this._getUpdates().then(function (updates) { + this.lastRequest = this._getUpdates().then(function (updates) { + self.lastUpdate = Date.now(); debug('polling data %j', updates); updates.forEach(function (update, index) { // If is the latest, update the offset. @@ -35,6 +39,11 @@ TelegramBotPolling.prototype._polling = function () { }).catch(function (err) { debug('polling error: %j', err); }).finally(function () { + if (self.abort) { + debug('Polling is aborted!'); + return; + } + debug('setTimeout for %s miliseconds', self.interval); setTimeout(self._polling.bind(self), self.interval); }); @@ -54,7 +63,7 @@ TelegramBotPolling.prototype._getUpdates = function () { }) }; debug('polling with options: %j', opts); - return requestPromise(opts).then(function (resp) { + return requestPromise(opts).cancellable().then(function (resp) { if (resp[0].statusCode !== 200) { throw new Error(resp[0].statusCode+' '+resp[0].body); }