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 24-hour customer service window that opens each time the customer writes to you; outside it you can send approved templates only. And WhatsApp's business messaging policy says automation is fine inside that window as long as there are "prompt, clear, and direct escalation paths" to a human.

This post builds the routing core for that in plain Python (standard library only), so you can drop it behind Flask, FastAPI, a Lambda or whatever already runs your site.

What the router does

  1. Verifies the signature. Meta signs each webhook POST with an HMAC-SHA256 of the raw body, using your app secret, in the X-Hub-Signature-256 header. Reject anything that doesn't match.
  2. Records the window. Every inbound message from a customer resets their 24-hour window, so we store the time of their last message.
  3. Routes each message. Plain questions go to the bot; non-text messages and anything that asks for a person, a refund or a complaint go to a human queue.
  4. Answers "can I reply free-form?" before anything is sent later.

The code

import hashlib, hmac, json, time WINDOW_SECONDS = 24 * 60 * 60 HANDOFF_WORDS = {"human", "agent", "person", "complaint", "refund", "cancel"} last_inbound = {} # wa_id -> unix time of the customer's last message def signature_ok(raw_body: bytes, header: str, app_secret: str) -> bool: """Check Meta's X-Hub-Signature-256 header against the raw request body.""" if not header or not header.startswith("sha256="): return False expected = hmac.new(app_secret.encode(), raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, header[len("sha256="):]) def window_open(wa_id: str, now: float) -> bool: """True while the 24-hour customer service window is open for this customer.""" t = last_inbound.get(wa_id) return t is not None and now - t < WINDOW_SECONDS def route(payload: dict, now: float): """Turn a webhook payload into (wa_id, action) decisions.""" out = [] for entry in payload.get("entry", []): for change in entry.get("changes", []): for msg in change.get("value", {}).get("messages", []): wa_id = msg["from"] last_inbound[wa_id] = now # every inbound message resets the window text = msg.get("text", {}).get("body", "").lower() if msg.get("type") != "text": out.append((wa_id, "handoff: non-text message")) elif HANDOFF_WORDS & set(text.replace("?", " ").split()): out.append((wa_id, "handoff: customer asked for a person")) else: out.append((wa_id, "bot: answer from knowledge base")) return out def can_send_free_form(wa_id: str, now: float) -> str: return "free-form reply allowed" if window_open(wa_id, now) else "template only" 

A few details that matter:

  • Use the raw body for the HMAC. If your framework parses JSON first and you re-serialise it, the bytes change and every signature fails. In Flask that is request.get_data(); in FastAPI, await request.body().
  • hmac.compare_digest avoids leaking timing information when comparing signatures.
  • The window is per customer, keyed on the from number (wa_id). In production, keep last_inbound in Redis or your database, not in memory, so it survives restarts and works across workers.
  • The keyword list is deliberately blunt. It's a safety net, not the main classifier. If you use an LLM to answer, also let the model return a "needs human" flag for anything outside its knowledge, and route that the same way.

Trying it locally

The bottom of the file builds a fake webhook payload with three customers (UK, Australia and Canada numbers from the reserved test ranges), signs it, and runs it through the router:

if __name__ == "__main__": secret = "test-app-secret" body = json.dumps({"entry": [{"changes": [{"value": {"messages": [ {"from": "447700900123", "type": "text", "text": {"body": "Do you ship to Leeds?"}}, {"from": "61400000000", "type": "text", "text": {"body": "I want a refund please"}}, {"from": "14165550123", "type": "image"}]}}]}]}).encode() good = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest() print("signature valid:", signature_ok(body, good, secret)) print("tampered body:", signature_ok(body + b" ", good, secret)) t0 = time.time() for wa_id, action in route(json.loads(body), t0): print(wa_id, "->", action) print("after 3 hours:", can_send_free_form("447700900123", t0 + 3 * 3600)) print("after 25 hours:", can_send_free_form("447700900123", t0 + 25 * 3600)) 

Output:

signature valid: True tampered body: False 447700900123 -> bot: answer from knowledge base 61400000000 -> handoff: customer asked for a person 14165550123 -> handoff: non-text message after 3 hours: free-form reply allowed after 25 hours: template only 

Wiring it to the real endpoint

Your webhook URL needs two handlers:

  • GET for the one-time verification Meta does when you register the URL: check that hub.mode is subscribe and hub.verify_token matches the token you chose, then return hub.challenge as plain text.
  • POST for events: check the signature with signature_ok, return 200 quickly, and do the slow work (calling the model, looking up orders) in a background job. Status updates (sent, delivered, read) arrive on the same endpoint without a messages array, which is why route simply finds nothing to do for them.

When a message is routed to a human, put it in your shared inbox and tell the customer what happens next ("A member of the team will reply here within two hours"). If the reply comes after the window has closed, it has to be an approved template, so keep a "we've replied to your request" utility template ready.

Why the window check is worth the extra table

Meta has charged per delivered message since July 2025, and from 1 October 2026 service replies inside the window are only free for the first 1,000 a month per business number. A follow-up sent outside the window without a template simply fails, so the check prevents both silent failures and surprise template costs. I wrote up the pricing and policy side for business owners in a plain-English WhatsApp AI chatbot guide.

FAQ

Do I need the WhatsApp Business app for this?
No. Webhooks and API replies need a number on the WhatsApp Business Platform (Cloud API). A number used in the Business app can't receive webhooks.

Where do I find the app secret?
In your Meta developer app's basic settings. Keep it in an environment variable, never in the repository.

Can the bot reply to images and voice notes?
Yes, but you have to download the media through the API first. Routing them to a person, as here, is a sensible first version.

Disclosure: I work at Dzimark, where we build custom AI chatbots for websites and WhatsApp.