From 1889439ed7a18ec4e075df8fd447b60578c37804 Mon Sep 17 00:00:00 2001 From: maksarsanjeev Date: Mon, 9 Nov 2026 00:44:13 +0300 Subject: [PATCH] =?UTF-8?q?ops=20bot:=20task=20lists=20carry=20=E2=9C=93/?= =?UTF-8?q?=E2=8F=B0=20buttons=20again=20(tasks,=20today,=20free-text=20as?= =?UTF-8?q?ks)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ops/brovops/app.py | 90 ++++++++++++++++++++++++++++++++++++---------- 1 file changed, 71 insertions(+), 19 deletions(-) diff --git a/ops/brovops/app.py b/ops/brovops/app.py index 0e612ba..4c1a590 100644 --- a/ops/brovops/app.py +++ b/ops/brovops/app.py @@ -31,8 +31,8 @@ CFG = { "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"), + "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")), @@ -82,8 +82,32 @@ def owner_only(handler): 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) + """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 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 @@ -97,13 +121,18 @@ async def cmd_start(update: Update, ctx): @owner_only 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 async def cmd_tasks(update: Update, ctx): - lines = fmt.tree(locked(ops.task_tree)) - await send_long(update, "\n".join(lines) if lines else "Открытых задач нет 👌") + with lock: + 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 @@ -132,17 +161,25 @@ def repeat_buttons(sub: dict) -> InlineKeyboardMarkup: 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["claude"], CFG["model"], paid) + 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: # Claude timeout, CLI missing… + except Exception as e: # Kimi timeout, CLI missing… log.exception("brain") 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 s = locked(ops.sub, sid) if s["paid"] and s["active"]: @@ -213,6 +250,13 @@ async def on_button(update: Update, ctx): 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) @@ -289,14 +333,14 @@ async def api_say(request): if not text: raise web.HTTPBadRequest(text="empty") 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: 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.""" + """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": @@ -308,7 +352,7 @@ async def api_action(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) body = await request.json() 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(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, timeout=25) - asyncio.create_task(reminder_loop(tg.bot)) - asyncio.create_task(poll_watchdog()) - await asyncio.Event().wait() + # 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__":