// 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, // 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; } export function createBot({ store, telegram, pub, owner, getPlan, savePlan, transcriber, testRun = null, strategyCard = null, siteUrl = "", 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 === "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")) })); 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); // 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")); 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: — подтверждение тестового канала if (testRun && a === "tr") { await send(chat, await testRun.onButton(parts[1], parts[2], parts[3], now().getTime())); return { ok: true }; } // BRM-165: sv::<версия>:<хеш> — карточка стратегии; sq:<вопрос>:<вариант>; ss: — чат для сводок if (strategyCard && ["sv", "sq", "ss"].includes(a)) { await send(chat, await strategyCard.onButton(a, parts.slice(1), now().getTime())); 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; } }; }