UNPKG

typescript-telegram-bot-api

Version:

Telegram Bot API wrapper for Node.js written in TypeScript

65 lines (64 loc) 2.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Polling = void 0; const types_1 = require("./types/"); const errors_1 = require("./errors"); class Polling { constructor(telegramBot) { this.telegramBot = telegramBot; this.abortController = new AbortController(); this.offset = 0; } emitMessage(message) { types_1.messageTypes.forEach((key) => { if (key in message) { this.telegramBot.emit(`message:${key}`, message); } }); } emitUpdate(update) { Object.keys(update).forEach((key) => { if (key !== 'update_id') { const eventType = key; const eventData = update[eventType]; if (eventData !== undefined) { this.telegramBot.emit(eventType, eventData); if (eventType === 'message') { this.emitMessage(eventData); } } } }); } async poll() { while (!this.abortController.signal.aborted) { try { const updates = await this.telegramBot.getUpdates({ offset: this.offset, allowed_updates: this.telegramBot.allowedUpdates, timeout: this.telegramBot.pollingTimeout, }, this.abortController); for (const update of updates) { this.emitUpdate(update); this.offset = update.update_id + 1; } } catch (error) { if (error instanceof errors_1.TelegramError) { if (error.response.error_code === 409) { /* eslint-disable no-console */ console.warn(error.message); /* eslint-enable no-console */ } } } } } async start() { this.poll().catch(); } async stop() { this.abortController.abort(); } } exports.Polling = Polling;