A WhatsApp Cloud API webhook that knows when to hand off to a human (Python, no framework)
Most WhatsApp chatbot tutorials stop at "echo the message back". The parts that bite in production are different: checking that the webhook call really came from Meta, knowing whether you are still allowed to send a free-form reply, and getting a customer to a person when the bot shouldn't answer. WhatsApp's own rules make the last two non-optional. Free-form replies are only allowed inside the…
This article details a WhatsApp cloud API webhook written in Python, with no reliance on a framework, that determines when to hand off a conversation to a human agent. The webhook verifies signatures to ensure it is communicating directly with Meta, maintains a 24-hour window for free-form replies, and routes messages accordingly.
Key points include:
- The webhook checks Meta's X-Hub-Signature-256 header against the raw request body to validate the signature, using HMAC-SHA256 hashing.
- It records the time of each customer's last inbound message to track when the 24-hour window for free-form replies begins and ends.
- Messages are classified as plain questions, non-text messages, or requests for a human (e.g., complaints, refunds, cancellations) based on keywords.
- Free-form replies are only allowed within the open customer service window, otherwise the webhook responds with approved templates.
- The routing logic is kept simple, with a list of handoff keywords to trigger escalation to a human agent when necessary.
The code leverages Python's standard library modules hashlib, hmac, json and time. For production use, the last_inbound customer window state would need to be persisted in a database or cache like Redis to survive service restarts and work across multiple instances.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to