119 lines
6.9 KiB
TypeScript
119 lines
6.9 KiB
TypeScript
// 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 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 = await new MockTelegram({ id: 4242, username: "mock_alice_factory_bot" }).start();
|
||
const OWN_TOKEN = "1234567890:" + "A".repeat(35);
|
||
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<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
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);
|
||
});
|
||
|
||
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), []);
|
||
});
|
||
});
|