// Mock Telegram Bot API server for bot tests: the methods Peppa's bot uses, long-polling // getUpdates, injectable user actions, and failure injection (429 / 5xx). import { createServer, type Server } from "node:http"; import type { AddressInfo } from "node:net"; export interface MockTgMessage { message_id: number; chat_id: number; text: string; reply_markup?: { inline_keyboard: Array> }; edits: number; reply_to?: number; } export interface MockTgUser { id: number; chatId: number; username?: string; } /** Groups have negative ids in Telegram. */ const chatType = (chatId: number) => (chatId < 0 ? "group" : "private"); export class MockTelegram { readonly token = "mock-123:TOKEN"; /** PEP-85: a second instance stands in for a user's own bot — give it its own identity. */ constructor(bot: { id?: number; username?: string } = {}) { this.bot = { id: bot.id ?? 999, username: bot.username ?? "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" }; } readonly bot: { id: number; username: string; is_bot: boolean; first_name: string }; readonly messages = new Map(); readonly callbackAnswers: Array<{ id: string; text?: string }> = []; readonly calls: Array<{ method: string; params: Record }> = []; private updates: Array & { update_id: number }> = []; private nextUpdateId = 1; private nextMessageId = 100; private waiters: Array<() => void> = []; private failures: Array<{ method: string; code: number; retryAfter?: number }> = []; private server: Server | null = null; /** PEP-45: uploaded voice files by file_id (served at /file/bot/). */ private files = new Map(); /** PEP-60: channels by chat id; the bot's membership decides what getChat/sendMessage do. */ readonly channels = new Map(); url = ""; /** A channel; by default the bot is its admin with the right to post. */ addChannel(chatId: number, title: string, o: { bot?: "administrator" | "member" | "left"; canPost?: boolean } = {}) { this.channels.set(chatId, { title, bot: o.bot ?? "administrator", canPost: o.canPost ?? true }); } async start(port = 0): Promise { this.server = createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", async () => { if (req.method === "GET" && req.url!.startsWith(`/file/bot${this.token}/`)) { const path = decodeURIComponent(req.url!.slice(`/file/bot${this.token}/`.length)); const f = [...this.files.values()].find((x) => x.path === path); res.writeHead(f ? 200 : 404, { "Content-Type": "application/octet-stream" }); return res.end(f?.data ?? ""); } if (req.url!.startsWith("/_mock/")) { const r = this.inspect(req.method!, req.url!, body ? JSON.parse(body) : {}); res.writeHead(r.status, { "Content-Type": "application/json" }); return res.end(JSON.stringify(r.body)); } const method = req.url!.split("/").pop()!; const params = body ? (JSON.parse(body) as Record) : {}; const result = await this.handle(method, params); res.writeHead(result.ok ? 200 : (result.error_code as number), { "Content-Type": "application/json" }); res.end(JSON.stringify(result)); }); }); await new Promise((r) => this.server!.listen(port, "127.0.0.1", r)); this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`; return this; } async stop() { this.waiters.forEach((w) => w()); await new Promise((r) => this.server?.close(() => r()) ?? r()); } /** The next call to `method` fails with this code (429 carries retry_after). */ failNext(method: string, code: number, retryAfter?: number) { this.failures.push({ method, code, retryAfter }); } private async handle(method: string, p: Record): Promise> { if (method !== "getUpdates") this.calls.push({ method, params: p }); const f = this.failures.findIndex((x) => x.method === method); if (f >= 0) { const { code, retryAfter } = this.failures.splice(f, 1)[0]!; return { ok: false, error_code: code, description: code === 429 ? "Too Many Requests" : "Internal Server Error", ...(retryAfter != null ? { parameters: { retry_after: retryAfter } } : {}) }; } switch (method) { case "getMe": return { ok: true, result: this.bot }; case "getUpdates": { const offset = Number(p.offset ?? 0); const timeout = Math.min(Number(p.timeout ?? 0), 1); const pending = () => this.updates.filter((u) => u.update_id >= offset); if (!pending().length && timeout > 0) { await new Promise((r) => { const t = setTimeout(r, timeout * 1000); this.waiters.push(() => (clearTimeout(t), r())); }); } return { ok: true, result: pending() }; } case "getChat": { const c = this.channels.get(Number(p.chat_id)); if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" }; return { ok: true, result: { id: Number(p.chat_id), type: "channel", title: c.title } }; } case "getChatMember": { const c = this.channels.get(Number(p.chat_id)); if (!c || c.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" }; if (Number(p.user_id) !== this.bot.id) return { ok: false, error_code: 400, description: "Bad Request: user not found" }; return { ok: true, result: { user: this.bot, status: c.bot, ...(c.bot === "administrator" ? { can_post_messages: c.canPost } : {}) } }; } case "sendMessage": { // Channels added with addChannel: the bot must be an admin that may post. Other «-100…» // ids are supergroups (PEP-62) and accept messages as before. const ch = this.channels.get(Number(p.chat_id)); if (ch && ch.bot === "left") return { ok: false, error_code: 400, description: "Bad Request: chat not found" }; if (ch && (ch.bot !== "administrator" || !ch.canPost)) return { ok: false, error_code: 403, description: "Forbidden: bot is not a member of the channel chat" }; const m: MockTgMessage = { message_id: this.nextMessageId++, chat_id: Number(p.chat_id), text: String(p.text), reply_markup: p.reply_markup as MockTgMessage["reply_markup"], edits: 0, reply_to: (p.reply_parameters as { message_id?: number } | undefined)?.message_id, }; this.messages.set(m.message_id, m); return { ok: true, result: { message_id: m.message_id, chat: { id: m.chat_id, type: chatType(m.chat_id) }, text: m.text } }; } case "editMessageText": { const m = this.messages.get(Number(p.message_id)); if (!m) return { ok: false, error_code: 400, description: "Bad Request: message to edit not found" }; if (m.text === p.text) return { ok: false, error_code: 400, description: "Bad Request: message is not modified" }; m.text = String(p.text); m.reply_markup = p.reply_markup as MockTgMessage["reply_markup"]; m.edits++; return { ok: true, result: { message_id: m.message_id } }; } case "getFile": { const f = this.files.get(String(p.file_id)); if (!f) return { ok: false, error_code: 400, description: "Bad Request: invalid file_id" }; return { ok: true, result: { file_id: p.file_id, file_unique_id: `u-${p.file_id}`, file_size: f.data.length, file_path: f.path } }; } case "answerCallbackQuery": this.callbackAnswers.push({ id: String(p.callback_query_id), text: p.text as string | undefined }); return { ok: true, result: true }; default: return { ok: false, error_code: 404, description: `mock: unknown method ${method}` }; } } private push(update: Record) { const u = { update_id: this.nextUpdateId++, ...update }; this.updates.push(u); this.waiters.splice(0).forEach((w) => w()); return u.update_id; } /** User sends a text message (optionally as a reply). */ userSends(user: MockTgUser, text: string, replyTo?: number) { return this.push({ message: { message_id: this.nextMessageId++, chat: { id: user.chatId, type: "private" }, from: { id: user.id, username: user.username, first_name: user.username ?? "user" }, text, ...(replyTo ? { reply_to_message: { message_id: replyTo, chat: { id: user.chatId, type: "private" } } } : {}), }, }); } /** PEP-62: a user writes in a group (negative chat id, as in Telegram), optionally as a reply. */ userSendsInGroup(user: MockTgUser, group: { id: number; title: string }, text: string, replyTo?: number) { const chat = { id: group.id, type: "group", title: group.title }; return this.push({ message: { message_id: this.nextMessageId++, chat, from: { id: user.id, username: user.username, first_name: user.username ?? "user" }, text, ...(replyTo ? { reply_to_message: { message_id: replyTo, chat } } : {}), }, }); } /** User sends a voice note (OGG/Opus in real Telegram; any bytes here). */ userSendsVoice(user: MockTgUser, audio: Buffer, duration = 3) { const fileId = `mock-voice-${this.nextMessageId}`; this.files.set(fileId, { path: `voice/file_${this.nextMessageId}.oga`, data: audio }); return this.push({ message: { message_id: this.nextMessageId++, chat: { id: user.chatId, type: "private" }, from: { id: user.id, username: user.username, first_name: user.username ?? "user" }, voice: { file_id: fileId, file_unique_id: `u-${fileId}`, duration, mime_type: "audio/ogg", file_size: audio.length }, }, }); } /** User presses an inline button on a bot message. */ userClicks(user: MockTgUser, messageId: number, data: string) { const id = `cb-${this.nextUpdateId}`; const m = this.messages.get(messageId); this.push({ callback_query: { id, from: { id: user.id, username: user.username }, message: { message_id: messageId, chat: { id: m?.chat_id ?? user.chatId, type: chatType(m?.chat_id ?? user.chatId) }, text: m?.text }, data, }, }); return id; } /** The user that /_mock/send and /_mock/click act as (the dev stand's PM). */ pmUser: MockTgUser = { id: 4242, chatId: 4242, username: "mock-pm" }; /** Inspection/actions for the dev stand (peppa-dev tg). */ private inspect(method: string, url: string, body: Record): { status: number; body: unknown } { const path = url.split("?")[0]; if (method === "GET" && path === "/_mock/messages") { return { status: 200, body: this.botMessages(this.pmUser.chatId) }; } if (method === "GET" && path === "/_mock/callbacks") return { status: 200, body: this.callbackAnswers }; if (method === "POST" && path === "/_mock/send") { return { status: 200, body: { update_id: this.userSends(this.pmUser, String(body.text), body.replyTo ? Number(body.replyTo) : undefined) } }; } if (method === "POST" && path === "/_mock/click") { return { status: 200, body: { callback_id: this.userClicks(this.pmUser, Number(body.messageId), String(body.data)) } }; } return { status: 404, body: { error: `mock-telegram: ${method} ${path}` } }; } botMessages(chatId: number) { return [...this.messages.values()].filter((m) => m.chat_id === chatId); } }