Spaces:
Runtime error
Runtime error
Download src/backend/services/whatsapp.py from HAK-Tech/ciro-backend: direct link, hf CLI and curl.
- Browser
- Download file 4.19 kB
-
https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/whatsapp.py
- Command line
-
hf download hf://spaces/HAK-Tech/ciro-backend/src/backend/services/whatsapp.py
-
curl -L -o whatsapp.py https://huggingface.co/spaces/HAK-Tech/ciro-backend/resolve/main/src/backend/services/whatsapp.py
4.19 kB
| """ | |
| WhatsApp emergency dispatch service — Phase 12. | |
| Wraps the Meta WhatsApp Cloud API. Called by the simulation agent when | |
| emergency services are included in the response plan. | |
| This is the ONLY real-world side effect of the simulation phase — every | |
| other output (dispatch ticket, state changes) is simulated. The WhatsApp | |
| message is a real call to a real API sending a real message to pre-verified | |
| demo numbers. | |
| Failure policy: a failed send is logged and returns False — it must never | |
| crash the simulation or the pipeline. The demo proceeds even if the Meta | |
| API is unreachable. | |
| Pre-verified demo numbers are configured via .env: | |
| WHATSAPP_FIRE_BRIGADE_NUMBER | |
| WHATSAPP_POLICE_NUMBER | |
| WHATSAPP_AMBULANCE_NUMBER | |
| All three numbers must be verified in the Meta developer dashboard before | |
| the demo. See the Phase 12 Demo Setup Checklist. | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| import httpx | |
| from backend.core.config import settings | |
| logger = logging.getLogger(__name__) | |
| _GRAPH_API_VERSION = "v18.0" | |
| _TIMEOUT_SECONDS = 10.0 | |
| async def send_whatsapp_alert(to: str, message: str) -> bool: | |
| """Send a WhatsApp text message to a pre-verified number. | |
| Args: | |
| to: E.164 phone number, e.g. "+923001234567". | |
| message: Plain-text body of the message. | |
| Returns: | |
| True on HTTP 200, False on any failure (misconfiguration, network | |
| error, quota, unverified number). | |
| """ | |
| if not settings.whatsapp_token or not settings.whatsapp_phone_id: | |
| logger.info("WhatsApp not configured (WHATSAPP_TOKEN / WHATSAPP_PHONE_ID unset) — skipping") | |
| return False | |
| if not to: | |
| logger.warning("send_whatsapp_alert called with empty 'to' — skipped") | |
| return False | |
| url = f"https://graph.facebook.com/{_GRAPH_API_VERSION}/{settings.whatsapp_phone_id}/messages" | |
| payload = { | |
| "messaging_product": "whatsapp", | |
| "to": to, | |
| "type": "text", | |
| "text": {"body": message}, | |
| } | |
| headers = { | |
| "Authorization": f"Bearer {settings.whatsapp_token}", | |
| "Content-Type": "application/json", | |
| } | |
| try: | |
| async with httpx.AsyncClient(timeout=_TIMEOUT_SECONDS) as client: | |
| response = await client.post(url, json=payload, headers=headers) | |
| if response.status_code == 200: | |
| logger.info("WhatsApp alert sent to %s", to) | |
| return True | |
| logger.warning("WhatsApp API error %d for %s: %s", response.status_code, to, response.text[:200]) | |
| return False | |
| except httpx.TimeoutException: | |
| logger.warning("WhatsApp request timed out for %s", to) | |
| return False | |
| except Exception as exc: # noqa: BLE001 | |
| logger.warning("WhatsApp send failed for %s: %s", to, exc) | |
| return False | |
| async def dispatch_emergency_whatsapp( | |
| ticket_id: str, | |
| crisis_type: str, | |
| location: str, | |
| severity: int, | |
| units_summary: str, | |
| affected_population: str, | |
| ) -> dict[str, bool]: | |
| """Send the CIRO emergency dispatch message to all configured demo numbers. | |
| Sends the same structured message to fire brigade, police, and ambulance | |
| numbers from settings. Skips any number that is not configured. | |
| Returns: | |
| Dict mapping each role to whether the send succeeded: | |
| {"fire_brigade": bool, "police": bool, "ambulance": bool} | |
| """ | |
| message = ( | |
| "\U0001f6a8 CIRO EMERGENCY DISPATCH\n" | |
| f"Crisis: {crisis_type.replace('_', ' ').title()}\n" | |
| f"Location: {location}\n" | |
| f"Severity: {severity}/5\n" | |
| f"Ticket: #{ticket_id}\n" | |
| f"\nUnits Dispatched:\n{units_summary}\n" | |
| f"\nAffected: {affected_population}\n" | |
| "Respond immediately." | |
| ) | |
| results = { | |
| "fire_brigade": await send_whatsapp_alert(settings.whatsapp_fire_brigade_number, message), | |
| "police": await send_whatsapp_alert(settings.whatsapp_police_number, message), | |
| "ambulance": await send_whatsapp_alert(settings.whatsapp_ambulance_number, message), | |
| } | |
| sent = sum(1 for v in results.values() if v) | |
| logger.info("WhatsApp emergency dispatch: %d/3 numbers reached (ticket %s)", sent, ticket_id) | |
| return results | |