apps/whatsapp_control_api/app/services/payloads.py
text
from __future__ import annotations
from collections.abc import Iterator
from ..core.security import normalize_whatsapp_number
from ..schemas import InboundMessage
from .env_manager import sanitize_whatsapp_message
def iter_inbound_messages(payload: dict) -> Iterator[InboundMessage]:
for entry in payload.get("entry", []):
for change in entry.get("changes", []):
value = change.get("value", {})
contacts = value.get("contacts", [])
contact_name = None
if contacts:
contact_name = contacts[0].get("profile", {}).get("name")
phone_number_id = value.get("metadata", {}).get("phone_number_id")
for message in value.get("messages", []):
if message.get("type") != "text":
continue
text_body = message.get("text", {}).get("body", "").strip()
if not text_body:
continue
yield InboundMessage(
wa_message_id=message["id"],
from_number=normalize_whatsapp_number(message.get("from", "")),
profile_name=contact_name,
text_body=text_body,
phone_number_id=phone_number_id,
raw_payload=sanitize_whatsapp_message(message),
)