93 lines
3.9 KiB
Python
93 lines
3.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Точка приёма уведомлений для рабочих процессов.
|
|
|
|
Зачем: уведомления сейчас разбросаны по процессам n8n, и каждый шлёт
|
|
в Telegram по-своему. Здесь один адрес — любой процесс делает запрос
|
|
и сообщение уходит в Matrix (основной канал) и в Telegram (зеркало).
|
|
|
|
Использование:
|
|
curl -X POST http://192.168.1.10:8099/notify \
|
|
-H 'Content-Type: application/json' \
|
|
-d '{"text": "текст уведомления", "source": "имя процесса"}'
|
|
|
|
Ответ: {"delivered": true, "matrix": true, "telegram": false}
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
sys.path.insert(0, "/opt/buryan-hub/scripts")
|
|
|
|
PORT = int(os.getenv("NOTIFY_PORT", "8099"))
|
|
BIND = os.getenv("NOTIFY_BIND", "192.168.1.10")
|
|
|
|
|
|
def deliver(text: str, source: str = "", bot: str = "alert") -> dict:
|
|
"""Отправляет уведомление. Возвращает, куда доставлено."""
|
|
try:
|
|
import notify
|
|
# Разным процессам — разные боты: тревоги от ALERT, доступ от AUTH.
|
|
# Если для бота есть своя комната, шлём в неё.
|
|
if bot != "alert":
|
|
env = notify._load_env("/root/.buryan-bots-matrix.env")
|
|
token = env.get(f"MATRIX_{bot.upper()}_TOKEN")
|
|
room = env.get(f"MATRIX_{bot.upper()}_ROOM")
|
|
if token and room:
|
|
notify.CFG_FILE = "/root/.buryan-bots-matrix.env"
|
|
notify._matrix_env = lambda: (
|
|
env.get("MATRIX_HOMESERVER_LOCAL", ""), token, room
|
|
)
|
|
ok = notify.send(text)
|
|
return {"delivered": bool(ok), "matrix": bool(ok), "telegram": False}
|
|
except Exception as exc: # noqa: BLE001
|
|
print(f"ошибка отправки: {exc}", file=sys.stderr)
|
|
return {"delivered": False, "error": str(exc)}
|
|
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def _send(self, code: int, payload: dict) -> None:
|
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def do_GET(self):
|
|
if self.path.startswith("/health"):
|
|
self._send(200, {"status": "ok"})
|
|
else:
|
|
self._send(404, {"error": "не найдено"})
|
|
|
|
def do_POST(self):
|
|
if not self.path.startswith("/notify"):
|
|
self._send(404, {"error": "не найдено"})
|
|
return
|
|
try:
|
|
length = int(self.headers.get("Content-Length") or 0)
|
|
raw = self.rfile.read(length).decode("utf-8") if length else "{}"
|
|
data = json.loads(raw or "{}")
|
|
except Exception as exc: # noqa: BLE001
|
|
self._send(400, {"error": f"неверный запрос: {exc}"})
|
|
return
|
|
|
|
text = (data.get("text") or data.get("message") or "").strip()
|
|
if not text:
|
|
self._send(400, {"error": "пустой текст"})
|
|
return
|
|
source = str(data.get("source") or "процесс")
|
|
bot = str(data.get("bot") or "alert").lower()
|
|
print(f"уведомление от {source}, бот {bot}: {text[:80]}", flush=True)
|
|
self._send(200, deliver(text, source, bot))
|
|
|
|
def log_message(self, fmt, *args): # тише в журнале
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print(f"точка приёма уведомлений: http://{BIND}:{PORT}/notify", flush=True)
|
|
ThreadingHTTPServer((BIND, PORT), Handler).serve_forever()
|