Files
homelab-configs/apps/home-security-agent/agent/telegram_notify.py
T

43 lines
1.2 KiB
Python
Raw Normal View History

"""Telegram — enige externe meldkanaal."""
import os
import httpx
def send_message(text: str, parse_mode: str = "HTML") -> bool:
token = os.environ.get("TELEGRAM_BOT_TOKEN", "").strip()
chat_id = os.environ.get("TELEGRAM_CHAT_ID", "").strip()
if not token or not chat_id:
return False
url = f"https://api.telegram.org/bot{token}/sendMessage"
# Telegram max ~4096
if len(text) > 4000:
text = text[:3990] + ""
r = httpx.post(
url,
data={"chat_id": chat_id, "text": text, "parse_mode": parse_mode},
timeout=30,
)
return r.status_code == 200
def format_alert(severity: str, title: str, body: str, actions=None) -> str:
icon = {"critical": "🔴", "high": "🟠", "medium": "🟡", "low": "🔵", "info": ""}.get(
severity, ""
)
lines = [
f"{icon} <b>EL-KADI SECURITY</b> · {severity.upper()}",
f"<b>{_esc(title)}</b>",
"",
_esc(body),
]
if actions:
lines.append("")
lines.append("<b>Agent acties:</b>")
for a in actions:
lines.append(f"{_esc(a)}")
return "\n".join(lines)
def _esc(s: str) -> str:
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")