UNPKG

n8n-nodes-telegram-mtproto

Version:

Telegram MTPROTO API integration for n8n - Real-time new message listening and automation

77 lines 3.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TelegramConnectionManager = void 0; const telegram_1 = require("telegram"); const sessions_1 = require("telegram/sessions"); class TelegramConnectionManager { constructor() { this.clients = new Map(); } static getInstance() { if (!TelegramConnectionManager.instance) { TelegramConnectionManager.instance = new TelegramConnectionManager(); } return TelegramConnectionManager.instance; } getClientKey(credentials) { return `${credentials.apiId}_${credentials.phoneNumber}`; } async getClient(credentials) { const clientKey = this.getClientKey(credentials); if (this.clients.has(clientKey)) { const existingClient = this.clients.get(clientKey); if (existingClient.connected) { return existingClient; } } const sessionString = credentials.sessionString; const stringSession = new sessions_1.StringSession(sessionString); const client = new telegram_1.TelegramClient(stringSession, parseInt(credentials.apiId, 10), credentials.apiHash, { connectionRetries: 5, useIPV6: false, }); try { await client.start({ phoneNumber: async () => credentials.phoneNumber, password: async () => { throw new Error('Two-factor authentication detected. Please disable 2FA temporarily or provide password functionality.'); }, phoneCode: async () => { throw new Error('Phone verification code is required. Please ensure you have authorized this application first.'); }, onError: (err) => { console.error('Telegram auth error:', err); throw err; }, }); this.clients.set(clientKey, client); return client; } catch (error) { if (error instanceof Error) { throw new Error(`Authentication failed: ${error.message}. Please ensure your credentials are correct and you have authorized this application with Telegram.`); } throw error; } } async disconnectClient(credentials) { const clientKey = this.getClientKey(credentials); const client = this.clients.get(clientKey); if (client) { try { await client.disconnect(); } catch (error) { console.error('Error disconnecting client:', error); } this.clients.delete(clientKey); } } async disconnectAll() { const disconnectPromises = Array.from(this.clients.values()).map((client) => client.disconnect().catch((error) => console.error('Error disconnecting client:', error))); await Promise.all(disconnectPromises); this.clients.clear(); } } exports.TelegramConnectionManager = TelegramConnectionManager; //# sourceMappingURL=TelegramConnectionManager.js.map