171 lines
8.9 KiB
JavaScript
171 lines
8.9 KiB
JavaScript
// 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";
|
|
|
|
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,
|
|
bind(id) { st.chatId = id; save(); },
|
|
unbind() { st.chatId = 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;
|
|
}
|
|
|
|
export function createBot({ store, telegram, pub, owner, getPlan, savePlan, transcriber, 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 off = () => (telegram.connected() ? "" : L("off") + "\n");
|
|
|
|
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") {
|
|
const n = ideas().filter((i) => i.status === "review").length;
|
|
return send(chat, off() + L("status", { wait: n, state: s.stopped ? L("paused") : L("running") }));
|
|
}
|
|
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") {
|
|
return send(chat, off() + Object.entries(s.channels).map(([k, c]) => `${k}: ${c.stopped ? L("paused") : c.connected ? L("on") : L("offShort")}`).join("\n"));
|
|
}
|
|
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")) }));
|
|
markPublished(idea, getPlan().publications, { channel: "telegram", date: at.slice(0, 10), by: OWNER_NAME }, at); savePlan();
|
|
return send(chat, L("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);
|
|
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) {
|
|
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 }; }
|
|
if (text.startsWith("/start")) { await send(chat, L("bind.ask")); return { ok: true }; }
|
|
if (text && owner.isSet()) {
|
|
if (owner.verify(text) === "ok") { store.bind(from.id); await sendMenu(chat, L("bind.done")); return { ok: true, bound: true }; }
|
|
await send(chat, L("bind.wrong")); return { ok: true, denied: true };
|
|
}
|
|
await send(chat, owner.isSet() ? L("bind.ask") : L("bind.noWord"));
|
|
return { ok: true };
|
|
}
|
|
if (u.callback_query) {
|
|
const [a, id] = String(u.callback_query.data).split(":");
|
|
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; } };
|
|
}
|