ops bot: task lists carry ✓/⏰ buttons again (tasks, today, free-text asks)

This commit is contained in:
maksarsanjeev
2026-11-09 00:44:13 +03:00
parent 977665806f
commit 1889439ed7
+71 -19
View File
@@ -31,8 +31,8 @@ CFG = {
"api_port": int(os.environ.get("API_PORT", "8787")), "api_port": int(os.environ.get("API_PORT", "8787")),
"db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"), "db": os.environ.get("DB_PATH", "/var/lib/brov-ops/ops.db"),
"tz": os.environ.get("TZ_NAME", "Europe/Moscow"), "tz": os.environ.get("TZ_NAME", "Europe/Moscow"),
"claude": os.environ.get("CLAUDE_BIN", "claude"), "kimi": os.environ.get("KIMI_BIN", "kimi"),
"model": os.environ.get("CLAUDE_MODEL", "haiku"), "model": os.environ.get("KIMI_MODEL", ""),
"whisper": os.environ.get("WHISPER_MODEL", "small"), "whisper": os.environ.get("WHISPER_MODEL", "small"),
"digest_hour": int(os.environ.get("DIGEST_HOUR", "9")), "digest_hour": int(os.environ.get("DIGEST_HOUR", "9")),
"quiet_from": int(os.environ.get("QUIET_FROM", "22")), "quiet_from": int(os.environ.get("QUIET_FROM", "22")),
@@ -82,8 +82,32 @@ def owner_only(handler):
async def send_long(update: Update, text: str, **kw): async def send_long(update: Update, text: str, **kw):
for i in range(0, len(text), 3800): """Splits long text; extra kwargs (buttons) go only on the last chunk."""
await update.effective_message.reply_text(text[i:i + 3800], parse_mode=ParseMode.HTML, **kw) 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 task_buttons(tasks: list, limit: int = 12) -> InlineKeyboardMarkup | None:
"""One row per open task: ✓ completes, ⏰ snoozes a day — same callbacks as reminders."""
rows = []
for t in tasks[:limit]:
title = t["title"] if len(t["title"]) <= 20 else t["title"][:19] + "…"
rows.append([InlineKeyboardButton(f"✓ {title}", callback_data=f"done:task:{t['id']}"),
InlineKeyboardButton("⏰", callback_data=f"snooze:task:{t['id']}")])
return InlineKeyboardMarkup(rows) if rows else None
def flat_tasks(tree: list) -> list:
out = []
def walk(nodes):
for n in nodes:
out.append(n)
walk(n["children"])
walk(tree)
return out
@owner_only @owner_only
@@ -97,13 +121,18 @@ async def cmd_start(update: Update, ctx):
@owner_only @owner_only
async def cmd_today(update: Update, ctx): async def cmd_today(update: Update, ctx):
await send_long(update, fmt.agenda(locked(ops.agenda))) with lock:
agenda, tree = ops.agenda(), ops.task_tree()
await send_long(update, fmt.agenda(agenda), reply_markup=task_buttons(flat_tasks(tree)))
@owner_only @owner_only
async def cmd_tasks(update: Update, ctx): async def cmd_tasks(update: Update, ctx):
lines = fmt.tree(locked(ops.task_tree)) with lock:
await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌") tree = ops.task_tree()
lines = fmt.tree(tree)
await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌",
reply_markup=task_buttons(flat_tasks(tree)))
@owner_only @owner_only
@@ -132,17 +161,25 @@ def repeat_buttons(sub: dict) -> InlineKeyboardMarkup:
InlineKeyboardButton("Нет, закрыть", callback_data=f"rep:sub:{sub['id']}:0")]]) 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): async def think(update: Update, text: str):
msg = await update.effective_message.reply_text("🤔 думаю…") msg = await update.effective_message.reply_text("🤔 думаю…")
paid: list = [] paid: list = []
try: try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"], paid) answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"], paid)
except OpsError as e: except OpsError as e:
answer = f"Не получилось: {e}" answer = f"Не получилось: {e}"
except Exception as e: # Claude timeout, CLI missing… except Exception as e: # Kimi timeout, CLI missing…
log.exception("brain") log.exception("brain")
answer = f"Ошибка: {e.__class__.__name__}" answer = f"Ошибка: {e.__class__.__name__}"
await msg.edit_text(answer[:4000]) markup = None
if "✓" not in answer and any(h in text.lower() for h in LIST_HINTS):
markup = task_buttons(flat_tasks(locked(ops.task_tree)))
await msg.edit_text(answer[:4000], reply_markup=markup)
for sid in paid: # paid by text: ask «repeat?» with buttons for sid in paid: # paid by text: ask «repeat?» with buttons
s = locked(ops.sub, sid) s = locked(ops.sub, sid)
if s["paid"] and s["active"]: if s["paid"] and s["active"]:
@@ -213,6 +250,13 @@ async def on_button(update: Update, ctx):
note = "⏰ Напомню завтра" note = "⏰ Напомню завтра"
except OpsError as e: except OpsError as e:
note = f"Не получилось: {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.answer()
await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup) await q.edit_message_text(q.message.text + "\n\n" + note, reply_markup=markup)
@@ -289,14 +333,14 @@ async def api_say(request):
if not text: if not text:
raise web.HTTPBadRequest(text="empty") raise web.HTTPBadRequest(text="empty")
try: try:
answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["claude"], CFG["model"]) answer = await asyncio.to_thread(brain.handle_text, ops, text, lock, CFG["kimi"], CFG["model"])
except OpsError as e: except OpsError as e:
return ok({"ok": False, "answer": str(e)}) return ok({"ok": False, "answer": str(e)})
return ok({"ok": True, "answer": answer}) return ok({"ok": True, "answer": answer})
async def api_action(request): async def api_action(request):
"""One direct action from a BroV button (done, paid, timer…), no Claude involved.""" """One direct action from a BroV button (done, paid, timer…), no Kimi involved."""
check_auth(request) check_auth(request)
body = await request.json() body = await request.json()
if body.get("op") == "snooze": if body.get("op") == "snooze":
@@ -308,7 +352,7 @@ async def api_action(request):
async def api_delete(request): async def api_delete(request):
"""Delete by an explicit click in BroV (Claude never deletes).""" """Delete by an explicit click in BroV (Kimi never deletes)."""
check_auth(request) check_auth(request)
body = await request.json() body = await request.json()
kind, ref = str(body.get("kind")), int(body.get("id")) kind, ref = str(body.get("kind")), int(body.get("id"))
@@ -398,12 +442,20 @@ async def main():
tg.add_handler(CallbackQueryHandler(on_button)) tg.add_handler(CallbackQueryHandler(on_button))
tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice)) tg.add_handler(MessageHandler(filters.VOICE | filters.AUDIO, on_voice))
tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text)) tg.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, on_text))
async with tg: # A Telegram/proxy outage must not kill the API, calendar and reminders. Keep the
await tg.start() # process alive and retry Telegram; systemd restart is still reserved for the polling
await tg.updater.start_polling(drop_pending_updates=False, timeout=25) # watchdog, which catches a connection that looked established but stopped updating.
asyncio.create_task(reminder_loop(tg.bot)) while True:
asyncio.create_task(poll_watchdog()) try:
await asyncio.Event().wait() 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__": if __name__ == "__main__":