| 35 | // --------------------------------------------------------------------------- |
| 36 | |
| 37 | export class TelegramAdapter implements PlatformAdapter, MessageSender { |
| 38 | readonly name = "telegram"; |
| 39 | |
| 40 | private bot: TelegramBot | null = null; |
| 41 | private agent: IPackAgent | null = null; |
| 42 | private options: TelegramAdapterOptions; |
| 43 | private rootDir = ""; |
| 44 | private ipcBroadcaster: IpcBroadcaster | null = null; |
| 45 | |
| 46 | constructor(options: TelegramAdapterOptions) { |
| 47 | this.options = options; |
| 48 | } |
| 49 | |
| 50 | async start(ctx: AdapterContext): Promise<void> { |
| 51 | this.agent = ctx.agent; |
| 52 | this.rootDir = ctx.rootDir; |
| 53 | this.ipcBroadcaster = ctx.ipcBroadcaster ?? null; |
| 54 | |
| 55 | this.bot = new TelegramBot(this.options.token, { polling: true }); |
| 56 | |
| 57 | this.bot.on("message", (msg) => { |
| 58 | this.handleTelegramMessage(msg).catch((err) => { |
| 59 | console.error("[Telegram] Error handling message:", err); |
| 60 | }); |
| 61 | }); |
| 62 | |
| 63 | // Register bot commands with Telegram |
| 64 | await this.bot.setMyCommands(getTelegramBotCommands()); |
| 65 | |
| 66 | const me = await this.bot.getMe(); |
| 67 | console.log(`[TelegramAdapter] Started as @${me.username}`); |
| 68 | } |
| 69 | |
| 70 | async stop(): Promise<void> { |
| 71 | if (this.bot) { |
| 72 | await this.bot.stopPolling(); |
| 73 | this.bot = null; |
| 74 | } |
| 75 | console.log("[TelegramAdapter] Stopped"); |
| 76 | } |
| 77 | |
| 78 | // ------------------------------------------------------------------------- |
| 79 | // MessageSender – proactive message sending |
| 80 | // ------------------------------------------------------------------------- |
| 81 | |
| 82 | /** |
| 83 | * Public method: send a message to a specific Telegram chat. |
| 84 | * channelId format: telegram-<chatId> |
| 85 | */ |
| 86 | async sendMessage(channelId: string, text: string): Promise<void> { |
| 87 | if (!this.bot) throw new Error("[Telegram] Bot not initialized"); |
| 88 | const chatId = Number(channelId.replace("telegram-", "")); |
| 89 | if (isNaN(chatId)) { |
| 90 | throw new Error(`[Telegram] Invalid channelId: ${channelId}`); |
| 91 | } |
| 92 | await this.sendLongMessage(chatId, text); |
| 93 | } |
| 94 |
nothing calls this directly
no outgoing calls
no test coverage detected