brendmanager/src/bot.js

272 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// BRM-52: бот владельца в Telegram. Чистое ядро: принимает update, отвечает через telegram.call.
// Привязка — по секретному слову (owner), чужие аккаунты отклоняются. Пауза — pub.stop для всех каналов.
import fs from "node:fs";
import path from "node:path";
import { decide, publish as markPublished, submit } from "./approval.js";
import { t } from "./i18n.js";
import { almatyTime } from "./deploy-status.js";
export const MENU = ["status", "strategy", "approvals", "plan", "channels", "pr", "reports", "tasks", "settings", "pause"];
const OWNER_NAME = "Татьяна";
export function createBotStore(file) {
let st = { chatId: null, awaiting: {}, voice: {} };
try { st = { ...st, ...JSON.parse(fs.readFileSync(file, "utf8")) }; } catch {}
const save = () => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(st)); };
return {
chatId: () => st.chatId,
// BRM-150: кто привязан — имя и @ник из Telegram и время, чтобы страница могла подписать привязку.
owner: () => (st.chatId === null ? null : { name: st.owner?.name ?? null, username: st.owner?.username ?? null, at: st.owner?.at ?? null }),
bind(id, who = {}) { st.chatId = id; st.owner = { name: who.name ?? null, username: who.username ?? null, at: who.at ?? null }; save(); },
unbind() { st.chatId = null; st.owner = null; st.awaiting = {}; save(); },
awaiting: () => st.awaiting.comment ?? null,
setAwaiting(v) { if (v) st.awaiting.comment = v; else delete st.awaiting.comment; save(); },
voice: () => st.voice.text ?? null,
setVoice(v) { if (v) st.voice.text = v; else delete st.voice.text; save(); },
};
}
// Какие кнопки разрешены правилами для записи календаря.
export function allowedActions(idea) {
const a = [];
if (idea.status === "review" && idea.approver === OWNER_NAME) a.push("approve", "rework", "reject");
if (idea.status === "approved" && !idea.date) a.push("schedule");
if (idea.status === "approved") a.push("now");
a.push("more");
return a;
}
// BRM-171: состояние бота одними строками для бота и страницы: кто отвечает на команды, привязка, отправка сводок,
// решения владельца. Ключей и номеров чатов в тексте нет.
export function envOf(siteUrl = "") {
if (/-prod\./.test(siteUrl)) return "prod";
if (/-staging\./.test(siteUrl)) return "staging";
if (/-pr\d+\./.test(siteUrl)) return "preview";
return "local";
}
export function sendLine(lang, d, time = (x) => x) {
const T = (k, v) => t(lang, "now." + k, v);
if (!d.problem) return T("send.ok", { time: time(d.lastOk) });
const p = d.problem;
const head = p.code === "unchecked" ? T("send.unchecked") : T("send.off", { what: T("what." + p.code) });
return `${head} ${t(lang, "sv.who." + p.who)}. ${T("do." + p.code)}`;
}
// BRM-180: строки состояния бота — одни для ответа «Статус», «Бот сейчас» на «Бот и отчёты» и на главной.
// v: where (here | elsewhere | moving | none | noBot), env, receiverEnv, who (имя владельца или null), bound, wordSet,
// delivery (state() доставки), decisions. Возвращает [{ id, ok, text }].
export function nowLines(lang, v, time = (x) => x) {
const T = (k, x) => t(lang, "now." + k, x);
const envName = (e) => T("env." + (e ?? "local"));
const w = v.where ?? "here";
const cmd = w === "elsewhere" ? T("cmd.elsewhere", { where: envName(v.receiverEnv) })
: w === "moving" ? T("cmd.moving", { where: envName(v.receiverEnv) })
: w === "here" ? T("cmd.here", { where: envName(v.env) }) : T("cmd." + w);
const bindState = w === "elsewhere" || w === "moving" ? w : v.bound ? "on" : v.wordSet ? "waiting" : "none";
const bind = T("bind." + bindState, { who: v.who || t(lang, "bot.you") });
const d = v.delivery ?? { problem: null };
const send = w === "moving" ? T("send.moving") : sendLine(lang, d, time);
const wait = w === "elsewhere" || w === "moving" ? T("wait." + w) : waitLine(lang, v.decisions ?? { total: 0, parts: {} });
return [
{ id: "cmd", ok: w === "here", text: cmd },
{ id: "bind", ok: bindState === "on", text: bind },
{ id: "send", ok: w !== "moving" && !d.problem, text: send },
{ id: "pub", ok: null, text: T("pub") },
{ id: "wait", ok: null, text: wait },
];
}
export const whoOf = (o) => (!o ? null : o.name && o.username ? `${o.name} (@${o.username})` : o.name ?? (o.username ? "@" + o.username : null));
export function waitLine(lang, dec) {
const T = (k, v) => t(lang, "now." + k, v);
const parts = Object.entries(dec.parts).filter(([, n]) => n > 0).map(([k, n]) => `${T("part." + k)}: ${n}`);
return T("wait", { n: dec.total }) + (parts.length ? " (" + parts.join(", ") + ")" : "");
}
export function createBot({ store, telegram, pub, owner, getPlan, savePlan, transcriber, testRun = null, strategyCard = null, siteUrl = "", decisions = null, lang = "ru", now = () => new Date() }) {
const L = (k, v) => t(lang, "bot." + k, v);
const send = (chat, text, buttons) => telegram.call("sendMessage", { chat_id: chat, text, ...(buttons ? { reply_markup: { inline_keyboard: buttons } } : {}) });
const menuKeys = () => ({ reply_markup: { keyboard: MENU.map((k) => [{ text: L("menu." + k) }]), resize_keyboard: true } });
const sendMenu = (chat, text) => telegram.call("sendMessage", { chat_id: chat, text, ...menuKeys() });
const ideas = () => getPlan().ideas;
const N = (k, v) => t(lang, "now." + k, v);
const delivery = () => telegram.state?.() ?? { problem: telegram.connected() ? null : { code: "key", who: "pm" }, lastOk: null };
const when = (iso) => (iso ? almatyTime(iso) : "");
// Кнопки под ответом «Статус»: выбрать этот чат для сводок или проверить доставку.
const sendButtons = (d) => (d.problem?.code === "chat" || d.problem?.code === "other" ? [[{ text: t(lang, "sv.req.summaryHere"), callback_data: "ss:here" }]]
: ["unchecked", "blocked", "failed"].includes(d.problem?.code) ? [[{ text: N("checkBtn"), callback_data: "dc:0" }]] : undefined);
const statusText = (who) => {
const d = delivery();
const dec = decisions ? decisions() : { total: ideas().filter((i) => i.status === "review").length, parts: {} };
return nowLines(lang, { where: "here", env: envOf(siteUrl), bound: true, who, delivery: d, decisions: dec }, when).map((x) => x.text).join("\n");
};
// Проверочное сообщение в чат сводок; при неудаче — причина тем же текстом, что на странице.
async function checkDelivery(chat) {
if (!telegram.check) return;
const r = await telegram.check(N("check"));
if (!r.ok) await send(chat, sendLine(lang, delivery(), when));
}
function card(idea) {
const lines = [
`${idea.title}`,
L("card.text") + ": " + (idea.description || L("none")),
L("card.channel") + ": " + (idea.channel ?? L("none")),
L("card.date") + ": " + (idea.date ?? L("none")),
L("card.risk") + ": " + (idea.risk ?? L("card.riskNone")),
L("card.sources") + ": " + (idea.sources ?? L("card.sourcesNone")),
L("card.status") + ": " + L("st." + idea.status),
];
const btn = allowedActions(idea).map((a) => ({ text: L("act." + a), callback_data: `${a}:${idea.id}` }));
return { text: lines.join("\n"), buttons: btn.map((b) => [b]) };
}
async function showApprovals(chat) {
const list = ideas().filter((i) => i.status === "review");
if (!list.length) return send(chat, L("approvals.empty"));
for (const i of list) { const c = card(i); await send(chat, c.text, c.buttons); }
}
async function section(chat, key) {
const s = pub.status();
if (key === "status") {
return send(chat, statusText(whoOf(store.owner?.())), sendButtons(delivery()));
}
if (key === "approvals") return showApprovals(chat);
if (key === "plan") {
const next = ideas().filter((i) => i.date && i.status !== "published").sort((a, b) => a.date.localeCompare(b.date)).slice(0, 5);
return send(chat, next.length ? next.map((i) => `${i.date} — ${i.title}`).join("\n") : L("plan.empty"));
}
if (key === "channels") {
// BRM-180: telegram «включён» — только после подтверждённой доставки, как в строке «Отправка сводок».
const d = delivery();
const on = (k, c) => c.connected && (k !== "telegram" || !d.problem);
return send(chat, sendLine(lang, d, when) + "\n" + Object.entries(s.channels).map(([k, c]) => `${k}: ${c.stopped ? L("paused") : on(k, c) ? L("on") : L("offShort")}`).join("\n"));
}
if (key === "strategy" && strategyCard) {
const v = strategyCard.view();
return send(chat, v.n ? L("strategy.now", { n: v.n, stage: t(lang, "sv.stage." + v.stage), link: siteUrl ? siteUrl + "/strategy.html" : L("strategy.page") }) : t(lang, "sv.stage.none"));
}
if (key === "pause") {
pub.stop(undefined, "bot");
return send(chat, L("pause.done"), [[{ text: L("resume"), callback_data: "resume:0" }]]);
}
return send(chat, L("soon." + key));
}
async function act(chat, action, id) {
if (action === "resume") { pub.resume(undefined, "bot"); return send(chat, L("resume.done")); }
const idea = ideas().find((i) => i.id === id);
if (!idea) return send(chat, L("err.notFound"));
if (action !== "more" && !allowedActions(idea).includes(action)) return send(chat, L("err.notAllowed"));
const at = now().toISOString();
if (action === "more") return send(chat, `${idea.title}\n${idea.description || L("none")}\n${L("card.history")}: ${(idea.history ?? []).map((h) => `${h.at?.slice(0, 10)} ${L("st." + h.to)}`).join(", ") || L("none")}`);
if (action === "approve") {
const r = decide(idea, { action: "approve", by: OWNER_NAME }, at); savePlan();
return send(chat, r.err ? L("err.notAllowed") : L("done.approve"));
}
if (action === "rework" || action === "reject") {
store.setAwaiting({ id, action });
return send(chat, L(action === "rework" ? "ask.rework" : "ask.reject"));
}
if (action === "schedule") {
const d = new Date(now().getTime() + 86400e3).toISOString().slice(0, 10);
idea.date = d; savePlan();
return send(chat, L("done.schedule", { date: d }));
}
if (action === "now") {
const r = await pub.publish({ channel: "telegram", text: `${idea.title}\n${idea.description ?? ""}`.trim(), approvedBy: "tatiana" });
if (r.result !== "published") return send(chat, L("err.send", { why: L("why." + (["stopped", "limit"].includes(r.reason) ? r.reason : "other")) }));
// BRM-58: «опубликовано» — только со ссылкой; без неё запись ждёт ссылку в карточке на «Плане».
const m = markPublished(idea, getPlan().publications, { channel: "telegram", date: at.slice(0, 10), by: OWNER_NAME, link: r.url }, at); savePlan();
return send(chat, L(m.err ? "done.nowNoLink" : "done.now"));
}
}
async function onText(chat, text) {
const pend = store.awaiting();
if (pend) {
store.setAwaiting(null);
const idea = ideas().find((i) => i.id === pend.id);
if (!idea || !text.trim()) return send(chat, L("err.notFound"));
const r = decide(idea, { action: "return", comment: pend.action === "reject" ? `${L("rejected")}: ${text}` : text, by: OWNER_NAME }, now().toISOString()); savePlan();
return send(chat, r.err ? L("err.notAllowed") : L("done." + pend.action));
}
const key = MENU.find((k) => L("menu." + k) === text.trim());
if (key) return section(chat, key);
// BRM-165: после «На доработку» следующий текст — замечание к версии стратегии.
const sv = strategyCard?.takeText(text, now().getTime());
if (sv) return send(chat, sv);
return sendMenu(chat, L("hello"));
}
async function onVoice(chat, voice) {
const text = await transcriber.transcribe(voice).catch(() => "");
if (!text) return send(chat, L("voice.fail"));
store.setVoice(text);
return send(chat, L("voice.confirm", { text }), [[{ text: L("voice.yes"), callback_data: "vyes:0" }, { text: L("voice.no"), callback_data: "vno:0" }]]);
}
async function handleUpdate(u) {
// BRM-143: бота добавили в канал — проверочный путь предлагает владельцу подтвердить его как закрытый тестовый.
if (u.my_chat_member) {
const m = u.my_chat_member;
const added = ["administrator", "member"].includes(m.new_chat_member?.status);
if (testRun && added && ["channel", "supergroup", "group"].includes(m.chat?.type) && store.chatId() !== null) await testRun.offerChannel(m.chat, now().getTime());
return { ok: true };
}
const msg = u.message ?? u.callback_query?.message;
const from = u.message?.from ?? u.callback_query?.from;
const chat = msg?.chat?.id;
if (!chat) return { ok: true };
const bound = store.chatId();
// Привязка: /start → просьба назвать секретное слово → подтверждение.
if (bound === null || String(from?.id) !== String(bound)) {
const text = u.message?.text ?? "";
if (bound !== null) { await send(chat, L("denied")); return { ok: true, denied: true }; }
// BRM-150: на /start — шаги привязки; ссылка на «Бот и отчёты», где задаётся слово для одобрения.
const steps = () => L(owner.isSet() ? "bind.start" : "bind.startNoWord", { link: siteUrl ? siteUrl + "/bot.html" : L("bind.pageName") });
if (text.startsWith("/start")) { await send(chat, steps()); return { ok: true }; }
if (text && owner.isSet()) {
if (owner.verify(text) === "ok") {
const name = [from?.first_name, from?.last_name].filter(Boolean).join(" ") || null;
store.bind(from.id, { name, username: from?.username ?? null, at: now().toISOString() });
await sendMenu(chat, L("bind.done"));
// BRM-180: сразу после привязки — выбрать этот личный чат для сводок одной кнопкой.
if (strategyCard && delivery().problem?.code === "chat") await send(chat, L("bind.summary"), [[{ text: t(lang, "sv.req.summaryHere"), callback_data: "ss:here" }]]);
return { ok: true, bound: true };
}
await send(chat, L("bind.wrong")); return { ok: true, denied: true };
}
await send(chat, steps());
return { ok: true };
}
if (u.callback_query) {
const parts = String(u.callback_query.data).split(":");
const [a, id] = parts;
// tr:<действие>:<карточка>:<хеш версии> — кнопки карточки; tc:yes:<chat id> — подтверждение тестового канала
if (testRun && a === "tr") { await send(chat, await testRun.onButton(parts[1], parts[2], parts[3], now().getTime())); return { ok: true }; }
// BRM-165: sv:<approve|rework>:<версия>:<хеш> — карточка стратегии; sq:<вопрос>:<вариант>; ss:<here|other> — чат для сводок
if (strategyCard && ["sv", "sq", "ss"].includes(a)) {
await send(chat, await strategyCard.onButton(a, parts.slice(1), now().getTime()));
if (a === "ss" && parts[1] === "here") await checkDelivery(chat); // BRM-171: сразу проверяем доставку в выбранный чат
return { ok: true };
}
if (a === "dc") { await checkDelivery(chat); return { ok: true }; }
if (testRun && a === "tc") { await send(chat, await testRun.confirmChannel(parts.slice(2).join(":"), now().getTime())); return { ok: true }; }
if (a === "vyes") { const tx = store.voice(); store.setVoice(null); if (tx) await onText(chat, tx); return { ok: true }; }
if (a === "vno") { store.setVoice(null); await send(chat, L("voice.again")); return { ok: true }; }
await act(chat, a, Number(id));
return { ok: true };
}
if (u.message.voice) { await onVoice(chat, u.message.voice); return { ok: true }; }
if (u.message.text === "/start") { await sendMenu(chat, L("hello")); return { ok: true }; }
await onText(chat, u.message.text ?? "");
return { ok: true };
}
return { handleUpdate };
}
// Мок распознавания речи: ключа сервиса нет. Контракт: transcribe({file_id,duration}) → текст.
export function mockTranscriber(text = "Покажи статус") {
return { async transcribe(voice) { if (!voice?.file_id) throw new Error("нет файла"); return text; } };
}