ops: BroV Ops service for the homelab VM (tasks, subscriptions, routines)
- SQLite: tasks with subtasks and time tracking, subscriptions + payments, routines + history, reminder log. All rules in core.Ops (tested: ops/tests). - brain: free text → JSON actions via the local claude CLI (Haiku, the subscription); only whitelisted operations are applied, nothing is deleted. - Telegram bot (owner only): text and voice (faster-whisper on the VM), /today /tasks /subs /routines /stop, morning digest and daily reminders with Done/Paid/Tomorrow. - HTTP API for BroV (bearer token): agenda, tasks, subs, routines, say, action. - deploy/install.sh: user brovops, venv, systemd; a proxy-only mihomo (127.0.0.1:7890, checksum-verified) so Telegram and Claude work from Russia without a VPN on the VM. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,312 @@
|
||||
"""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
|
||||
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_only(handler):
|
||||
async def wrapped(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
|
||||
chat = update.effective_chat
|
||||
if not chat or chat.id != CFG["owner"]:
|
||||
if update.message and update.message.text == "/start":
|
||||
await update.message.reply_text(
|
||||
f"Это личный бот. Твой chat id: {chat.id if chat else '?'} — "
|
||||
"впиши его в OWNER_CHAT_ID на сервере и перезапусти службу.")
|
||||
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
|
||||
try:
|
||||
await f.download_to_drive(path)
|
||||
text = await asyncio.to_thread(voice.transcribe, path, CFG["whisper"])
|
||||
finally:
|
||||
os.unlink(path)
|
||||
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 != CFG["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']}, следующее списание {s['next_date']}"
|
||||
else:
|
||||
r = ops.done_routine(ref)
|
||||
note = f"✓ {r['title']}: следующий раз {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)
|
||||
if CFG["owner"] 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(CFG["owner"], "☀️ Доброе утро! " + fmt.agenda(agenda),
|
||||
parse_mode=ParseMode.HTML)
|
||||
locked(ops.mark_reminded, "digest", 0)
|
||||
today = ops.today()
|
||||
for it in items:
|
||||
await bot.send_message(CFG["owner"], "Напоминание: " + 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")
|
||||
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()
|
||||
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())
|
||||
Reference in New Issue
Block a user