Files
brov-macbook/ops/brovops/app.py
T
maksarsanjeev e47b97a462 ops: dates shown as DD.MM.YYYY (bot, digest, reminders, BroV)
Storage and the API stay ISO; ru_day() formats every user-facing date, Claude is asked
to write dates in its replies the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 03:21:24 +03:00

344 lines
13 KiB
Python

"""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 . 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"),
"claude": os.environ.get("CLAUDE_BIN", "claude"),
"model": os.environ.get("CLAUDE_MODEL", "haiku"),
"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):
for i in range(0, len(text), 3800):
await update.effective_message.reply_text(text[i:i + 3800], parse_mode=ParseMode.HTML, **kw)
@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):
await send_long(update, fmt.agenda(locked(ops.agenda)))
@owner_only
async def cmd_tasks(update: Update, ctx):
lines = fmt.tree(locked(ops.task_tree))
await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌")
@owner_only
async def cmd_subs(update: Update, ctx):
with lock:
text = fmt.subs(ops.subs(), ops.monthly_cost(), 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 "Таймер не шёл.")
async def think(update: Update, text: str):
msg = await update.effective_message.reply_text("🤔 думаю…")
try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"])
except OpsError as e:
answer = f"Не получилось: {e}"
except Exception as e: # Claude timeout, CLI missing…
log.exception("brain")
answer = f"Ошибка: {e.__class__.__name__}"
await msg.edit_text(answer[:4000])
@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
action, kind, ref = q.data.split(":")
ref = int(ref)
try:
with lock:
if action == "done":
if kind == "task":
note = f"✓ Сделано: {ops.complete_task(ref)['title']}"
elif kind == "sub":
s = ops.pay_sub(ref)
note = f"₽ Оплачено: {s['name']}, следующее списание {ru_day(s['next_date'])}"
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}"
await q.answer()
await q.edit_message_text(q.message.text + "\n\n" + note)
# 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))
async def api_subs(request):
check_auth(request)
with lock:
return ok({"subs": ops.subs(), "monthly_cost": ops.monthly_cost()})
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["claude"], 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 Claude 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_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)])
return app
# 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()
builder = Application.builder().token(CFG["token"])
if CFG["proxy"]:
builder = builder.proxy(CFG["proxy"]).get_updates_proxy(CFG["proxy"])
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))
async with tg:
await tg.start()
await tg.updater.start_polling(drop_pending_updates=False)
asyncio.create_task(reminder_loop(tg.bot))
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())