#!/usr/bin/env python3 """Центральная политика уведомлений: в Matrix только экстренное. Правило: critical → отправляется всегда (сервис лежит, бэкап не прошёл, CT упал) normal → только в файл /var/log/hub/notifications.log info → только в файл Использование из скриптов: from notify_policy import send send("critical", "Jellyfin не отвечает") send("normal", "Гигиена: найдено 20, high 0") """ import json import os import urllib.request from datetime import datetime LOG = "/var/log/hub/notifications.log" HUB = "http://127.0.0.1:9120/notify" def _quiet(): h = datetime.now().hour return h >= 23 or h < 7 def _log(level, text): try: os.makedirs(os.path.dirname(LOG), exist_ok=True) with open(LOG, "a", encoding="utf-8") as f: f.write("%s\t%s\t%s\n" % (datetime.now().isoformat(timespec="seconds"), level, text[:500])) except Exception: pass def send(level, text, force=False): """level: critical | normal | info. Возвращает True, если ушло в Matrix.""" _log(level, text) if level != "critical" and not force: return False if _quiet() and not force: _log("deferred", "тихие часы: " + text[:200]) return False try: body = json.dumps({"message": text, "source": "hub", "level": level}).encode() req = urllib.request.Request(HUB, data=body, method="POST") req.add_header("Content-Type", "application/json") with urllib.request.urlopen(req, timeout=30) as r: return r.status == 200 except Exception: return False if __name__ == "__main__": import sys if len(sys.argv) > 2: ok = send(sys.argv[1], " ".join(sys.argv[2:])) print("отправлено" if ok else "записано в лог (не экстренное)")