47 lines
1.9 KiB
Python
47 lines
1.9 KiB
Python
import os
|
|
|
|
import httpx
|
|
|
|
from .base import Notifier
|
|
|
|
|
|
class GatewayNotifier(Notifier):
|
|
def __init__(self, base_url: str = "", token: str = "",
|
|
channels: list[str] | None = None,
|
|
telegram_bot: str = "") -> None:
|
|
self.base_url = (base_url or os.getenv(
|
|
"NOTIFY_GATEWAY_URL", "http://notify-gateway:8770"
|
|
)).rstrip("/")
|
|
self.token = token or os.getenv("NOTIFY_GATEWAY_TOKEN", "")
|
|
self.channels = channels or []
|
|
self.telegram_bot = telegram_bot.strip()
|
|
if not self.token:
|
|
raise RuntimeError("NOTIFY_GATEWAY_TOKEN is not configured")
|
|
if not self.channels:
|
|
raise RuntimeError("notification channels must be explicitly configured")
|
|
if "telegram" in self.channels and not self.telegram_bot:
|
|
raise RuntimeError("telegram_bot is required when Telegram is selected")
|
|
|
|
async def send(self, title: str, text: str, idempotency_key: str = "",
|
|
images: list[dict] | None = None) -> None:
|
|
payload = {"title": title, "text": text, "channels": self.channels}
|
|
if "telegram" in self.channels:
|
|
payload["telegram_bot"] = self.telegram_bot
|
|
if images:
|
|
payload["images"] = [
|
|
{key: image[key] for key in ("filename", "content_type", "data_base64")}
|
|
for image in images
|
|
]
|
|
if idempotency_key:
|
|
payload["idempotency_key"] = idempotency_key
|
|
async with httpx.AsyncClient(timeout=90, trust_env=False) as client:
|
|
response = await client.post(
|
|
f"{self.base_url}/send",
|
|
headers={"Authorization": f"Bearer {self.token}"},
|
|
json=payload,
|
|
)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
if not data.get("ok"):
|
|
raise RuntimeError(f"notify-gateway delivery incomplete: {data.get('results', {})}")
|