// PEP-85: a user's own Telegram bot — the token from BotFather, pairing by Start in that bot, // questions arrive from it, the shared bot keeps serving everybody else. Two mock-telegram // instances: the platform's bot and the user's. import assert from "node:assert/strict"; import { after, before, describe, test } from "node:test"; import { core, db, teardown, waitFor } from "./helpers.ts"; import { MockTelegram } from "../src/mock-telegram.ts"; import { MockTranscribe } from "../src/mock-transcribe.ts"; import type { Bot } from "@peppa/bot"; const { createBot } = await import("@peppa/bot"); const { TelegramApi } = await import("@peppa/bot/telegram"); process.env.PEPPA_SECRET = "mock-secret-for-tests"; const shared = await new MockTelegram().start(); const OWN_TOKEN = "1234567890:" + "A".repeat(35); const own = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot", token: OWN_TOKEN }).start(); const ALICE = { id: 601, chatId: 601, username: "alice" }; const BOB = { id: 602, chatId: 602, username: "bob" }; const EVE = { id: 666, chatId: 666, username: "eve" }; let bot: Bot; let alice: Awaited>; let bob: typeof alice; before(async () => { alice = await core.upsertUserFromGitea(db, { id: 8501, login: "mock-own-alice" }, { access_token: "x" }); bob = await core.upsertUserFromGitea(db, { id: 8502, login: "mock-own-bob" }, { access_token: "y" }); bot = createBot({ db, api: new TelegramApi(shared.token, shared.url), userApi: (token) => new TelegramApi(token, own.url), secret: shared.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 400, userBotsIntervalMs: 200, }); await bot.start(); }); after(async () => { await bot.stop(); await shared.stop(); await own.stop(); await teardown(); }); describe("свой Telegram-бот", () => { test("Scenario: токен проверяется у Telegram; привязка — Start в своём боте; вопрос приходит из него", async () => { await assert.rejects(core.setUserBot(db, alice.id, "не токен"), /не похоже на токен бота/); process.env.TELEGRAM_API_URL = own.url; try { own.failNext("getMe", 401); await assert.rejects(core.setUserBot(db, alice.id, OWN_TOKEN), /Telegram не принял этот токен/); assert.deepEqual(await core.setUserBot(db, alice.id, OWN_TOKEN), { username: "mock_alice_factory_bot" }); await assert.rejects(core.setUserBot(db, bob.id, OWN_TOKEN), /уже подключён другим пользователем/); } finally { delete process.env.TELEGRAM_API_URL; } const saved = (await core.getUser(db, alice.id))!; assert.equal(saved.telegramBotUsername, "mock_alice_factory_bot"); assert.ok(saved.telegramBotTokenEnc && !saved.telegramBotTokenEnc.includes(OWN_TOKEN), "stored encrypted"); assert.deepEqual((await core.userBots(db)).map((b) => [b.userId, b.token, b.chatId]), [[alice.id, OWN_TOKEN, null]]); await bot.syncOwnBots(); // The owner's code works only in her own bot. const code = await core.createPairingCode(db, shared.token, alice.id); shared.userSends(ALICE, `/start ${code}`); await waitFor("the shared bot refuses", async () => shared.botMessages(ALICE.chatId).some((m) => /неверный или истёк/.test(m.text))); assert.equal((await core.getUser(db, alice.id))!.telegramChatId, null); // Somebody else's code does not work in her bot either. own.userSends(EVE, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`); await waitFor("her bot refuses a stranger", async () => own.botMessages(EVE.chatId).some((m) => /неверный или истёк/.test(m.text))); assert.equal((await core.getUser(db, bob.id))!.telegramChatId, null); own.userSends(ALICE, `/start ${await core.createPairingCode(db, shared.token, alice.id)}`); await waitFor("paired in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => /Привязано/.test(m.text))); assert.equal((await core.getUser(db, alice.id))!.telegramChatId, ALICE.chatId); // A question of her project comes from her bot, not from the shared one. const p = await core.createProject(db, { slug: "mock-own-a", key: "MOWNA", name: "Own A", giteaOwner: "x", workspacePath: "/tmp/mock-own-a", ownerId: alice.id }); const ref = await core.createTask(db, { projectId: p.id, title: "Каталог" }); const sharedBefore = shared.botMessages(ALICE.chatId).length; const q = await core.askPm(db, ref, { kind: "question", text: "Нужна ли мобильная версия?" }); await waitFor("question in the own bot", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Нужна ли мобильная версия?"))); assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot"); // She answers by a reply in her bot. const msg = own.botMessages(ALICE.chatId).find((m) => m.text.includes("Нужна ли мобильная версия?"))!; own.userSends(ALICE, "Не нужна", msg.message_id); await waitFor("answered", async () => !!(await core.getQuestion(db, q.id)).answeredAt); assert.equal((await core.getQuestion(db, q.id)).answer, "Не нужна"); }); test("Scenario: общий бот продолжает работать для остальных; чужому свой бот не отвечает", async () => { shared.userSends(BOB, `/start ${await core.createPairingCode(db, shared.token, bob.id)}`); await waitFor("bob paired with the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => /Привязано/.test(m.text))); const p = await core.createProject(db, { slug: "mock-own-b", key: "MOWNB", name: "Own B", giteaOwner: "x", workspacePath: "/tmp/mock-own-b", ownerId: bob.id }); const ref = await core.createTask(db, { projectId: p.id, title: "Оплата" }); await core.askPm(db, ref, { kind: "question", text: "Какая валюта?" }); await waitFor("bob's question in the shared bot", async () => shared.botMessages(BOB.chatId).some((m) => m.text.includes("Какая валюта?"))); assert.equal(own.botMessages(BOB.chatId).length, 0); // Bob writes to Alice's bot: it serves its owner only. const n = own.botMessages(BOB.chatId).length; own.userSends(BOB, "/status"); await new Promise((r) => setTimeout(r, 1500)); assert.equal(own.botMessages(BOB.chatId).length, n); }); // PEP-108, spec telegram-notifications: «Стори из своего бота текстом и голосом». The voice file // exists only in her bot's mock (its own token) — getFile/downloadFile must go through the bot // the update came from; every reply comes from her bot, the shared one stays silent. test("Scenario: Стори из своего бота текстом и голосом", async () => { const p = await core.getProject(db, "MOWNA"); const sharedBefore = shared.botMessages(ALICE.chatId).length; const storyNamed = (title: string) => waitFor(`story «${title}»`, async () => (await core.listTasks(db, { projectId: p.id })).find((t) => t.title === title)); const createFrom = async (re: RegExp) => { const ask = await waitFor(`draft ${re}`, async () => own.botMessages(ALICE.chatId).find((m) => re.test(m.text))); const create = ask.reply_markup!.inline_keyboard.flat().find((b) => /Создать/.test(b.text))!; own.userClicks(ALICE, ask.message_id, create.callback_data!); await waitFor("created in her bot", async () => /Создал/.test(ask.text)); }; // Text. own.userSends(ALICE, "в MOWNA: каталог товаров"); await createFrom(/Новая задача в MOWNA<\/b>: «каталог товаров»/); assert.ok(await storyNamed("каталог товаров")); // Voice. const stt = await new MockTranscribe().start(); Object.assign(process.env, { PEPPA_TRANSCRIBE_URL: stt.url, PEPPA_TRANSCRIBE_KEY: stt.key }); try { own.userSends(ALICE, "/help"); await waitFor("help mentions voice", async () => own.botMessages(ALICE.chatId).some((m) => /наговорите голосом/.test(m.text))); own.userSendsVoice(ALICE, MockTranscribe.speech("В проекте Mowna починить вход")); await waitFor("heard", async () => own.botMessages(ALICE.chatId).some((m) => m.text.includes("Расслышал: «В проекте Mowna починить вход»"))); await createFrom(/Новая задача в MOWNA<\/b>: «починить вход»/); assert.match((await storyNamed("починить вход")).description!, /расшифровка голосового/); assert.equal(stt.requests.length, 1); } finally { delete process.env.PEPPA_TRANSCRIBE_URL; delete process.env.PEPPA_TRANSCRIBE_KEY; await stt.stop(); } assert.equal(shared.botMessages(ALICE.chatId).length, sharedBefore, "nothing through the shared bot"); }); test("отключение своего бота: опрос останавливается, привязка сбрасывается", async () => { await core.clearUserBot(db, alice.id); await bot.syncOwnBots(); const u = (await core.getUser(db, alice.id))!; assert.deepEqual([u.telegramBotTokenEnc, u.telegramBotUsername, u.telegramChatId], [null, null, null]); assert.deepEqual(await core.userBots(db), []); }); });