Initial barberousse bot: Telegram commands, Pterodactyl deploy notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
87c295b76e
commit
fce314e1e0
6 changed files with 320 additions and 0 deletions
11
.env.example
Normal file
11
.env.example
Normal file
|
|
@ -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
|
||||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
.local/
|
||||||
|
.cache/
|
||||||
|
.config/
|
||||||
41
README.md
41
README.md
|
|
@ -1,2 +1,43 @@
|
||||||
# barberousse
|
# 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 <name>` | 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/<slug>` and
|
||||||
|
`/api/status-page/heartbeat/<slug>`): 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.
|
||||||
|
|
|
||||||
198
app.py
Normal file
198
app.py
Normal file
|
|
@ -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: <code>{esc(e)}</code>")
|
||||||
|
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 = "✅ <b>All up</b>" if not down else f"❌ <b>{len(down)} down</b>"
|
||||||
|
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, (
|
||||||
|
"🏴☠️ <b>Barberousse</b> 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} <b>{esc(m.name)}</b> ({esc(m.group)}) for {ago(m.down_since or m.last_time)}"
|
||||||
|
+ (f"\n <i>{esc(m.msg[:200])}</i>" 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 <code>{esc(query)}</code>.")
|
||||||
|
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} <b>{esc(m.name)}</b>\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: <i>{esc(m.msg[:300])}</i>\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 = ["<b>Uptime, last 24 h</b> (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 = "☀️ <b>Daily digest</b>\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 (<code>{esc(e)}</code>)"
|
||||||
|
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()
|
||||||
61
kuma.py
Normal file
61
kuma.py
Normal file
|
|
@ -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
|
||||||
3
requirements.txt
Normal file
3
requirements.txt
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
python-telegram-bot[job-queue]==21.11.1
|
||||||
|
httpx>=0.27,<1
|
||||||
|
python-dotenv>=1.0,<2
|
||||||
Loading…
Add table
Reference in a new issue