"""BroV Ops — one process: Telegram bot (text + voice), a small HTTP API for BroV on the home network, and the reminder loop. Configuration comes from the environment (/etc/brov-ops/config.env, see deploy/config.env.example).""" import asyncio import hmac import json import logging import os import tempfile import threading from datetime import datetime from aiohttp import web from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update from telegram.constants import ParseMode from telegram.ext import (Application, CallbackQueryHandler, CommandHandler, ContextTypes, MessageHandler, filters) from telegram.request import HTTPXRequest from . import brain, fmt, voice from .core import Ops, OpsError, ru_day from .db import connect log = logging.getLogger("brovops") CFG = { "token": os.environ.get("TELEGRAM_TOKEN", ""), "owner": int(os.environ.get("OWNER_CHAT_ID", "0") or 0), "api_token": os.environ.get("API_TOKEN", ""), "api_bind": os.environ.get("API_BIND", "0.0.0.0"), "api_port": int(os.environ.get("API_PORT", "8787")), "db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"), "tz": os.environ.get("TZ_NAME", "Europe/Moscow"), "kimi": os.environ.get("KIMI_BIN", "kimi"), "model": os.environ.get("KIMI_MODEL", ""), "whisper": os.environ.get("WHISPER_MODEL", "small"), "digest_hour": int(os.environ.get("DIGEST_HOUR", "9")), "quiet_from": int(os.environ.get("QUIET_FROM", "22")), "proxy": os.environ.get("TELEGRAM_PROXY", ""), } ops = Ops(connect(CFG["db"]), CFG["tz"]) lock = threading.Lock() # one SQLite connection shared by the bot, the API and the loop def locked(fn, *a, **kw): with lock: return fn(*a, **kw) # MARK: - Telegram def owner() -> int: """OWNER_CHAT_ID, or whoever sent /start first (saved in the database).""" if CFG["owner"]: return CFG["owner"] with lock: row = ops.con.execute("SELECT value FROM settings WHERE key = 'owner'").fetchone() return int(row["value"]) if row else 0 def claim_owner(chat_id: int) -> bool: with lock: if CFG["owner"] or ops.con.execute("SELECT 1 FROM settings WHERE key = 'owner'").fetchone(): return False ops.con.execute("INSERT INTO settings (key, value) VALUES ('owner', ?)", (str(chat_id),)) log.info("owner claimed: %s", chat_id) return True def owner_only(handler): async def wrapped(update: Update, ctx: ContextTypes.DEFAULT_TYPE): chat = update.effective_chat if chat and update.message and update.message.text == "/start" and claim_owner(chat.id): await update.message.reply_text("Готово: этот чат — владелец бота. Чужим он отвечать не будет.") if not chat or chat.id != owner(): if update.message and update.message.text == "/start": await update.message.reply_text("Это личный бот.") return await handler(update, ctx) return wrapped async def send_long(update: Update, text: str, **kw): """Splits long text; extra kwargs (buttons) go only on the last chunk.""" chunks = [text[i:i + 3800] for i in range(0, len(text), 3800)] or [""] for i, chunk in enumerate(chunks): last = i == len(chunks) - 1 await update.effective_message.reply_text(chunk, parse_mode=ParseMode.HTML, **(kw if last else {})) def one_task_buttons(task_id: int) -> InlineKeyboardMarkup: """Buttons under a single task card — same callbacks as reminders.""" return InlineKeyboardMarkup([[ InlineKeyboardButton("✓ Сделано", callback_data=f"done:task:{task_id}"), InlineKeyboardButton("⏰ Перенести", callback_data=f"snooze:task:{task_id}")]]) def flat_tasks(tree: list) -> list: """[(task, depth)] in display order.""" out = [] def walk(nodes, depth): for n in nodes: out.append((n, depth)) walk(n["children"], depth + 1) walk(tree, 0) return out async def send_task_cards(update: Update, tree: list, limit: int = 12): """Every open task as its own message: task text, then Сделано / Перенести.""" tasks = flat_tasks(tree) today = ops.today() for t, depth in tasks[:limit]: await update.effective_message.reply_text(fmt.task_line(t, depth, today), parse_mode=ParseMode.HTML, reply_markup=one_task_buttons(t["id"])) if len(tasks) > limit: await update.effective_message.reply_text(f"…и ещё {len(tasks) - limit}. Повтори /tasks.") @owner_only async def cmd_start(update: Update, ctx): await update.message.reply_text( "Привет! Пиши или говори голосом, что сделать: «продлить домен до 15 ноября», " "«подписка хостинг 900 ₽ в месяц, списание 20-го», «бэкап NAS раз в неделю», " "«начал чинить принтер в Саге».\n\n/today — что горит · /tasks — задачи · /subs — подписки · " "/routines — регламент · /stop — остановить таймер") @owner_only async def cmd_today(update: Update, ctx): with lock: agenda, tree = ops.agenda(), ops.task_tree() await send_long(update, fmt.agenda(agenda)) await send_task_cards(update, tree) @owner_only async def cmd_tasks(update: Update, ctx): with lock: tree = ops.task_tree() if not tree: await update.effective_message.reply_text("Открытых задач нет 👌") return await update.effective_message.reply_text( f"Открытые задачи ({len(flat_tasks(tree))}) — по одной, жми Сделано или Перенести:") await send_task_cards(update, tree) @owner_only async def cmd_subs(update: Update, ctx): with lock: text = fmt.subs(ops.subs(), ops.monthly_by_client(), ops.today()) await send_long(update, text) @owner_only async def cmd_routines(update: Update, ctx): with lock: text = fmt.routines(ops.routines(), ops.today()) await send_long(update, text) @owner_only async def cmd_stop(update: Update, ctx): t = locked(ops.stop_timer) await update.message.reply_text(f"⏹ Остановил: {t['title']}" if t else "Таймер не шёл.") def repeat_buttons(sub: dict) -> InlineKeyboardMarkup: return InlineKeyboardMarkup([[ InlineKeyboardButton(f"🔁 Да, {ru_day(sub['next_if_repeat'])}", callback_data=f"rep:sub:{sub['id']}:1"), InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]]) # Free-text asks that should end with the task list's buttons (nothing was changed, just shown). LIST_HINTS = ("задач", "дела", "делы", "делах", "план", "список", "что там", "что горит", "today", "tasks", "агенда") async def think(update: Update, text: str): msg = await update.effective_message.reply_text("🤔 думаю…") paid: list = [] try: answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"], paid) except OpsError as e: answer = f"Не получилось: {e}" except Exception as e: # Kimi timeout, CLI missing… log.exception("brain") answer = f"Ошибка: {e.__class__.__name__}" await msg.edit_text(answer[:4000]) if "✓" not in answer and any(h in text.lower() for h in LIST_HINTS): await send_task_cards(update, locked(ops.task_tree)) for sid in paid: # paid by text: ask «repeat?» with buttons s = locked(ops.sub, sid) if s["paid"] and s["active"]: await update.effective_message.reply_text(f"₽ {s['name']} оплачена. Повторить?", reply_markup=repeat_buttons(s)) @owner_only async def on_text(update: Update, ctx): await think(update, update.message.text) @owner_only async def on_voice(update: Update, ctx): v = update.message.voice or update.message.audio f = await v.get_file() with tempfile.NamedTemporaryFile(suffix=".ogg", delete=False) as tmp: path = tmp.name note = await update.message.reply_text("🎧 слушаю…") try: await f.download_to_drive(path) text = await asyncio.to_thread(voice.transcribe, path, CFG["whisper"]) except Exception as e: log.exception("voice") await note.edit_text(f"Не смог распознать голосовое: {e.__class__.__name__}. Напиши текстом?") return finally: os.unlink(path) await note.delete() if not text: await update.message.reply_text("Не расслышал, повтори?") return await update.message.reply_text(f"🎤 {text}") await think(update, text) def reminder_buttons(it: dict) -> InlineKeyboardMarkup: kind, ref = it["kind"], it["id"] first = {"task": "✓ Сделано", "sub": "₽ Оплачено?", "routine": "✓ Сделано"}[kind] return InlineKeyboardMarkup([[InlineKeyboardButton(first, callback_data=f"done:{kind}:{ref}"), InlineKeyboardButton("⏰ Завтра", callback_data=f"snooze:{kind}:{ref}")]]) async def on_button(update: Update, ctx): q = update.callback_query if not q or q.message.chat.id != owner(): return parts = q.data.split(":") action, kind, ref = parts[0], parts[1], int(parts[2]) markup = None try: with lock: if action == "rep": s = ops.repeat_sub(ref, parts[3] == "1") note = (f"🔁 Следующее списание {ru_day(s['next_date'])}" if s["active"] else "✓ Закрыта, больше не повторяется") elif action == "done": if kind == "task": note = f"✓ Сделано: {ops.complete_task(ref)['title']}" elif kind == "sub": s = ops.pay_sub(ref) note = f"₽ Оплачено. Повторить {ru_day(s['next_if_repeat'])}?" markup = repeat_buttons(s) else: r = ops.done_routine(ref) note = f"✓ {r['title']}: следующий раз {ru_day(r['next_date'])}" else: ops.snooze(kind, ref, 1) note = "⏰ Напомню завтра" except OpsError as e: note = f"Не получилось: {e}" if action in ("done", "snooze") and kind == "task" and q.message.reply_markup: # Task-list message (several task rows): drop the row just handled, keep the rest tappable. # A single-row reminder keyboard is removed entirely, as before. kb = q.message.reply_markup.inline_keyboard if len(kb) > 1: rows = [row for row in kb if not any(b.callback_data == f"{action}:task:{ref}" for b in row)] markup = InlineKeyboardMarkup(rows) if rows else None await q.answer() await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup) # MARK: - Reminders async def reminder_loop(bot): """Every 5 minutes: the morning digest once a day, then each due item once a day, only between DIGEST_HOUR and QUIET_FROM.""" while True: try: now = datetime.now(ops.tz) chat = owner() if chat and CFG["digest_hour"] <= now.hour < CFG["quiet_from"]: with lock: digest_due = not ops.con.execute( "SELECT 1 FROM reminders_sent WHERE kind = 'digest' AND day = ?", (ops.today().isoformat(),)).fetchone() agenda = ops.agenda() if digest_due else None items = ops.due_reminders() if digest_due: await bot.send_message(chat, "☀️ Доброе утро! " + fmt.agenda(agenda), parse_mode=ParseMode.HTML) locked(ops.mark_reminded, "digest", 0) today = ops.today() for it in items: await bot.send_message(chat, "Напоминание: " + fmt.item_line(it, today), parse_mode=ParseMode.HTML, reply_markup=reminder_buttons(it)) locked(ops.mark_reminded, it["kind"], it["id"]) except Exception: log.exception("reminders") await asyncio.sleep(300) # MARK: - HTTP API for BroV def check_auth(request: web.Request) -> None: got = request.headers.get("Authorization", "").removeprefix("Bearer ").strip() if not CFG["api_token"] or not hmac.compare_digest(got, CFG["api_token"]): raise web.HTTPUnauthorized(text="bad token") def ok(data) -> web.Response: return web.json_response(data, dumps=lambda o: json.dumps(o, ensure_ascii=False)) async def api_agenda(request): check_auth(request) return ok(locked(ops.agenda)) async def api_tasks(request): check_auth(request) return ok(locked(ops.task_tree, request.query.get("all") == "1")) async def api_subs(request): check_auth(request) with lock: return ok({"subs": ops.subs(active_only=request.query.get("all") != "1"), "monthly_cost": ops.monthly_cost(), "by_client": ops.monthly_by_client()}) async def api_routines(request): check_auth(request) return ok(locked(ops.routines)) async def api_say(request): """Free text from BroV's notch: the same brain as Telegram.""" check_auth(request) body = await request.json() text = str(body.get("text", "")).strip() if not text: raise web.HTTPBadRequest(text="empty") try: answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"]) except OpsError as e: return ok({"ok": False, "answer": str(e)}) return ok({"ok": True, "answer": answer}) async def api_action(request): """One direct action from a BroV button (done, paid, timer…), no Kimi involved.""" check_auth(request) body = await request.json() if body.get("op") == "snooze": locked(ops.snooze, str(body.get("kind")), int(body.get("id")), int(body.get("days", 1))) return ok({"ok": True, "result": ["⏰ отложено"]}) with lock: result = brain.apply_plan(ops, {"actions": [body]}) return ok({"ok": not any(r.startswith("✗") for r in result), "result": result}) async def api_delete(request): """Delete by an explicit click in BroV (Kimi never deletes).""" check_auth(request) body = await request.json() kind, ref = str(body.get("kind")), int(body.get("id")) fn = {"task": ops.delete_task, "sub": ops.delete_sub, "routine": ops.delete_routine}.get(kind) if not fn: raise web.HTTPBadRequest(text="kind") try: locked(fn, ref) except OpsError as e: return ok({"ok": False, "result": [str(e)]}) return ok({"ok": True, "result": ["🗑 удалено"]}) async def api_health(request): return ok({"ok": True}) def make_api() -> web.Application: app = web.Application(client_max_size=64 * 1024) app.add_routes([web.get("/api/health", api_health), web.get("/api/agenda", api_agenda), web.get("/api/tasks", api_tasks), web.get("/api/subs", api_subs), web.get("/api/routines", api_routines), web.post("/api/say", api_say), web.post("/api/action", api_action), web.post("/api/delete", api_delete)]) return app # MARK: - Polling watchdog # # 12.10.2026: one ConnectError through the proxy left getUpdates hanging on a dead # connection (CLOSE-WAIT) for 1.5 days — reminders still went out, incoming messages # didn't. Every successful getUpdates is stamped; when none succeeds for 3 minutes the # process exits and systemd starts a fresh one. last_poll_ok = [0.0] class PollRequest(HTTPXRequest): async def do_request(self, url, method, *args, **kwargs): result = await super().do_request(url, method, *args, **kwargs) if url.endswith("/getUpdates") and result[0] == 200: last_poll_ok[0] = asyncio.get_running_loop().time() return result async def poll_watchdog(): loop = asyncio.get_running_loop() last_poll_ok[0] = loop.time() while True: await asyncio.sleep(30) stale = loop.time() - last_poll_ok[0] if stale > 180: log.error("no successful getUpdates for %.0f s — restarting", stale) os._exit(1) # MARK: - Main async def main(): logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") # httpx logs every request URL, and Telegram URLs carry the bot token. logging.getLogger("httpx").setLevel(logging.WARNING) logging.getLogger("httpx2").setLevel(logging.WARNING) runner = web.AppRunner(make_api()) await runner.setup() await web.TCPSite(runner, CFG["api_bind"], CFG["api_port"]).start() log.info("API on %s:%s", CFG["api_bind"], CFG["api_port"]) if not CFG["token"]: log.warning("TELEGRAM_TOKEN not set: API only") await asyncio.Event().wait() proxy = CFG["proxy"] or None builder = (Application.builder().token(CFG["token"]) .request(HTTPXRequest(proxy=proxy, connect_timeout=10, read_timeout=20, write_timeout=20, pool_timeout=10, connection_pool_size=8)) .get_updates_request(PollRequest(proxy=proxy, connect_timeout=10, read_timeout=40, write_timeout=10, pool_timeout=10))) tg = builder.build() async def on_error(update, ctx): log.error("handler failed", exc_info=ctx.error) tg.add_error_handler(on_error) tg.add_handler(CommandHandler("start", cmd_start)) tg.add_handler(CommandHandler("today", cmd_today)) tg.add_handler(CommandHandler("tasks", cmd_tasks)) tg.add_handler(CommandHandler("subs", cmd_subs)) tg.add_handler(CommandHandler("routines", cmd_routines)) tg.add_handler(CommandHandler("stop", cmd_stop)) tg.add_handler(CallbackQueryHandler(on_button)) tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice)) tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text)) # A Telegram/proxy outage must not kill the API, calendar and reminders. Keep the # process alive and retry Telegram; systemd restart is still reserved for the polling # watchdog, which catches a connection that looked established but stopped updating. while True: try: async with tg: await tg.start() await tg.updater.start_polling(drop_pending_updates=False, timeout=25) asyncio.create_task(reminder_loop(tg.bot)) asyncio.create_task(poll_watchdog()) await asyncio.Event().wait() except Exception: log.exception("Telegram unavailable; API remains active, retrying in 30 s") await asyncio.sleep(30) if __name__ == "__main__": asyncio.run(main())