// 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; } export class MockTelegram { readonly token = "mock-123:TOKEN"; readonly bot = { id: 999, username: "mock_peppa_bot", is_bot: true, first_name: "Mock Peppa" }; 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; url = ""; async start(port = 0): Promise { this.server = createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", async () => { 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 "sendMessage": { 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: "private" }, 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 "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" } } } : {}), }, }); } /** 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: "private" }, 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); } }