diff --git a/locales/ru.json b/locales/ru.json index 4f8e7d4..79573be 100644 --- a/locales/ru.json +++ b/locales/ru.json @@ -362,5 +362,81 @@ "err.deploy.task": "Номер задачи указан неверно.", "home.check.visual.pre": "Откройте ", "home.check.visual.post": ": наверху должны быть видны палитра цветными плашками, два шрифта (PT Serif и PT Sans) и образцы публикации и обложки для Telegram и LinkedIn. Рядом с названием написано «черновик», пока Татьяна документ не утвердила.", - "home.page.visual": "Палитра, шрифты и образцы публикаций и обложек для Telegram и LinkedIn" + "home.page.visual": "Палитра, шрифты и образцы публикаций и обложек для Telegram и LinkedIn", + "bot.menu.status": "Статус", + "bot.soon.status": "Этот раздел скоро появится.", + "bot.menu.strategy": "Стратегия", + "bot.soon.strategy": "Этот раздел скоро появится.", + "bot.menu.approvals": "Согласования", + "bot.soon.approvals": "Этот раздел скоро появится.", + "bot.menu.plan": "Контент-план", + "bot.soon.plan": "Этот раздел скоро появится.", + "bot.menu.channels": "Каналы", + "bot.soon.channels": "Этот раздел скоро появится.", + "bot.menu.pr": "PR и лиды", + "bot.soon.pr": "Этот раздел скоро появится.", + "bot.menu.reports": "Отчёты", + "bot.soon.reports": "Этот раздел скоро появится.", + "bot.menu.tasks": "Задачи", + "bot.soon.tasks": "Этот раздел скоро появится.", + "bot.menu.settings": "Настройки", + "bot.soon.settings": "Этот раздел скоро появится.", + "bot.menu.pause": "Пауза", + "bot.soon.pause": "Этот раздел скоро появится.", + "bot.off": "Отправка выключена: ключ бота ещё не получен.", + "bot.none": "не указано", + "bot.on": "включён", + "bot.offShort": "выключен", + "bot.paused": "на паузе", + "bot.running": "работает", + "bot.hello": "Здравствуйте! Выберите раздел в меню.", + "bot.denied": "Этот бот отвечает только владельцу.", + "bot.bind.ask": "Чтобы подключить бота, напишите секретное слово для одобрения.", + "bot.bind.wrong": "Слово не подошло. Попробуйте ещё раз.", + "bot.bind.done": "Готово, бот подключён к вашему аккаунту.", + "bot.bind.noWord": "Секретное слово ещё не задано. Задайте его на сайте и вернитесь сюда.", + "bot.status": "Ждут вашего решения: {wait}. Отправка: {state}.", + "bot.approvals.empty": "Сейчас нечего согласовывать.", + "bot.plan.empty": "В контент-плане пока нет записей с датой.", + "bot.pause.done": "Все отправки остановлены.", + "bot.resume": "Возобновить", + "bot.resume.done": "Отправки снова включены.", + "bot.card.text": "Текст", + "bot.card.channel": "Канал", + "bot.card.date": "Дата", + "bot.card.risk": "Уровень риска", + "bot.card.riskNone": "не оценён", + "bot.card.sources": "Источники фактов", + "bot.card.sourcesNone": "не указаны", + "bot.card.status": "Статус", + "bot.card.history": "История", + "bot.st.draft": "черновик", + "bot.st.review": "на согласовании", + "bot.st.approved": "согласовано", + "bot.st.published": "опубликовано", + "bot.act.approve": "Утвердить", + "bot.act.rework": "Доработать", + "bot.act.reject": "Отклонить", + "bot.act.schedule": "Запланировать", + "bot.act.now": "Опубликовать сейчас", + "bot.act.more": "Подробнее", + "bot.ask.rework": "Напишите, что доработать.", + "bot.ask.reject": "Напишите, почему отклоняете.", + "bot.rejected": "Отклонено", + "bot.done.approve": "Утверждено.", + "bot.done.rework": "Вернули в черновик с вашим комментарием.", + "bot.done.reject": "Отклонено и возвращено в черновик.", + "bot.done.schedule": "Запланировано на {date}.", + "bot.done.now": "Опубликовано.", + "bot.err.notFound": "Запись не найдена.", + "bot.err.notAllowed": "Сейчас это действие недоступно.", + "bot.err.send": "Не отправлено: {why}.", + "bot.why.stopped": "отправки на паузе", + "bot.why.limit": "достигнут дневной лимит", + "bot.why.other": "канал недоступен", + "bot.voice.fail": "Не удалось распознать голос. Напишите текстом.", + "bot.voice.confirm": "Я услышал: «{text}». Верно?", + "bot.voice.yes": "Верно", + "bot.voice.no": "Нет", + "bot.voice.again": "Хорошо, скажите ещё раз." } diff --git a/src/bot.js b/src/bot.js new file mode 100644 index 0000000..68fa6f3 --- /dev/null +++ b/src/bot.js @@ -0,0 +1,170 @@ +// 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; } }; +} diff --git a/src/server.js b/src/server.js index 817d36f..f633737 100644 --- a/src/server.js +++ b/src/server.js @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; import { STAGES, TYPES, createStore } from "./opportunities.js"; import { PERIODS, buildSummary, createMetricsStore, isDate as isDay } from "./metrics.js"; import { createTelegram } from "./telegram.js"; +import { createBot, createBotStore, mockTranscriber } from "./bot.js"; import { createPublisher } from "./publisher.js"; import { runDue, sendSummary } from "./summary-schedule.js"; import { createLetters, letterView } from "./letters.js"; @@ -24,7 +25,7 @@ const PAGES = ["/plan.html", "/opportunities.html", "/summary.html", "/market.ht const ROOT = path.dirname(fileURLToPath(import.meta.url)); -export function createApp({ file, oppsFile, metricsFile, telegram = createTelegram(), draftWriter = mockDraftWriter, ownerCode = process.env.OWNER_CODE, deploySecret = process.env.DEPLOY_STATUS_SECRET }) { +export function createApp({ file, oppsFile, metricsFile, telegram = createTelegram(), draftWriter = mockDraftWriter, ownerCode = process.env.OWNER_CODE, deploySecret = process.env.DEPLOY_STATUS_SECRET, webhookSecret = process.env.TELEGRAM_WEBHOOK_SECRET, transcriber = mockTranscriber() }) { const deploy = createDeployStatus(path.join(path.dirname(file), "deploy-status.json")); const letters = createLetters(path.join(path.dirname(file), "letters.json")); const owner = createOwner(path.join(path.dirname(file), "owner.json"), ownerCode); @@ -47,6 +48,8 @@ export function createApp({ file, oppsFile, metricsFile, telegram = createTelegr fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(plan, null, 2)); }; + // BRM-52: бот владельца. Распознавание речи — мок, пока нет ключа сервиса. + const bot = createBot({ store: createBotStore(path.join(path.dirname(file), "bot.json")), telegram, pub, owner, getPlan: () => plan, savePlan: save, transcriber }); // Состояние плана с материалами; идея с датой без материалов помечается noAssets. const state = () => { const s = buildState(plan); @@ -276,6 +279,12 @@ export function createApp({ file, oppsFile, metricsFile, telegram = createTelegr if (req.method === "GET" && url === "/assets.html") return send(200, fs.readFileSync(path.join(ROOT, "../public/assets.html"), "utf8"), "text/html"); let body = {}; + if (req.method === "POST" && url === "/api/telegram/webhook") { + let raw = ""; + for await (const c of req) raw += c; + if (!webhookSecret || !tokenOk(req.headers["x-telegram-bot-api-secret-token"], webhookSecret)) return send(403, { error: "denied" }); + try { return send(200, await bot.handleUpdate(JSON.parse(raw))); } catch { return send(200, { ok: false }); } + } if (req.method === "POST" || req.method === "PUT") { let raw = ""; for await (const c of req) raw += c; diff --git a/src/telegram.js b/src/telegram.js index 7308fd9..8875a3e 100644 --- a/src/telegram.js +++ b/src/telegram.js @@ -4,6 +4,11 @@ export function createTelegram({ token = process.env.TELEGRAM_BOT_TOKEN, chatId channel: "telegram", secrets: () => [token].filter(Boolean), connected: () => Boolean(token && chatId), + async call(method, payload) { + if (!token) return null; // отправка выключена, пока нет ключа бота + const r = await fetchImpl(`https://api.telegram.org/bot${token}/${method}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }); + return (await r.json()).result ?? null; + }, async send(text) { if (!token || !chatId) throw new Error("нет доступов к Telegram"); const r = await fetchImpl(`https://api.telegram.org/bot${token}/sendMessage`, { @@ -26,6 +31,8 @@ export function mockTelegram({ fail } = {}) { sent, secrets: () => ["MOCK_TOKEN"], connected: () => true, + calls: [], + async call(method, payload) { this.calls.push({ method, ...payload }); return { message_id: this.calls.length }; }, async send(text) { if (fail) throw new Error(fail); const m = { message_id: sent.length + 1, text };