@xalbex/telegram-bot
Version:
Telegram Bot API for Node.js
86 lines • 3.37 kB
JavaScript
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const API = __importStar(require("./api"));
const events_1 = require("events");
class TelegramBotManager extends events_1.EventEmitter {
constructor(token) {
// Construct the EventEmitter object
super();
/**
* When this flag is true, when this object recives an update,
* immediately re-send another getUpdates request for next updates.
*/
this.continueUpdates = false;
/**
* Last update_id received. Update identifiers
* start from a certain positive number and increase sequentially.
* This ID becomes especially handy if you’re using Webhooks,
* since it allows you to ignore repeated updates or to restore
* the correct update sequence, should they get out of order.
* If there are no new updates for at least a week, then identifier
* of the next update will be chosen randomly instead of sequentially.
*/
this.lastUpdateId = 0;
// The object to make raw requests
this.api = new API.TelegramBotRaw(token);
// Start the polling of the updates
this.start();
}
/**
* Put this object into listening state.
* The object will emit events for each new update.
*/
start() {
if (this.continueUpdates === false)
this.dispatchUpdates();
}
/**
* Stop this object form the listening state.
* After the response of the getUpdates request it
* will not make any other requests. *
*/
stop() {
if (this.continueUpdates === true)
this.continueUpdates = false;
}
/**
* Continue to make getUpdates requests and
* emit the appropriate event until the flag continueUpdates is true.
*/
async dispatchUpdates() {
// Set the flag to true
this.continueUpdates = true;
for (;;) {
try {
// Obtains update after the last that I have received
let updates = await this.api.getUpdates({ timeout: 60, offset: this.lastUpdateId + 1 });
// Check if the update cycle has to stop
if (!this.continueUpdates)
break;
// Iterate over all updates
for (let update of updates)
for (let key in update) {
// It emits events for every properties expect for update_id
if (key !== 'update_id')
this.emit(key, update[key]);
}
// Cambia l'ID dell'ultimo aggiornamento
if (updates.length)
this.lastUpdateId = updates[updates.length - 1].update_id;
}
catch (error) {
// It emits the error raised in the getUpdates request.
this.emit('error', error);
}
}
}
}
exports.TelegramBotManager = TelegramBotManager;
//# sourceMappingURL=client.js.map