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())
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Free text (typed in BroV or dictated in Telegram) → actions, via the local `claude` CLI
|
||||
(your subscription, no API key). Claude only proposes JSON; every action is checked and
|
||||
carried out by Ops, and anything outside the list below is refused."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
from .core import Ops, OpsError
|
||||
|
||||
INSTRUCTIONS = """Ты — помощник-менеджер системного администратора. Пользователь пишет или говорит
|
||||
по-русски, коротко и неформально. Твоя задача — превратить сообщение в действия над его базой дел.
|
||||
|
||||
Ответь ТОЛЬКО одним JSON-объектом, без пояснений и без ```:
|
||||
{"actions": [ ... ], "reply": "короткий ответ пользователю по-русски"}
|
||||
|
||||
Действия (поле "op"), используй только эти:
|
||||
- add_task {title, due?, client?, notes?, parent_id?, parent_key?, key?}
|
||||
подзадача: parent_id (существующая задача) или parent_key (= key задачи, созданной выше в этом же ответе)
|
||||
- update_task {id, title?, due?, client?, notes?, status?} status: todo | doing | done
|
||||
- complete_task {id}
|
||||
- reopen_task {id}
|
||||
- start_timer {id} засечь время работы над задачей (предыдущий таймер остановится)
|
||||
- stop_timer {}
|
||||
- add_sub {name, amount, next_date, period?, every?, currency?, remind_days?, notes?}
|
||||
period: day | week | month | year (по умолчанию month); currency по умолчанию RUB
|
||||
- update_sub {id, name?, amount?, next_date?, period?, every?, currency?, remind_days?, notes?, active?}
|
||||
- pay_sub {id, amount?, paid_on?} оплачено: следующая дата сдвинется сама
|
||||
- add_routine {title, every_days, next_date?, notes?} регламентное дело (бэкап, обновления…)
|
||||
- done_routine {id, note?}
|
||||
- update_routine {id, title?, every_days?, next_date?, notes?, active?}
|
||||
|
||||
Правила:
|
||||
- Даты — строго ГГГГ-ММ-ДД. «завтра», «в пятницу», «15-го» переводи от сегодняшней даты.
|
||||
- client — одно из: saga, planet9, home, или пусто.
|
||||
- Если пользователь просто спрашивает (что на сегодня, сколько трачу, что просрочено) —
|
||||
actions пустой, ответ в reply по данным ниже.
|
||||
- Если непонятно, что сделать, — actions пустой, в reply переспроси.
|
||||
- Ничего не удаляй. Не выдумывай id — бери только из данных ниже.
|
||||
- reply — 1–3 строки, без markdown-заголовков.
|
||||
"""
|
||||
|
||||
ALLOWED = {"add_task", "update_task", "complete_task", "reopen_task", "start_timer", "stop_timer",
|
||||
"add_sub", "update_sub", "pay_sub", "add_routine", "done_routine", "update_routine"}
|
||||
|
||||
|
||||
def snapshot(ops: Ops) -> str:
|
||||
"""Compact state for the prompt: open tasks (tree), subscriptions, routines."""
|
||||
lines = [f"Сегодня: {ops.today().isoformat()} ({['пн','вт','ср','чт','пт','сб','вс'][ops.today().weekday()]})", "",
|
||||
"Открытые задачи (id, срок, клиент, минуты):"]
|
||||
|
||||
def walk(nodes, depth):
|
||||
for t in nodes:
|
||||
run = " ⏱идёт" if t["running"] else ""
|
||||
lines.append(f"{' ' * depth}- #{t['id']} {t['title']} | {t['due'] or '-'} | {t['client'] or '-'} | "
|
||||
f"{t['minutes']}м | {t['status']}{run}")
|
||||
walk(t["children"], depth + 1)
|
||||
walk(ops.task_tree(), 0)
|
||||
lines += ["", "Подписки (id, сумма, период, следующее списание):"]
|
||||
for s in ops.subs(active_only=False):
|
||||
lines.append(f"- #{s['id']} {s['name']} | {s['amount']:g} {s['currency']} | каждые {s['every']} {s['period']} | "
|
||||
f"{s['next_date']} | {'активна' if s['active'] else 'выкл'}")
|
||||
lines.append(f"Итого в месяц: {ops.monthly_cost()}")
|
||||
lines += ["", "Регламентные дела (id, раз в N дней, следующий раз, последний раз):"]
|
||||
for r in ops.routines():
|
||||
lines.append(f"- #{r['id']} {r['title']} | {r['every_days']}д | {r['next_date']} | {r['last_done'] or '-'}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def ask_claude(prompt: str, claude_bin: str = "claude", model: str = "haiku", timeout: int = 90) -> str:
|
||||
env = {k: v for k, v in os.environ.items() if k not in ("CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT")}
|
||||
with tempfile.TemporaryDirectory(prefix="brovops-") as cwd: # nothing to read there
|
||||
p = subprocess.run(
|
||||
[claude_bin, "-p", prompt, "--model", model, "--output-format", "json",
|
||||
"--permission-mode", "plan", "--append-system-prompt", INSTRUCTIONS],
|
||||
cwd=cwd, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)
|
||||
if p.returncode != 0:
|
||||
raise OpsError("Claude не ответил: " + (p.stderr or p.stdout).strip()[-300:])
|
||||
try:
|
||||
return json.loads(p.stdout).get("result", "")
|
||||
except json.JSONDecodeError:
|
||||
return p.stdout
|
||||
|
||||
|
||||
def parse_plan(text: str) -> dict:
|
||||
a, b = text.find("{"), text.rfind("}")
|
||||
if a < 0 or b <= a:
|
||||
raise OpsError("Claude ответил не JSON-ом")
|
||||
plan = json.loads(text[a:b + 1])
|
||||
if not isinstance(plan, dict) or not isinstance(plan.get("actions", []), list):
|
||||
raise OpsError("Claude ответил не в том формате")
|
||||
return plan
|
||||
|
||||
|
||||
def apply_plan(ops: Ops, plan: dict) -> list[str]:
|
||||
"""Carries out the actions in order; returns one human line per action."""
|
||||
done, keys = [], {}
|
||||
for a in plan.get("actions", []):
|
||||
op = a.get("op") if isinstance(a, dict) else None
|
||||
if op not in ALLOWED:
|
||||
done.append(f"✗ пропущено неизвестное действие {op!r}")
|
||||
continue
|
||||
args = {k: v for k, v in a.items() if k not in ("op", "key", "parent_key")}
|
||||
try:
|
||||
if op == "add_task":
|
||||
if a.get("parent_key"):
|
||||
args["parent_id"] = keys.get(a["parent_key"])
|
||||
t = ops.add_task(**_only(args, "title", "due", "client", "notes", "parent_id"))
|
||||
if a.get("key"):
|
||||
keys[a["key"]] = t["id"]
|
||||
done.append(f"+ задача #{t['id']} {t['title']}" + (f" (подзадача #{t['parent_id']})" if t["parent_id"] else "")
|
||||
+ (f", срок {t['due']}" if t["due"] else ""))
|
||||
elif op == "update_task":
|
||||
t = ops.update_task(int(a["id"]), **_only(args, "title", "due", "client", "notes", "status"))
|
||||
done.append(f"✎ задача #{t['id']} {t['title']}")
|
||||
elif op == "complete_task":
|
||||
t = ops.complete_task(int(a["id"]))
|
||||
done.append(f"✓ сделано: #{t['id']} {t['title']}")
|
||||
elif op == "reopen_task":
|
||||
t = ops.reopen_task(int(a["id"]))
|
||||
done.append(f"↺ снова в работе: #{t['id']} {t['title']}")
|
||||
elif op == "start_timer":
|
||||
t = ops.start_timer(int(a["id"]))
|
||||
done.append(f"⏱ таймер: #{t['id']} {t['title']}")
|
||||
elif op == "stop_timer":
|
||||
t = ops.stop_timer()
|
||||
done.append(f"⏹ таймер остановлен" + (f": #{t['id']} {t['title']}" if t else " (не шёл)"))
|
||||
elif op == "add_sub":
|
||||
s = ops.add_sub(**_only(args, "name", "amount", "next_date", "period", "every", "currency",
|
||||
"remind_days", "notes"))
|
||||
done.append(f"+ подписка #{s['id']} {s['name']}: {s['amount']:g} {s['currency']}, след. {s['next_date']}")
|
||||
elif op == "update_sub":
|
||||
s = ops.update_sub(int(a["id"]), **_only(args, "name", "amount", "next_date", "period", "every",
|
||||
"currency", "remind_days", "notes", "active"))
|
||||
done.append(f"✎ подписка #{s['id']} {s['name']}")
|
||||
elif op == "pay_sub":
|
||||
s = ops.pay_sub(int(a["id"]), a.get("amount"), a.get("paid_on"))
|
||||
done.append(f"₽ оплачено: {s['name']}, следующее списание {s['next_date']}")
|
||||
elif op == "add_routine":
|
||||
r = ops.add_routine(**_only(args, "title", "every_days", "next_date", "notes"))
|
||||
done.append(f"+ регламент #{r['id']} {r['title']}: раз в {r['every_days']} дн., след. {r['next_date']}")
|
||||
elif op == "done_routine":
|
||||
r = ops.done_routine(int(a["id"]), a.get("note", ""))
|
||||
done.append(f"✓ {r['title']}: следующий раз {r['next_date']}")
|
||||
elif op == "update_routine":
|
||||
r = ops.update_routine(int(a["id"]), **_only(args, "title", "every_days", "next_date", "notes", "active"))
|
||||
done.append(f"✎ регламент #{r['id']} {r['title']}")
|
||||
except (OpsError, KeyError, TypeError, ValueError) as e:
|
||||
done.append(f"✗ {op}: {e}")
|
||||
return done
|
||||
|
||||
|
||||
def _only(d: dict, *keys) -> dict:
|
||||
return {k: d[k] for k in keys if k in d}
|
||||
|
||||
|
||||
def handle_text(ops: Ops, text: str, lock, claude_bin: str = "claude", model: str = "haiku") -> str:
|
||||
"""One message in, one answer out (actions taken + Claude's reply). The database lock
|
||||
is held only while reading the state and applying the actions, not while Claude thinks."""
|
||||
with lock:
|
||||
prompt = snapshot(ops) + "\n\nСообщение пользователя:\n" + text.strip()
|
||||
plan = parse_plan(ask_claude(prompt, claude_bin, model))
|
||||
with lock:
|
||||
lines = apply_plan(ops, plan)
|
||||
reply = str(plan.get("reply", "")).strip()
|
||||
return "\n".join(([reply] if reply else []) + lines) or "Готово."
|
||||
@@ -0,0 +1,356 @@
|
||||
"""Everything BroV Ops can do with the data. The Telegram bot, the BroV API and the
|
||||
Claude "brain" all go through this class, so the rules live in one place."""
|
||||
import calendar
|
||||
import sqlite3
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
PERIODS = ("day", "week", "month", "year")
|
||||
STATUSES = ("todo", "doing", "done")
|
||||
|
||||
|
||||
class OpsError(ValueError):
|
||||
"""A request that can't be carried out (shown to the user as is)."""
|
||||
|
||||
|
||||
def add_period(d: date, period: str, every: int = 1) -> date:
|
||||
if period == "day":
|
||||
return d + timedelta(days=every)
|
||||
if period == "week":
|
||||
return d + timedelta(weeks=every)
|
||||
if period == "month":
|
||||
m = d.month - 1 + every
|
||||
y, m = d.year + m // 12, m % 12 + 1
|
||||
return date(y, m, min(d.day, calendar.monthrange(y, m)[1]))
|
||||
if period == "year":
|
||||
y = d.year + every
|
||||
return date(y, d.month, min(d.day, calendar.monthrange(y, d.month)[1]))
|
||||
raise OpsError(f"неизвестный период: {period}")
|
||||
|
||||
|
||||
def parse_day(s) -> date | None:
|
||||
if s in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(str(s)[:10])
|
||||
except ValueError:
|
||||
raise OpsError(f"не понял дату: {s} (нужно ГГГГ-ММ-ДД)")
|
||||
|
||||
|
||||
class Ops:
|
||||
def __init__(self, con: sqlite3.Connection, tz: str = "Europe/Moscow"):
|
||||
self.con = con
|
||||
self.tz = ZoneInfo(tz)
|
||||
|
||||
def today(self) -> date:
|
||||
return datetime.now(self.tz).date()
|
||||
|
||||
# MARK: - Tasks
|
||||
|
||||
def task(self, task_id: int) -> dict:
|
||||
row = self.con.execute("SELECT * FROM tasks WHERE id = ?", (task_id,)).fetchone()
|
||||
if not row:
|
||||
raise OpsError(f"задачи #{task_id} нет")
|
||||
return dict(row)
|
||||
|
||||
def add_task(self, title: str, parent_id: int | None = None, due=None, client: str = "",
|
||||
notes: str = "") -> dict:
|
||||
title = (title or "").strip()
|
||||
if not title:
|
||||
raise OpsError("у задачи нет названия")
|
||||
if parent_id is not None:
|
||||
self.task(parent_id)
|
||||
d = parse_day(due)
|
||||
cur = self.con.execute(
|
||||
"INSERT INTO tasks (parent_id, title, due, client, notes) VALUES (?, ?, ?, ?, ?)",
|
||||
(parent_id, title, d.isoformat() if d else None, client or "", notes or ""))
|
||||
return self.task(cur.lastrowid)
|
||||
|
||||
def update_task(self, task_id: int, **fields) -> dict:
|
||||
allowed = {"title", "notes", "client", "due", "status", "parent_id"}
|
||||
sets, vals = [], []
|
||||
for k, v in fields.items():
|
||||
if k not in allowed or v is None:
|
||||
continue
|
||||
if k == "due":
|
||||
d = parse_day(v)
|
||||
v = d.isoformat() if d else None
|
||||
if k == "status" and v not in STATUSES:
|
||||
raise OpsError(f"статус может быть только {', '.join(STATUSES)}")
|
||||
sets.append(f"{k} = ?")
|
||||
vals.append(v)
|
||||
if sets:
|
||||
self.task(task_id)
|
||||
self.con.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", (*vals, task_id))
|
||||
if fields.get("status") == "done":
|
||||
self._finish(task_id)
|
||||
return self.task(task_id)
|
||||
|
||||
def complete_task(self, task_id: int) -> dict:
|
||||
self.task(task_id)
|
||||
self._finish(task_id)
|
||||
return self.task(task_id)
|
||||
|
||||
def _finish(self, task_id: int):
|
||||
"""Done with all subtasks; a running timer stops."""
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
ids = [task_id] + [r["id"] for r in self._descendants(task_id)]
|
||||
for i in ids:
|
||||
self.con.execute("UPDATE tasks SET status = 'done', done_at = COALESCE(done_at, ?) WHERE id = ?", (now, i))
|
||||
self.con.execute("UPDATE time_entries SET stopped = ? WHERE task_id = ? AND stopped IS NULL", (now, i))
|
||||
|
||||
def reopen_task(self, task_id: int) -> dict:
|
||||
self.task(task_id)
|
||||
self.con.execute("UPDATE tasks SET status = 'todo', done_at = NULL WHERE id = ?", (task_id,))
|
||||
return self.task(task_id)
|
||||
|
||||
def delete_task(self, task_id: int) -> None:
|
||||
self.task(task_id)
|
||||
self.con.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
|
||||
|
||||
def _descendants(self, task_id: int) -> list:
|
||||
return self.con.execute("""
|
||||
WITH RECURSIVE sub(id) AS (SELECT id FROM tasks WHERE parent_id = ?
|
||||
UNION ALL SELECT t.id FROM tasks t JOIN sub ON t.parent_id = sub.id)
|
||||
SELECT tasks.* FROM tasks JOIN sub ON tasks.id = sub.id""", (task_id,)).fetchall()
|
||||
|
||||
def task_tree(self, include_done: bool = False) -> list[dict]:
|
||||
"""Open tasks as a tree: [{…task, minutes, running, children: […]}]."""
|
||||
rows = [dict(r) for r in self.con.execute("SELECT * FROM tasks ORDER BY due IS NULL, due, id")]
|
||||
minutes = self._minutes()
|
||||
running = self.running_task_id()
|
||||
by_parent: dict = {}
|
||||
for r in rows:
|
||||
if not include_done and r["status"] == "done":
|
||||
continue
|
||||
r["minutes"] = minutes.get(r["id"], 0)
|
||||
r["running"] = r["id"] == running
|
||||
by_parent.setdefault(r["parent_id"], []).append(r)
|
||||
|
||||
def build(parent):
|
||||
out = []
|
||||
for r in by_parent.get(parent, []):
|
||||
r["children"] = build(r["id"])
|
||||
out.append(r)
|
||||
return out
|
||||
return build(None)
|
||||
|
||||
# MARK: - Time tracking
|
||||
|
||||
def running_task_id(self) -> int | None:
|
||||
row = self.con.execute("SELECT task_id FROM time_entries WHERE stopped IS NULL LIMIT 1").fetchone()
|
||||
return row["task_id"] if row else None
|
||||
|
||||
def start_timer(self, task_id: int) -> dict:
|
||||
"""One timer at a time: starting a task stops the previous one."""
|
||||
t = self.task(task_id)
|
||||
if t["status"] == "done":
|
||||
raise OpsError(f"задача #{task_id} уже сделана")
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
self.con.execute("UPDATE time_entries SET stopped = ? WHERE stopped IS NULL", (now,))
|
||||
self.con.execute("INSERT INTO time_entries (task_id, started) VALUES (?, ?)", (task_id, now))
|
||||
self.con.execute("UPDATE tasks SET status = 'doing' WHERE id = ?", (task_id,))
|
||||
return self.task(task_id)
|
||||
|
||||
def stop_timer(self) -> dict | None:
|
||||
tid = self.running_task_id()
|
||||
if tid is None:
|
||||
return None
|
||||
now = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
self.con.execute("UPDATE time_entries SET stopped = ? WHERE stopped IS NULL", (now,))
|
||||
return self.task(tid)
|
||||
|
||||
def _minutes(self) -> dict[int, int]:
|
||||
now = datetime.now(timezone.utc)
|
||||
out: dict[int, float] = {}
|
||||
for r in self.con.execute("SELECT task_id, started, stopped FROM time_entries"):
|
||||
a = datetime.fromisoformat(r["started"])
|
||||
b = datetime.fromisoformat(r["stopped"]) if r["stopped"] else now
|
||||
out[r["task_id"]] = out.get(r["task_id"], 0) + max(0.0, (b - a).total_seconds() / 60)
|
||||
return {k: int(round(v)) for k, v in out.items()}
|
||||
|
||||
# MARK: - Subscriptions and payments
|
||||
|
||||
def sub(self, sub_id: int) -> dict:
|
||||
row = self.con.execute("SELECT * FROM subscriptions WHERE id = ?", (sub_id,)).fetchone()
|
||||
if not row:
|
||||
raise OpsError(f"подписки #{sub_id} нет")
|
||||
return dict(row)
|
||||
|
||||
def add_sub(self, name: str, amount: float, next_date, period: str = "month", every: int = 1,
|
||||
currency: str = "RUB", remind_days: int = 3, notes: str = "") -> dict:
|
||||
if not (name or "").strip():
|
||||
raise OpsError("у подписки нет названия")
|
||||
if period not in PERIODS:
|
||||
raise OpsError(f"период может быть только {', '.join(PERIODS)}")
|
||||
d = parse_day(next_date)
|
||||
if not d:
|
||||
raise OpsError("нужна дата следующего списания")
|
||||
cur = self.con.execute(
|
||||
"""INSERT INTO subscriptions (name, amount, currency, period, every, next_date, remind_days, notes)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(name.strip(), float(amount or 0), (currency or "RUB").upper(), period, max(1, int(every or 1)),
|
||||
d.isoformat(), max(0, int(remind_days if remind_days is not None else 3)), notes or ""))
|
||||
return self.sub(cur.lastrowid)
|
||||
|
||||
def update_sub(self, sub_id: int, **fields) -> dict:
|
||||
allowed = {"name", "amount", "currency", "period", "every", "next_date", "remind_days", "notes", "active"}
|
||||
sets, vals = [], []
|
||||
for k, v in fields.items():
|
||||
if k not in allowed or v is None:
|
||||
continue
|
||||
if k == "next_date":
|
||||
v = parse_day(v).isoformat()
|
||||
if k == "period" and v not in PERIODS:
|
||||
raise OpsError(f"период может быть только {', '.join(PERIODS)}")
|
||||
sets.append(f"{k} = ?")
|
||||
vals.append(v)
|
||||
if sets:
|
||||
self.sub(sub_id)
|
||||
self.con.execute(f"UPDATE subscriptions SET {', '.join(sets)} WHERE id = ?", (*vals, sub_id))
|
||||
return self.sub(sub_id)
|
||||
|
||||
def pay_sub(self, sub_id: int, amount: float | None = None, paid_on=None) -> dict:
|
||||
"""Records the payment and moves the next charge one period forward."""
|
||||
s = self.sub(sub_id)
|
||||
day = parse_day(paid_on) or self.today()
|
||||
self.con.execute("INSERT INTO payments (sub_id, paid_on, amount) VALUES (?, ?, ?)",
|
||||
(sub_id, day.isoformat(), float(amount if amount is not None else s["amount"])))
|
||||
nxt = add_period(date.fromisoformat(s["next_date"]), s["period"], s["every"])
|
||||
while nxt <= day: # paid late or far ahead: the next charge is still in the future
|
||||
nxt = add_period(nxt, s["period"], s["every"])
|
||||
self.con.execute("UPDATE subscriptions SET next_date = ? WHERE id = ?", (nxt.isoformat(), sub_id))
|
||||
return self.sub(sub_id)
|
||||
|
||||
def subs(self, active_only: bool = True) -> list[dict]:
|
||||
q = "SELECT * FROM subscriptions" + (" WHERE active = 1" if active_only else "") + " ORDER BY next_date"
|
||||
return [dict(r) for r in self.con.execute(q)]
|
||||
|
||||
def monthly_cost(self) -> dict[str, float]:
|
||||
"""Active subscriptions per month, by currency."""
|
||||
per_month = {"day": 30.44, "week": 4.345, "month": 1, "year": 1 / 12}
|
||||
out: dict[str, float] = {}
|
||||
for s in self.subs():
|
||||
out[s["currency"]] = out.get(s["currency"], 0) + s["amount"] * per_month[s["period"]] / s["every"]
|
||||
return {k: round(v, 2) for k, v in out.items()}
|
||||
|
||||
# MARK: - Routines
|
||||
|
||||
def routine(self, rid: int) -> dict:
|
||||
row = self.con.execute("SELECT * FROM routines WHERE id = ?", (rid,)).fetchone()
|
||||
if not row:
|
||||
raise OpsError(f"регламента #{rid} нет")
|
||||
return dict(row)
|
||||
|
||||
def add_routine(self, title: str, every_days: int, next_date=None, notes: str = "") -> dict:
|
||||
if not (title or "").strip():
|
||||
raise OpsError("у регламентного дела нет названия")
|
||||
n = int(every_days or 0)
|
||||
if n < 1:
|
||||
raise OpsError("периодичность — целое число дней, не меньше 1")
|
||||
d = parse_day(next_date) or self.today()
|
||||
cur = self.con.execute("INSERT INTO routines (title, every_days, next_date, notes) VALUES (?, ?, ?, ?)",
|
||||
(title.strip(), n, d.isoformat(), notes or ""))
|
||||
return self.routine(cur.lastrowid)
|
||||
|
||||
def done_routine(self, rid: int, note: str = "", done_on=None) -> dict:
|
||||
r = self.routine(rid)
|
||||
day = parse_day(done_on) or self.today()
|
||||
self.con.execute("INSERT INTO routine_log (routine_id, done_on, note) VALUES (?, ?, ?)",
|
||||
(rid, day.isoformat(), note or ""))
|
||||
self.con.execute("UPDATE routines SET next_date = ? WHERE id = ?",
|
||||
((day + timedelta(days=r["every_days"])).isoformat(), rid))
|
||||
return self.routine(rid)
|
||||
|
||||
def routines(self) -> list[dict]:
|
||||
rows = [dict(r) for r in self.con.execute("SELECT * FROM routines WHERE active = 1 ORDER BY next_date")]
|
||||
for r in rows:
|
||||
last = self.con.execute("SELECT done_on FROM routine_log WHERE routine_id = ? ORDER BY done_on DESC LIMIT 1",
|
||||
(r["id"],)).fetchone()
|
||||
r["last_done"] = last["done_on"] if last else None
|
||||
return rows
|
||||
|
||||
def update_routine(self, rid: int, **fields) -> dict:
|
||||
allowed = {"title", "every_days", "next_date", "notes", "active"}
|
||||
sets, vals = [], []
|
||||
for k, v in fields.items():
|
||||
if k not in allowed or v is None:
|
||||
continue
|
||||
if k == "next_date":
|
||||
v = parse_day(v).isoformat()
|
||||
sets.append(f"{k} = ?")
|
||||
vals.append(v)
|
||||
if sets:
|
||||
self.routine(rid)
|
||||
self.con.execute(f"UPDATE routines SET {', '.join(sets)} WHERE id = ?", (*vals, rid))
|
||||
return self.routine(rid)
|
||||
|
||||
# MARK: - Agenda
|
||||
|
||||
def agenda(self, days_ahead: int = 7) -> dict:
|
||||
"""What needs attention: overdue, today, the coming week — for the notch and the digest."""
|
||||
today = self.today()
|
||||
horizon = today + timedelta(days=days_ahead)
|
||||
|
||||
def bucket(d: date) -> str:
|
||||
return "overdue" if d < today else ("today" if d == today else "soon")
|
||||
|
||||
out = {"today": today.isoformat(), "overdue": [], "due_today": [], "soon": [],
|
||||
"running": None, "monthly_cost": self.monthly_cost()}
|
||||
key = {"overdue": "overdue", "today": "due_today", "soon": "soon"}
|
||||
for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?",
|
||||
(horizon.isoformat(),)):
|
||||
d = date.fromisoformat(t["due"])
|
||||
out[key[bucket(d)]].append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"],
|
||||
"client": t["client"]})
|
||||
for s in self.subs():
|
||||
d = date.fromisoformat(s["next_date"])
|
||||
if d <= horizon:
|
||||
out[key[bucket(d)]].append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"],
|
||||
"amount": s["amount"], "currency": s["currency"]})
|
||||
for r in self.routines():
|
||||
d = date.fromisoformat(r["next_date"])
|
||||
if d <= horizon:
|
||||
out[key[bucket(d)]].append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]})
|
||||
for k in ("overdue", "due_today", "soon"):
|
||||
out[k].sort(key=lambda x: (x["date"], x["kind"], x["id"]))
|
||||
tid = self.running_task_id()
|
||||
if tid is not None:
|
||||
t = self.task(tid)
|
||||
out["running"] = {"id": tid, "title": t["title"], "minutes": self._minutes().get(tid, 0)}
|
||||
return out
|
||||
|
||||
# MARK: - Reminders
|
||||
|
||||
def due_reminders(self) -> list[dict]:
|
||||
"""Things to remind about today that haven't been reminded about today yet."""
|
||||
today = self.today()
|
||||
sent = {(r["kind"], r["ref"]) for r in
|
||||
self.con.execute("SELECT kind, ref FROM reminders_sent WHERE day = ?", (today.isoformat(),))}
|
||||
out = []
|
||||
for t in self.con.execute("SELECT * FROM tasks WHERE status != 'done' AND due IS NOT NULL AND due <= ?",
|
||||
(today.isoformat(),)):
|
||||
if ("task", t["id"]) not in sent:
|
||||
out.append({"kind": "task", "id": t["id"], "title": t["title"], "date": t["due"]})
|
||||
for s in self.subs():
|
||||
d = date.fromisoformat(s["next_date"])
|
||||
if d - timedelta(days=s["remind_days"]) <= today and ("sub", s["id"]) not in sent:
|
||||
out.append({"kind": "sub", "id": s["id"], "title": s["name"], "date": s["next_date"],
|
||||
"amount": s["amount"], "currency": s["currency"]})
|
||||
for r in self.routines():
|
||||
if date.fromisoformat(r["next_date"]) <= today and ("routine", r["id"]) not in sent:
|
||||
out.append({"kind": "routine", "id": r["id"], "title": r["title"], "date": r["next_date"]})
|
||||
return out
|
||||
|
||||
def mark_reminded(self, kind: str, ref: int) -> None:
|
||||
self.con.execute("INSERT OR IGNORE INTO reminders_sent (kind, ref, day) VALUES (?, ?, ?)",
|
||||
(kind, ref, self.today().isoformat()))
|
||||
|
||||
def snooze(self, kind: str, ref: int, days: int = 1) -> None:
|
||||
"""Push a task / routine forward; a subscription is only reminded again tomorrow."""
|
||||
until = (self.today() + timedelta(days=days)).isoformat()
|
||||
if kind == "task":
|
||||
self.update_task(ref, due=until)
|
||||
elif kind == "routine":
|
||||
self.update_routine(ref, next_date=until)
|
||||
self.mark_reminded(kind, ref)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""SQLite storage for BroV Ops: tasks (with subtasks and time tracking), subscriptions
|
||||
with their payments, routines with their history, and a log of sent reminders."""
|
||||
import sqlite3
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS tasks (
|
||||
id INTEGER PRIMARY KEY,
|
||||
parent_id INTEGER REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
title TEXT NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
client TEXT NOT NULL DEFAULT '', -- saga / planet9 / home / …
|
||||
status TEXT NOT NULL DEFAULT 'todo', -- todo | doing | done
|
||||
due TEXT, -- YYYY-MM-DD
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
done_at TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS time_entries (
|
||||
id INTEGER PRIMARY KEY,
|
||||
task_id INTEGER NOT NULL REFERENCES tasks(id) ON DELETE CASCADE,
|
||||
started TEXT NOT NULL, -- ISO datetime, UTC
|
||||
stopped TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS subscriptions (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
amount REAL NOT NULL DEFAULT 0,
|
||||
currency TEXT NOT NULL DEFAULT 'RUB',
|
||||
period TEXT NOT NULL DEFAULT 'month', -- day | week | month | year
|
||||
every INTEGER NOT NULL DEFAULT 1, -- every N periods
|
||||
next_date TEXT NOT NULL, -- YYYY-MM-DD of the next charge
|
||||
remind_days INTEGER NOT NULL DEFAULT 3,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
active INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id INTEGER PRIMARY KEY,
|
||||
sub_id INTEGER NOT NULL REFERENCES subscriptions(id) ON DELETE CASCADE,
|
||||
paid_on TEXT NOT NULL,
|
||||
amount REAL NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS routines (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
every_days INTEGER NOT NULL,
|
||||
next_date TEXT NOT NULL,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
active INTEGER NOT NULL DEFAULT 1
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS routine_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
routine_id INTEGER NOT NULL REFERENCES routines(id) ON DELETE CASCADE,
|
||||
done_on TEXT NOT NULL,
|
||||
note TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS reminders_sent (
|
||||
kind TEXT NOT NULL, -- task | sub | routine | digest
|
||||
ref INTEGER NOT NULL,
|
||||
day TEXT NOT NULL, -- YYYY-MM-DD the reminder was sent for
|
||||
PRIMARY KEY (kind, ref, day)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
def connect(path: str) -> sqlite3.Connection:
|
||||
con = sqlite3.connect(path, check_same_thread=False, isolation_level=None)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA foreign_keys = ON")
|
||||
con.execute("PRAGMA journal_mode = WAL")
|
||||
con.executescript(SCHEMA)
|
||||
return con
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Plain-text rendering for Telegram (HTML parse mode)."""
|
||||
from datetime import date
|
||||
from html import escape
|
||||
|
||||
ICON = {"task": "📌", "sub": "💳", "routine": "🔁"}
|
||||
|
||||
|
||||
def human_day(iso: str, today: date) -> str:
|
||||
d = date.fromisoformat(iso)
|
||||
delta = (d - today).days
|
||||
if delta == 0:
|
||||
return "сегодня"
|
||||
if delta == 1:
|
||||
return "завтра"
|
||||
if delta == -1:
|
||||
return "вчера"
|
||||
if delta < 0:
|
||||
return f"просрочено на {-delta} дн."
|
||||
return d.strftime("%d.%m")
|
||||
|
||||
|
||||
def item_line(it: dict, today: date) -> str:
|
||||
extra = f" — {it['amount']:g} {it['currency']}" if it["kind"] == "sub" else ""
|
||||
client = f" [{it['client']}]" if it.get("client") else ""
|
||||
return f"{ICON[it['kind']]} {escape(it['title'])}{client}{extra} · {human_day(it['date'], today)}"
|
||||
|
||||
|
||||
def agenda(a: dict) -> str:
|
||||
today = date.fromisoformat(a["today"])
|
||||
out = []
|
||||
if a["running"]:
|
||||
out.append(f"⏱ Сейчас: <b>{escape(a['running']['title'])}</b> ({a['running']['minutes']} мин)")
|
||||
for key, title in (("overdue", "🔥 Просрочено"), ("due_today", "📅 Сегодня"), ("soon", "🗓 Ближайшая неделя")):
|
||||
if a[key]:
|
||||
out.append(f"\n<b>{title}</b>")
|
||||
out += [item_line(it, today) for it in a[key]]
|
||||
if not (a["overdue"] or a["due_today"] or a["soon"]):
|
||||
out.append("На ближайшую неделю ничего не горит 👌")
|
||||
if a["monthly_cost"]:
|
||||
out.append("\nПодписки в месяц: " + ", ".join(f"{v:g} {k}" for k, v in a["monthly_cost"].items()))
|
||||
return "\n".join(out).strip()
|
||||
|
||||
|
||||
def tree(nodes: list, depth: int = 0) -> list[str]:
|
||||
out = []
|
||||
for t in nodes:
|
||||
mark = "⏱" if t["running"] else ("▶️" if t["status"] == "doing" else "▫️")
|
||||
due = f" · до {t['due']}" if t["due"] else ""
|
||||
mins = f" · {t['minutes']} мин" if t["minutes"] else ""
|
||||
client = f" [{t['client']}]" if t["client"] else ""
|
||||
out.append(f"{' ' * depth}{mark} #{t['id']} {escape(t['title'])}{client}{due}{mins}")
|
||||
out += tree(t["children"], depth + 1)
|
||||
return out
|
||||
|
||||
|
||||
def subs(rows: list, monthly: dict, today: date) -> str:
|
||||
if not rows:
|
||||
return "Подписок пока нет. Скажи, например: «хостинг 900 рублей в месяц, списание 15-го»."
|
||||
lines = [f"💳 {escape(s['name'])} — {s['amount']:g} {s['currency']} / "
|
||||
f"{s['every'] if s['every'] > 1 else ''}{ {'day':'день','week':'нед.','month':'мес.','year':'год'}[s['period']] }"
|
||||
f" · {human_day(s['next_date'], today)}" for s in rows]
|
||||
lines.append("\nВ месяц: " + ", ".join(f"{v:g} {k}" for k, v in monthly.items()))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def routines(rows: list, today: date) -> str:
|
||||
if not rows:
|
||||
return "Регламентных дел пока нет. Скажи: «бэкап NAS раз в неделю»."
|
||||
return "\n".join(f"🔁 #{r['id']} {escape(r['title'])} · раз в {r['every_days']} дн. · {human_day(r['next_date'], today)}"
|
||||
+ (f" · последний раз {r['last_done']}" if r["last_done"] else "") for r in rows)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Telegram voice notes → text with faster-whisper, locally on the VM (no audio leaves it).
|
||||
The model loads on first use and stays in memory."""
|
||||
import threading
|
||||
|
||||
_model = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def transcribe(path: str, model_name: str = "small") -> str:
|
||||
global _model
|
||||
with _lock:
|
||||
if _model is None:
|
||||
from faster_whisper import WhisperModel # heavy import: only when a voice note comes
|
||||
_model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
||||
segments, _ = _model.transcribe(path, language="ru", vad_filter=True, beam_size=1)
|
||||
return " ".join(s.text.strip() for s in segments).strip()
|
||||
Reference in New Issue
Block a user