- bot: own Bot API client, long polling with persisted offset, updates claimed before acting (no replay after restart), outbox with retries (429 retry_after, 5xx), /start pairing code (hashed, single use, 10 min), only the paired chat/user is served - PM questions rendered per kind: approve button / reply to reject, option buttons, allow/always/deny, alerts with continue or resume/stop; messages are closed with who answered what, incl. terminal answers - stopping/resuming a session expires its open questions - CLI: peppa telegram pair|status|unpair; launchd agent for the bot - testkit: mock-telegram + 11 bot journeys (32 e2e tests, all green) - fix: keep the tmux server alive when empty (exit-empty off) — a new session could die with a server shutting down after the last kill - fix: test env must load before runner modules (no leaks to real tmux) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
152 lines
6.0 KiB
TypeScript
152 lines
6.0 KiB
TypeScript
// 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<Array<{ text: string; callback_data?: string }>> };
|
|
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<number, MockTgMessage>();
|
|
readonly callbackAnswers: Array<{ id: string; text?: string }> = [];
|
|
readonly calls: Array<{ method: string; params: Record<string, unknown> }> = [];
|
|
private updates: Array<Record<string, unknown> & { 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(): Promise<this> {
|
|
this.server = createServer((req, res) => {
|
|
let body = "";
|
|
req.on("data", (c) => (body += c));
|
|
req.on("end", async () => {
|
|
const method = req.url!.split("/").pop()!;
|
|
const params = body ? (JSON.parse(body) as Record<string, unknown>) : {};
|
|
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<void>((r) => this.server!.listen(0, "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<void>((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<string, unknown>): Promise<Record<string, unknown>> {
|
|
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<void>((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<string, unknown>) {
|
|
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;
|
|
}
|
|
|
|
botMessages(chatId: number) {
|
|
return [...this.messages.values()].filter((m) => m.chat_id === chatId);
|
|
}
|
|
}
|