"""Barberousse: Telegram commands on top of Uptime Kuma (read-only).""" from __future__ import annotations import html import logging import os from datetime import datetime, time, timezone from functools import wraps from zoneinfo import ZoneInfo import httpx from dotenv import load_dotenv from telegram import Update from telegram.constants import ParseMode from telegram.ext import Application, CommandHandler, ContextTypes import kuma load_dotenv() TOKEN = os.environ["TELEGRAM_BOT_TOKEN"] ALLOWED = {int(x) for x in os.environ["ALLOWED_CHAT_IDS"].split(",") if x.strip()} KUMA_URL = os.environ.get("KUMA_URL", "https://status.un-oeil.fr") KUMA_SLUG = os.environ.get("KUMA_SLUG", "homelab") DIGEST_TIME = os.environ.get("DIGEST_TIME", "").strip() # "09:00", empty = off PUSH_URL = os.environ.get("KUMA_PUSH_URL", "").strip() # heartbeat for the bot itself TZ = ZoneInfo(os.environ.get("TZ", "Europe/Paris")) logging.basicConfig(format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.INFO) logging.getLogger("httpx").setLevel(logging.WARNING) log = logging.getLogger("barberousse") def restricted(func): @wraps(func) async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE): chat = update.effective_chat if chat is None or chat.id not in ALLOWED: log.warning("ignored command from chat %s (%s)", chat and chat.id, update.effective_user) return return await func(update, context) return wrapper def esc(s) -> str: return html.escape(str(s)) def ago(dt: datetime | None) -> str: if dt is None: return "?" secs = int((datetime.now(timezone.utc) - dt).total_seconds()) if secs < 60: return f"{secs}s" if secs < 3600: return f"{secs // 60}m" if secs < 86400: return f"{secs // 3600}h{secs % 3600 // 60:02d}" return f"{secs // 86400}d{secs % 86400 // 3600}h" async def reply(update: Update, text: str): await update.effective_message.reply_text(text, parse_mode=ParseMode.HTML, disable_web_page_preview=True) async def load(update: Update) -> list[kuma.Monitor] | None: try: return await kuma.fetch_monitors(KUMA_URL, KUMA_SLUG) except Exception as e: # noqa: BLE001 - report any failure to the user log.exception("Kuma fetch failed") await reply(update, f"⚠️ Can't reach Uptime Kuma: {esc(e)}") return None def status_text(monitors: list[kuma.Monitor]) -> str: groups: dict[str, list[kuma.Monitor]] = {} for m in monitors: groups.setdefault(m.group, []).append(m) down = [m for m in monitors if m.status == kuma.DOWN] head = "✅ All up" if not down else f"❌ {len(down)} down" lines = [f"{head} · {len(monitors)} monitors"] for name, ms in groups.items(): bad = [m for m in ms if m.status not in (kuma.UP, None)] paused = sum(m.status is None for m in ms) extra = f" · {paused} paused" if paused else "" if not bad: lines.append(f"✅ {esc(name)} ({len(ms)}){extra}") else: lines.append(f"❌ {esc(name)}: " + ", ".join(f"{m.icon} {esc(m.name)}" for m in bad) + extra) return "\n".join(lines) @restricted async def cmd_help(update: Update, context: ContextTypes.DEFAULT_TYPE): await reply(update, ( "🏴‍☠️ Barberousse watches Uptime Kuma\n\n" "/status: every group at a glance\n" "/down: only what is down, and since when\n" "/monitor <name>: details of one monitor\n" "/uptime: 24 h uptime, worst first" )) @restricted async def cmd_status(update: Update, context: ContextTypes.DEFAULT_TYPE): if (monitors := await load(update)) is not None: await reply(update, status_text(monitors)) @restricted async def cmd_down(update: Update, context: ContextTypes.DEFAULT_TYPE): if (monitors := await load(update)) is None: return down = [m for m in monitors if m.status in (kuma.DOWN, kuma.PENDING)] if not down: await reply(update, "✅ Nothing is down.") return lines = [f"{m.icon} {esc(m.name)} ({esc(m.group)}) for {ago(m.down_since or m.last_time)}" + (f"\n {esc(m.msg[:200])}" if m.msg else "") for m in down] await reply(update, "\n".join(lines)) @restricted async def cmd_monitor(update: Update, context: ContextTypes.DEFAULT_TYPE): query = " ".join(context.args).strip().lower() if not query: await reply(update, "Usage: /monitor <name> (part of the name is enough)") return if (monitors := await load(update)) is None: return exact = [m for m in monitors if m.name.lower() == query] found = exact or [m for m in monitors if query in m.name.lower()] if not found: await reply(update, f"No monitor matches {esc(query)}.") return if len(found) > 1: await reply(update, "Several matches:\n" + "\n".join(f"{m.icon} {esc(m.name)}" for m in found[:20])) return m = found[0] up = f"{m.uptime_24h * 100:.2f} %" if m.uptime_24h is not None else "?" ping = f"{m.ping:.0f} ms" if m.ping is not None else "-" history = "".join(kuma.ICONS.get(s, "❔") for s in m.recent) or "no data" await reply(update, ( f"{m.icon} {esc(m.name)}\n" f"Group: {esc(m.group)} · type {esc(m.type)}\n" f"Last check: {ago(m.last_time)} ago · {ping}\n" + (f"Down for: {ago(m.down_since)}\n" if m.down_since else "") + (f"Message: {esc(m.msg[:300])}\n" if m.msg else "") + f"Uptime 24 h: {up}\nLast checks: {history}" )) @restricted async def cmd_uptime(update: Update, context: ContextTypes.DEFAULT_TYPE): if (monitors := await load(update)) is None: return rated = sorted((m for m in monitors if m.uptime_24h is not None), key=lambda m: m.uptime_24h) lines = ["Uptime, last 24 h (worst first)"] lines += [f"{m.icon} {m.uptime_24h * 100:6.2f} % {esc(m.name)}" for m in rated[:25]] if len(rated) > 25: lines.append(f"… and {len(rated) - 25} more at 100 %" if all(m.uptime_24h == 1 for m in rated[25:]) else f"… and {len(rated) - 25} more") await reply(update, "\n".join(lines)) async def job_digest(context: ContextTypes.DEFAULT_TYPE): try: text = "☀️ Daily digest\n" + status_text(await kuma.fetch_monitors(KUMA_URL, KUMA_SLUG)) except Exception as e: # noqa: BLE001 text = f"☀️ Daily digest: ⚠️ can't reach Uptime Kuma ({esc(e)})" for chat_id in ALLOWED: await context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML) async def job_heartbeat(context: ContextTypes.DEFAULT_TYPE): try: async with httpx.AsyncClient(timeout=10) as client: await client.get(PUSH_URL, params={"status": "up", "msg": "OK"}) except httpx.HTTPError as e: log.warning("heartbeat failed: %s", e) def main(): app = Application.builder().token(TOKEN).build() for name, fn in (("start", cmd_help), ("help", cmd_help), ("status", cmd_status), ("down", cmd_down), ("monitor", cmd_monitor), ("uptime", cmd_uptime)): app.add_handler(CommandHandler(name, fn)) if DIGEST_TIME: hh, mm = (int(x) for x in DIGEST_TIME.split(":")) app.job_queue.run_daily(job_digest, time(hh, mm, tzinfo=TZ), name="digest") if PUSH_URL: app.job_queue.run_repeating(job_heartbeat, interval=60, first=5, name="heartbeat") log.info("Barberousse starting (kuma=%s/%s, digest=%s, heartbeat=%s)", KUMA_URL, KUMA_SLUG, DIGEST_TIME or "off", "on" if PUSH_URL else "off") app.run_polling(allowed_updates=Update.ALL_TYPES) if __name__ == "__main__": main()