From fce314e1e02804ee12fa7e601b2f2f496dd16ea5 Mon Sep 17 00:00:00 2001 From: un-oeil Date: Tue, 13 Oct 2026 14:12:13 +0200 Subject: [PATCH] Initial barberousse bot: Telegram commands, Pterodactyl deploy notes Co-Authored-By: Claude Opus 5.5 --- .env.example | 11 +++ .gitignore | 6 ++ README.md | 41 ++++++++++ app.py | 198 +++++++++++++++++++++++++++++++++++++++++++++++ kuma.py | 61 +++++++++++++++ requirements.txt | 3 + 6 files changed, 320 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 app.py create mode 100644 kuma.py create mode 100644 requirements.txt diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..b114591 --- /dev/null +++ b/.env.example @@ -0,0 +1,11 @@ +# Copy to .env (never commit it) and fill in. +TELEGRAM_BOT_TOKEN=123456:ABC... +# Comma-separated Telegram chat IDs allowed to use the bot +ALLOWED_CHAT_IDS=8248249474 +KUMA_URL=https://status.un-oeil.fr +KUMA_SLUG=homelab +# Daily summary at this local time (Europe/Paris); leave empty to disable +DIGEST_TIME=09:00 +# Kuma Push URL for the "Barberousse" monitor (bot heartbeat every 60 s); empty = off +KUMA_PUSH_URL= +TZ=Europe/Paris diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..85aed96 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.env +.venv/ +__pycache__/ +.local/ +.cache/ +.config/ diff --git a/README.md b/README.md index b743c32..c4fb109 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,43 @@ # barberousse +Telegram bot that answers questions about the homelab's **Uptime Kuma**. +Kuma itself still sends the alerts (same bot token); this bot only adds commands. + +| Command | Reply | +|---|---| +| `/status` | Every status-page group at a glance (✅ or what's down) | +| `/down` | Only what is down or pending, since when, last error | +| `/monitor ` | One monitor: state, response time, 24 h uptime, last 10 checks | +| `/uptime` | 24 h uptime, worst first | + +Optional: a daily digest (`DIGEST_TIME`) and a heartbeat to a Kuma Push monitor (`KUMA_PUSH_URL`). + +It reads Kuma's **public status page API** (`/api/status-page/` and +`/api/status-page/heartbeat/`): read-only, no Kuma login. It only answers the chat +IDs in `ALLOWED_CHAT_IDS`. + +## Run locally + +```bash +python3 -m venv .venv && .venv/bin/pip install -r requirements.txt +cp .env.example .env # fill in the token +.venv/bin/python app.py +``` + +## Deploy on Pterodactyl (python generic egg) + +Server `barberousse` on node `wings`. + +| Variable | Value | +|---|---| +| `GIT_ADDRESS` | `https://forgejo.un-oeil.fr/un-oeil/barberousse.git` | +| `USERNAME` / `ACCESS_TOKEN` | Forgejo user + token with **read:repository** only | +| `AUTO_UPDATE` | `1` (git pull on every restart) | +| `PY_FILE` | `app.py` | +| `REQUIREMENTS_FILE` | `requirements.txt` | + +1. Set the variables, then **Reinstall** (the install clones the repo into an empty folder). +2. Files → create `.env` from `.env.example`. It is git-ignored, so `git pull` never touches it. +3. Start. The console shows `Barberousse starting (...)`. + +To update: push to Forgejo, then Restart the server. diff --git a/app.py b/app.py new file mode 100644 index 0000000..e1c3b89 --- /dev/null +++ b/app.py @@ -0,0 +1,198 @@ +"""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() diff --git a/kuma.py b/kuma.py new file mode 100644 index 0000000..52f8d5e --- /dev/null +++ b/kuma.py @@ -0,0 +1,61 @@ +"""Read-only client for an Uptime Kuma public status page.""" +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime, timezone + +import httpx + +DOWN, UP, PENDING, MAINTENANCE = 0, 1, 2, 3 +ICONS = {DOWN: "❌", UP: "✅", PENDING: "🟡", MAINTENANCE: "🔧", None: "⏸"} + + +@dataclass +class Monitor: + id: int + name: str + group: str + type: str + status: int | None = None # last heartbeat status, None = no data (paused) + msg: str = "" + ping: float | None = None + last_time: datetime | None = None + down_since: datetime | None = None + uptime_24h: float | None = None + recent: list[int] = field(default_factory=list) + + @property + def icon(self) -> str: + return ICONS.get(self.status, "❔") + + +def _parse_time(s: str) -> datetime: + # Kuma returns UTC as "YYYY-MM-DD HH:MM:SS.mmm" + return datetime.fromisoformat(s.replace(" ", "T")).replace(tzinfo=timezone.utc) + + +async def fetch_monitors(base_url: str, slug: str) -> list[Monitor]: + async with httpx.AsyncClient(base_url=base_url.rstrip("/"), timeout=15) as client: + page = (await client.get(f"/api/status-page/{slug}")).raise_for_status().json() + beats = (await client.get(f"/api/status-page/heartbeat/{slug}")).raise_for_status().json() + + monitors = [] + for group in page["publicGroupList"]: + for m in group["monitorList"]: + mon = Monitor(id=m["id"], name=m["name"], group=group["name"], type=m.get("type", "")) + history = beats["heartbeatList"].get(str(m["id"]), []) + if history: + last = history[-1] + mon.status, mon.msg, mon.ping = last["status"], last.get("msg") or "", last.get("ping") + mon.last_time = _parse_time(last["time"]) + mon.recent = [h["status"] for h in history[-10:]] + if mon.status == DOWN: + since = last + for h in reversed(history): + if h["status"] != DOWN: + break + since = h + mon.down_since = _parse_time(since["time"]) + mon.uptime_24h = beats["uptimeList"].get(f"{m['id']}_24") + monitors.append(mon) + return monitors diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..54d1b62 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +python-telegram-bot[job-queue]==21.11.1 +httpx>=0.27,<1 +python-dotenv>=1.0,<2