from __future__ import annotations import httpx from ...redaction import redact from .base import DeliveryResult from .http import classify_response def _format_message(event_type: str, payload: dict) -> str: icon = "[FIRING]" if event_type == "firing" else "[RESOLVED]" sev = payload.get("severity", "unknown") agent = payload.get("agent_id", "?") check = payload.get("check_id", "?") status = payload.get("status", "?") incident_key = payload.get("incident_key", "?") output = payload.get("output") or "" lines = [ f"{icon} {sev} {agent}/{check}", f"status: {status}", f"incident_key: {incident_key}", f"observed_at: {payload.get('observed_at', '?')}", ] if output: lines.append(f"output: {output[:300]}") return redact("\n".join(lines)) or "" class TelegramNotifier: name = "telegram" def __init__(self, client: httpx.AsyncClient, token: str, chat_id: str) -> None: self._client = client self._token = token self._chat_id = chat_id async def deliver(self, event_type: str, payload: dict) -> DeliveryResult: url = f"https://api.telegram.org/bot{self._token}/sendMessage" body = {"chat_id": self._chat_id, "text": _format_message(event_type, payload)} try: resp = await self._client.post(url, json=body) except httpx.HTTPError as exc: return DeliveryResult(ok=False, permanent=False, error=type(exc).__name__) ok, perm = classify_response(resp.status_code) if ok: return DeliveryResult(ok=True) return DeliveryResult(ok=False, permanent=perm, error=f"http_{resp.status_code}")