точка приёма понимает формат Telegram: для переключения процесса достаточно сменить адрес
This commit is contained in:
1 parent
5197f04bdd
commit
ce804d59aa
2 files changed
+129
-31
No files matched your search
@@ -761,3 +761,39 @@ POST http://192.168.1.10:8099/notify
|
||||
|
||||
Служба: `buryan-notify.service`, запускается автоматически,
|
||||
журнал `/var/log/buryan-notify.log`.
|
||||
|
||||
---
|
||||
|
||||
## ТОЧКА ПРИЁМА ПОНИМАЕТ ФОРМАТ TELEGRAM (15.10.2026)
|
||||
|
||||
Чтобы переключить процессы n8n **минимальной правкой**, точка приёма
|
||||
теперь принимает тот же запрос, что и Telegram:
|
||||
|
||||
```
|
||||
БЫЛО: https://api.telegram.org/bot{{ТОКЕН}}/sendMessage
|
||||
СТАЛО: http://192.168.1.10:8099/bot{{ТОКЕН}}/sendMessage
|
||||
```
|
||||
|
||||
Поля `chat_id`, `text`, `parse_mode` остаются прежними, ответ приходит
|
||||
в том же виде (`{"ok": true, ...}`). **Логика процессов не меняется —
|
||||
меняется только адрес.**
|
||||
|
||||
Бот определяется **по токену автоматически**: тревоги уходят от ALERT
|
||||
в комнату тревог, сообщения о доступе — от AUTH в комнату доступа.
|
||||
|
||||
### Проверено
|
||||
|
||||
```
|
||||
тревога (токен ALERT) → {"ok": true, "routed": {"delivered": true}} → @bot_alert
|
||||
доступ (токен AUTH) → {"ok": true, "routed": {"delivered": true}} → @bot_auth
|
||||
```
|
||||
|
||||
Разделение по задачам работает: одно и то же обращение, но разные
|
||||
токены — и сообщения попадают в **разные комнаты от разных ботов**.
|
||||
|
||||
### Что осталось
|
||||
|
||||
Переключить адреса в семи активных процессах n8n:
|
||||
Alert Queue Processor, Prometheus/Grafana Alert Webhook,
|
||||
Uptime Kuma → Gitea Self-Healing, F6-2, F6-3, Gitea Task Dispatcher,
|
||||
Buryan Health Monitor.
|
||||
+93
-31
@@ -1,47 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Точка приёма уведомлений для рабочих процессов.
|
||||
|
||||
Зачем: уведомления сейчас разбросаны по процессам n8n, и каждый шлёт
|
||||
в Telegram по-своему. Здесь один адрес — любой процесс делает запрос
|
||||
и сообщение уходит в Matrix (основной канал) и в Telegram (зеркало).
|
||||
Зачем: уведомления разбросаны по процессам n8n, и каждый шлёт в Telegram
|
||||
по-своему. Здесь один адрес — процесс делает запрос, сообщение уходит
|
||||
в Matrix (основной канал) и в Telegram (зеркало).
|
||||
|
||||
Использование:
|
||||
curl -X POST http://192.168.1.10:8099/notify \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"text": "текст уведомления", "source": "имя процесса"}'
|
||||
ПОЧЕМУ ПОНИМАЕТ ФОРМАТ TELEGRAM:
|
||||
чтобы переключить процесс n8n, достаточно поменять АДРЕС в его узле —
|
||||
логика, поля и оформление остаются прежними. Иначе пришлось бы
|
||||
переписывать каждый процесс.
|
||||
|
||||
Ответ: {"delivered": true, "matrix": true, "telegram": false}
|
||||
Два способа обращения:
|
||||
1. Свой формат:
|
||||
POST /notify {"text": "...", "source": "имя", "bot": "alert"}
|
||||
2. Формат Telegram (совместимый):
|
||||
POST /bot<ТОКЕН>/sendMessage chat_id=...&text=...&parse_mode=HTML
|
||||
Бот определяется по токену — тревоги уйдут от ALERT, доступ от AUTH.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.parse
|
||||
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")
|
||||
BOTS_ENV = "/root/.buryan-bots-matrix.env"
|
||||
TOKENS_ENV = "/root/bots-tokens.env"
|
||||
|
||||
|
||||
def _env(path: str) -> dict:
|
||||
data = {}
|
||||
try:
|
||||
with open(path, encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
k, v = line.split("=", 1)
|
||||
data[k.strip()] = v.strip()
|
||||
return data
|
||||
except OSError:
|
||||
return {}
|
||||
|
||||
|
||||
def bot_by_telegram_token(token: str) -> str:
|
||||
"""Определяет, какому боту принадлежит токен Telegram.
|
||||
|
||||
Токены лежат в файле. Сопоставление нужно, чтобы сообщение от
|
||||
процесса F6-2 (доступ) ушло от бота AUTH, а тревоги — от ALERT.
|
||||
"""
|
||||
env = _env(TOKENS_ENV)
|
||||
for key, val in env.items():
|
||||
if val and val == token:
|
||||
name = key.replace("_TOKEN", "").lower()
|
||||
return {"adm": "adm", "alert": "alert", "auth": "auth",
|
||||
"work": "work", "media": "media"}.get(name, "alert")
|
||||
return "alert"
|
||||
|
||||
|
||||
def deliver(text: str, source: str = "", bot: str = "alert") -> dict:
|
||||
"""Отправляет уведомление. Возвращает, куда доставлено."""
|
||||
try:
|
||||
import notify
|
||||
# Разным процессам — разные боты: тревоги от ALERT, доступ от AUTH.
|
||||
# Если для бота есть своя комната, шлём в неё.
|
||||
env = _env(BOTS_ENV)
|
||||
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}
|
||||
return {"delivered": bool(ok), "matrix": bool(ok), "telegram": False,
|
||||
"bot": bot, "source": source}
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"ошибка отправки: {exc}", file=sys.stderr)
|
||||
return {"delivered": False, "error": str(exc)}
|
||||
@@ -56,6 +93,17 @@ class Handler(BaseHTTPRequestHandler):
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _read(self) -> dict:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
raw = self.rfile.read(length).decode("utf-8") if length else ""
|
||||
ctype = (self.headers.get("Content-Type") or "").lower()
|
||||
if "json" in ctype:
|
||||
try:
|
||||
return json.loads(raw or "{}")
|
||||
except Exception: # noqa: BLE001
|
||||
return {}
|
||||
return {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()}
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/health"):
|
||||
self._send(200, {"status": "ok"})
|
||||
@@ -63,30 +111,44 @@ class Handler(BaseHTTPRequestHandler):
|
||||
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}"})
|
||||
data = self._read()
|
||||
|
||||
# ── Формат Telegram: /bot<ТОКЕН>/sendMessage ──────────────
|
||||
m = re.match(r"^/bot([0-9A-Za-z:_-]+)/sendMessage", self.path)
|
||||
if m:
|
||||
token = m.group(1)
|
||||
text = (data.get("text") or "").strip()
|
||||
if not text:
|
||||
self._send(400, {"ok": False, "description": "пустой текст"})
|
||||
return
|
||||
bot = bot_by_telegram_token(token)
|
||||
# Приводим разметку Telegram к тому же виду для Matrix
|
||||
text = text.replace("<b>", "<b>").replace("</b>", "</b>")
|
||||
print(f"приём в формате Telegram, бот {bot}: {text[:80]}", flush=True)
|
||||
res = deliver(text, "telegram-процесс", bot)
|
||||
# Отвечаем в формате Telegram — процессу привычно
|
||||
self._send(200, {"ok": True, "result": {"message_id": 1}, "routed": res})
|
||||
return
|
||||
|
||||
text = (data.get("text") or data.get("message") or "").strip()
|
||||
if not text:
|
||||
self._send(400, {"error": "пустой текст"})
|
||||
# ── Свой формат: /notify ──────────────────────────────────
|
||||
if self.path.startswith("/notify"):
|
||||
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))
|
||||
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): # тише в журнале
|
||||
self._send(404, {"error": "не найдено"})
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(f"точка приёма уведомлений: http://{BIND}:{PORT}/notify", flush=True)
|
||||
print(f"точка приёма: http://{BIND}:{PORT}/notify "
|
||||
f"и http://{BIND}:{PORT}/bot<ТОКЕН>/sendMessage", flush=True)
|
||||
ThreadingHTTPServer((BIND, PORT), Handler).serve_forever()
|
||||
Reference in new issue
Block a user