47 lines
2.1 KiB
Python
47 lines
2.1 KiB
Python
"""Push-Nachrichten auf Marcs Handy über seinen Gotify-Server (GOTIFY_URL, App-Token GOTIFY_TOKEN).
|
||
|
||
Gotify läuft auf Marcs eigenem Server – Nachrichten dürfen daher Inhalt haben (Frist, Absender), bleiben aber kurz;
|
||
Details stehen im Chat (Klick öffnet LibreChat, NOTIFY_CLICK_URL). Nur Marc nutzt Push, Marisa nicht.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import urllib.error
|
||
import urllib.request
|
||
|
||
PRIO = {"min": 0, "low": 2, "default": 5, "high": 8, "urgent": 10}
|
||
MAX_ZEICHEN = 1000
|
||
|
||
|
||
def _env(name: str) -> str:
|
||
val = os.environ.get(name)
|
||
if not val:
|
||
raise SystemExit(f"{name} fehlt in docker/butler/notify.env (Gotify: App „Butler“ anlegen, Token eintragen)")
|
||
return val
|
||
|
||
|
||
def senden(text: str, titel: str = "", prioritaet: str = "default") -> dict:
|
||
text = (text or "").strip()
|
||
if not text:
|
||
raise ValueError("Text fehlt")
|
||
if len(text) > MAX_ZEICHEN:
|
||
raise ValueError(f"Zu lang ({len(text)} Zeichen, max. {MAX_ZEICHEN}) – Push kurz halten, Details im Chat.")
|
||
if prioritaet not in PRIO:
|
||
raise ValueError(f"prioritaet: {', '.join(PRIO)}")
|
||
nachricht = {"title": titel.strip()[:100] or "Butler", "message": text, "priority": PRIO[prioritaet],
|
||
"extras": {"client::display": {"contentType": "text/markdown"}}}
|
||
if os.environ.get("NOTIFY_CLICK_URL"):
|
||
nachricht["extras"]["client::notification"] = {"click": {"url": os.environ["NOTIFY_CLICK_URL"]}}
|
||
req = urllib.request.Request(_env("GOTIFY_URL").rstrip("/") + "/message", data=json.dumps(nachricht).encode(),
|
||
headers={"Content-Type": "application/json", "X-Gotify-Key": _env("GOTIFY_TOKEN")},
|
||
method="POST")
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=30) as r:
|
||
antwort = json.load(r)
|
||
except urllib.error.HTTPError as e:
|
||
if e.code in (401, 403):
|
||
raise RuntimeError("Gotify lehnt den Token ab – GOTIFY_TOKEN in docker/butler/notify.env prüfen.") from e
|
||
raise
|
||
return {"gesendet": True, "id": antwort.get("id")}
|