Detect when a WhatsApp customer wants a person, hand the chat to your team with a summary, assign it, keep every bot and AI answer quiet while a person replies, and give it back to the bot when it is solved.
A bot is quick with simple questions. Some chats need a person: a refund, a complaint, an order that went wrong, or a customer who just types "can I talk to someone?".
In this guide your bot hands such a chat to your team, and takes it back when the team is done.
What the customer sees: they ask for a person, and the bot answers "Thanks! A person from our team will answer you here soon." From then on only your team replies, in the same WhatsApp chat. No bot answer and no AI answer gets in between.
What you see: the chat in the app2email Inbox, assigned to one person on your team, with an internal note that says why the bot handed it over and what the customer asked. Your webhook gets an event for each change: who owns the chat, who it is assigned to, and when it is solved.
Every conversation (one per contact) has an owner. The owner says who answers that contact right now. You set it with one call, PUT /conversations/{contact}/owner:
owner | Meaning | What happens |
|---|---|---|
"" (empty) | Normal routing | The number's auto reply, chat automations, AI answers and the A2A / OpenClaw agent work as you set them up. |
agent | An automation owns it | A marker for everyone else: "an automation is handling this contact". AI answers stay quiet, because they only answer a conversation with no owner. |
human | A person owns it | app2email's auto reply and the A2A / OpenClaw agent leave the contact alone, and so do AI answers. Your team replies. |
paused | Automatic answers are paused | The same as human for the auto reply, the A2A / OpenClaw agent and AI answers. |
Email forwarding carries on whatever the owner is, so the people who get the WhatsApp messages by email keep getting them.
The handover in this guide works like this:
message.received.GET /conversations/{contact}). If a person already owns it, the bot does nothing.human with a reason and a summary, tells the customer a person will answer, assigns the chat to someone on the team and adds an internal note."" and answers the next message again. until_minutes can also give the chat back by itself after a set time.Your webhook still gets every event of the number, also message.received for a chat a person owns. app2email's own auto reply, the A2A / OpenClaw agent and AI answers check the owner by themselves. Your own bot must check it too, before every answer.
plan_not_allowed; a paused service answers 403 service_not_live. See Getting started.POST /webhooks, signing secret). This guide adds the handover to it.| Scope | What it is for here |
|---|---|
messages:send | Set the owner (PUT /conversations/{contact}/owner), assign the chat (PUT /conversations/{contact}/assignee), mark it solved (PUT /conversations/{contact}/status), add a note (POST /conversations/{contact}/notes), send the customer a message (POST /messages) |
messages:read | Read one conversation (GET /conversations/{contact}), the list of conversations, the team (GET /team/members) and the notes |
webhooks:manage | Register the webhook once (POST /webhooks), or add it on the API key page |
team_inbox_not_in_plan; the owner itself works on every paid plan.Trying it out. The instant sandbox needs no account: POST https://api.app2email.com/v1/account/sandbox (no key, no body) or the create_sandbox tool of the Management MCP server https://api.app2email.com/mcp/manage answers a key for the demo number 12025550100. Its pretend customer 12025550105 asks for a person, so you can test the detection. The instant sandbox has PUT /conversations/{contact}/owner, GET /conversations, POST /messages and GET /events (read events there, it has no webhooks). The team calls (members, assignee, status, notes) answer 403 not_in_instant_sandbox there. Details: Sandbox.
A sandbox key on your own number sends nothing to WhatsApp, but the owner, the assignee, the status and the notes are real changes to your conversations, also with a sandbox key. Test those calls on a contact of your own, such as your own phone.
In every request, YOUR_NUMBER is the WhatsApp number you send from: country code first, digits only. The contact is the customer's number (country code first) or their business-scoped user id (like AU.1234567890123456), the from or from_user_id of the event.
GET /conversations/{contact} (scope messages:read) tells you the owner, whether a free-form reply can be sent now, and whether email replies are waiting. Call it before every answer of your bot.
curl https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678 \
-H "Authorization: Bearer YOUR_API_KEY"const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678", {
headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
const conv = await res.json();
console.log(conv.owner, conv.window_open);import os, requests
res = requests.get("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"}, timeout=10)
conv = res.json()
print(conv.get("owner"), conv.get("window_open"))What you get back (a chat a person owns):
{
"success": true,
"request_id": "c9slm",
"contact": "61412345678",
"identity_type": "phone",
"phone": "61412345678",
"name": "John",
"window_state": "open",
"window_open": true,
"window_closes_at": "2026-11-22T01:05:44Z",
"last_inbound_at": "2026-11-21T01:20:44Z",
"last_outbound_at": "2026-11-21T01:12:09Z",
"messages": 12,
"owner": "human",
"owner_set_at": "2026-11-21T01:21:00Z",
"owner_set_by": "api:Support bot",
"owner_reason": "customer asked for a person",
"owner_summary": "Wants to move the delivery to Monday.",
"held_replies": false,
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}| Field | What it tells your bot |
|---|---|
owner | "" normal routing, agent, human or paused. Answer only when it is "" (or agent, if agent is your own bot's marker) |
owner_set_by | Who set it, eg api:Support bot (the key's name) |
owner_reason, owner_summary | What was given with the handover |
owner_until | When a temporary owner ends. A time in the past means "" again |
owner_set | What was set, even when owner_until has passed |
window_state, window_open | open: a free-form reply can be sent now. closed: only an approved template |
window_closes_at | The exact time the window closes |
held_replies | true: email replies are waiting for the contact to tap "Show reply", because the 24 hour window had closed |
A field with no value is left out of the answer, so a chat with normal routing may have no owner_* fields at all. A contact who has never written answers 404 conversation_not_found.
Your bot decides this from the message.received event. Three signals work well:
type interactive and interactive.id.A tap on a reply button arrives like this:
{
"id": "evt_Pa3k9m2Lw8Rt5Yp1Zs012",
"type": "message.received",
"created": "2026-11-21T01:20:44.000Z",
"number": "4976659348270",
"data": {
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=",
"from": "61412345678",
"from_user_id": "AU.1234567890123456",
"name": "John",
"type": "interactive",
"text": "Talk to a person",
"interactive": {
"type": "button_reply",
"id": "person",
"title": "Talk to a person"
},
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_SAMPLEk3XbQ9rTzP2mW",
"timestamp": "2026-11-21T01:20:44.000Z"
}
}The button itself is a normal interactive message, sent within the 24 hour window:
{
"to": "61412345678",
"type": "interactive",
"interactive": {
"type": "button",
"body": { "text": "What would you like to do?" },
"action": {
"buttons": [
{ "type": "reply", "reply": { "id": "track", "title": "Track my order" } },
{ "type": "reply", "reply": { "id": "person", "title": "Talk to a person" } }
]
}
}
}Using AI answers (app2email's assistant) instead of your own bot? It notices this by itself and hands over: see AI answers hand over by themselves.
PUT /conversations/{contact}/owner (scope messages:send) with "owner": "human":
| Field | Required | What to put in |
|---|---|---|
owner | yes | human. Also agent, paused, or "" to go back to normal |
reason | no | Why, in a few words (up to 200 characters), eg customer asked for a person |
summary | no | What the chat is about so far, for the person taking over (up to 2000 characters). The people who read the WhatsApp messages by email get it too |
until_minutes | no | 1 to 43200. After this many minutes the owner goes back to "" by itself |
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"owner": "human", "reason": "customer asked for a person", "summary": "Wants to move the delivery to Monday.", "until_minutes": 480}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner", {
method: "PUT",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({
owner: "human",
reason: "customer asked for a person",
summary: "Wants to move the delivery to Monday.",
until_minutes: 480,
}),
});
console.log(res.status, await res.json());res = requests.put(
"https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"owner": "human", "reason": "customer asked for a person",
"summary": "Wants to move the delivery to Monday.", "until_minutes": 480},
timeout=10,
)
print(res.status_code, res.json())What you get back (200): the updated conversation, with the same fields as step 1.
{
"success": true,
"request_id": "own3r",
"conversation": {
"contact": "61412345678",
"identity_type": "phone",
"phone": "61412345678",
"name": "John",
"window_state": "open",
"window_open": true,
"window_closes_at": "2026-11-22T01:05:44Z",
"messages": 12,
"owner": "human",
"owner_set": "human",
"owner_set_at": "2026-11-21T01:21:00Z",
"owner_set_by": "api:Support bot",
"owner_reason": "customer asked for a person",
"owner_summary": "Wants to move the delivery to Monday.",
"owner_until": "2026-11-21T09:21:00Z",
"held_replies": false,
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}
}From now on app2email's auto reply, the A2A / OpenClaw agent and AI answers leave this contact alone, and every webhook of the number gets conversation.owner_changed. Setting the same owner again is harmless, so a retry of this call is safe.
Pick until_minutes to fit your opening hours. With 480 (8 hours) a chat nobody picked up goes back to the bot by itself. Leave it out to keep the chat with your team until someone gives it back.
While the 24 hour window is open (window_open is true, and it is, because the customer just wrote), send a short free-form text with POST /messages. Give it an Idempotency-Key built from the customer's message_id, so a retry never sends it twice.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/messages \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: handoff-wamid.HBgLNjE0MTIzNDU2NzgVAgARGBJTQU1QTEVfVEVTVF9FVkVOVAA=" \
-d '{"to": "61412345678", "type": "text", "text": {"body": "Thanks! A person from our team will answer you here soon."}}'await fetch("https://api.app2email.com/v1/YOUR_NUMBER/messages", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
"Idempotency-Key": `handoff-${messageId}`,
},
body: JSON.stringify({
to: "61412345678",
type: "text",
text: { body: "Thanks! A person from our team will answer you here soon." },
}),
});requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/messages",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}", "Idempotency-Key": f"handoff-{message_id}"},
json={"to": "61412345678", "type": "text",
"text": {"body": "Thanks! A person from our team will answer you here soon."}},
timeout=10,
)What you get back (200):
{
"success": true,
"request_id": "kxrkf",
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI5QTNDQTVCM0Q0Q0Q2RTY3RTgA",
"status": "accepted",
"type": "text",
"from": "4976659348270",
"to": "61412345678",
"window_closes_at": "2026-11-22T01:05:44Z",
"conversation_url": "https://www.app2email.com/conversation/61412345678_4976659348270_..."
}The window closed? Then the send answers 422 outside_24h_window and only an approved template can reach the customer.
GET /team/members (scope messages:read) lists who can take a conversation: the number's owner and the members who may reply (viewers cannot be assigned).
curl https://api.app2email.com/v1/YOUR_NUMBER/team/members \
-H "Authorization: Bearer YOUR_API_KEY"What you get back:
{
"success": true,
"request_id": "t3amx",
"members": [
{ "user_id": "a8d2k4m6p1q3r5s", "name": "Ava", "email": "ava@example.com", "role": "owner", "away": false, "in_rotation": false },
{ "user_id": "k3x9q2m7p4z8w1v", "name": "Ben", "email": "ben@example.com", "role": "member", "away": false, "in_rotation": true }
],
"count": 2,
"auto_assign": "round_robin"
}away: true means the auto-assign rule skips that person for now; in_rotation: true means the round robin gives them conversations.
Then PUT /conversations/{contact}/assignee (scope messages:send). assignee takes:
user_id or an email from the list,"auto": the number's auto-assign rule picks (round robin among the chosen members, or back to the last person who answered). With the rule off, nothing changes,"": nobody.curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"assignee": "auto"}'const res = await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee", {
method: "PUT",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ assignee: "auto" }), // or "k3x9q2m7p4z8w1v", or "ben@example.com"
});
console.log(await res.json());res = requests.put(
"https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/assignee",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"assignee": "auto"}, # or "k3x9q2m7p4z8w1v", or "ben@example.com"
timeout=10,
)
print(res.json())What you get back:
{
"success": true,
"request_id": "as1gn",
"conversation": {
"contact": "61412345678",
"conversation_id": 1234,
"name": "John",
"assignee": "k3x9q2m7p4z8w1v",
"assignee_name": "Ben",
"assigned_at": "2026-11-21T01:21:01.000Z",
"assigned_by": "auto",
"status": "open",
"status_at": null,
"status_by": null
}
}Ben gets a push alert (when he switched alerts on), the Inbox shows an activity line such as API (Support bot) assigned this to Ben, and every webhook gets conversation.assigned.
The owner and the assignee are two separate fields: the owner says whether automatic answers stay away, the assignee says which person on the team has the chat.
POST /conversations/{contact}/notes (scope messages:send) adds an internal note: the team sees it in the Inbox thread as a yellow note, in time order with the messages. The customer never sees it. 1 to 4000 characters.
curl -X POST https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday."}'await fetch("https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ text: "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday." }),
});requests.post(
"https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/notes",
headers={"Authorization": f"Bearer {os.environ['API_KEY']}"},
json={"text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday."},
timeout=10,
)What you get back:
{
"success": true,
"request_id": "n0te1",
"contact": "61412345678",
"conversation_id": 1234,
"note": {
"id": 88,
"kind": "note",
"text": "Bot handover: customer asked for a person. Order 1234, wants to move the delivery to Monday.",
"actor": "api:Support bot",
"actor_name": "API (Support bot)",
"assignee": null,
"assignee_name": null,
"at": "2026-11-21T01:21:02.000Z"
}
}A note is not idempotent: a retry adds a second one. Add it once per handover (the code below does it after the owner is set, and does not retry it).
POST /messages.owner before every answer and does nothing while it is human or paused.a2a.respect_owner (on by default; GET /settings/number shows it).held_replies is true in GET /conversations/{contact} until the contact taps "Show reply". After the window, only an approved template starts the chat again.GET /conversations?assignee=k3x9q2m7p4z8w1v&status=open (scope messages:read) lists the open chats of one person; assignee=none lists the unassigned ones. Each entry has owner (left out for normal routing), assignee, assignee_name, status and window_open.
There are three ways, and you can use all of them:
PUT /conversations/{contact}/owner and "owner": "". A person can also change the owner on the dashboard (the event then says set_by dashboard).until_minutes from the handover. After it, owner reads "" again and owner_set still shows what was set.PUT /conversations/{contact}/status with "status": "solved" (or "Solved" in the Inbox) sends conversation.status_changed; your bot reacts to it by setting the owner back to "".# Mark it solved (it leaves the Inbox's Open view)
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/status \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"status": "solved"}'
# Back to normal routing: the bot answers again
curl -X PUT https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678/owner \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"owner": "", "reason": "solved by the team"}'const headers = { Authorization: `Bearer ${process.env.API_KEY}`, "Content-Type": "application/json" };
const base = "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678";
await fetch(`${base}/status`, { method: "PUT", headers, body: JSON.stringify({ status: "solved" }) });
await fetch(`${base}/owner`, { method: "PUT", headers, body: JSON.stringify({ owner: "", reason: "solved by the team" }) });base = "https://api.app2email.com/v1/YOUR_NUMBER/conversations/61412345678"
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
requests.put(f"{base}/status", headers=headers, json={"status": "solved"}, timeout=10)
requests.put(f"{base}/owner", headers=headers, json={"owner": "", "reason": "solved by the team"}, timeout=10)What you get back from the status call:
{
"success": true,
"request_id": "s0lvd",
"conversation": {
"contact": "61412345678",
"conversation_id": 1234,
"name": "John",
"assignee": "k3x9q2m7p4z8w1v",
"assignee_name": "Ben",
"assigned_at": "2026-11-21T01:21:01.000Z",
"assigned_by": "auto",
"status": "solved",
"status_at": "2026-11-21T02:15:00.000Z",
"status_by": "api:Support bot"
}
}A new message from the contact opens a solved conversation again by itself (conversation.status_changed with by contact). Sending a reply does not change the status.
Do not take a chat back from a person on your own. Give it back only on a signal your team agreed to (solved, a set time, or a person's own call). owner_set_by tells you who set the owner.
This adds the handover to the bot of Build a WhatsApp chatbot with the API. It verifies the signature, skips events it has handled, stays quiet while a person owns the chat, hands over on request, and gives the chat back when the team marks it solved. Set NUMBER (your WhatsApp number, digits), API_KEY and WEBHOOK_SECRET (the whsec_... value of your webhook) first.
// Node.js 18 or newer. npm install express then node handoff.mjs
import crypto from "node:crypto";
import express from "express";
const { NUMBER, API_KEY, WEBHOOK_SECRET, PORT = 3000 } = process.env;
const API = `https://api.app2email.com/v1/${NUMBER}`;
const ASKS_FOR_PERSON = /\b(human|person|someone|staff|manager)\b/i;
const done = new Set(); // handled event ids: use a database table or Redis in production
function verify(raw, header, secret) {
const t = /(?:^|,)\s*t=(\d+)/.exec(header ?? "")?.[1];
const v1 = [...(header ?? "").matchAll(/(?:^|,)\s*v1=([0-9a-f]+)/g)].map((m) => m[1]); // two during a secret change
if (!t || v1.length === 0 || Math.abs(Date.now() / 1000 - Number(t)) > 300) return false;
const expected = crypto.createHmac("sha256", secret).update(t + ".").update(raw).digest("hex");
return v1.some((v) => v.length === expected.length && crypto.timingSafeEqual(Buffer.from(v), Buffer.from(expected)));
}
async function api(method, path, body, idempotencyKey) {
for (let attempt = 1; ; attempt++) {
const res = await fetch(API + path, {
method,
signal: AbortSignal.timeout(4000),
headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json",
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}) },
body: body ? JSON.stringify(body) : undefined,
});
const json = await res.json();
if (res.ok) return json;
const code = json.error?.code;
const wait = Number(res.headers.get("Retry-After") ?? 1);
if (code === "rate_limited" && attempt < 3 && wait <= 3) { await new Promise((r) => setTimeout(r, wait * 1000)); continue; }
if (res.status >= 500 || res.status === 429) throw new Error(`${code} ${json.request_id}`);
console.warn(method, path, code, json.error?.how_to_fix, json.request_id);
return json;
}
}
const later = (promise, what) => promise.catch((err) => console.error(`${what} failed:`, err.message));
function wantsPerson(m) {
return m.interactive?.id === "person" || m.button?.payload === "person" ||
(m.type === "text" && ASKS_FOR_PERSON.test(m.text ?? ""));
}
async function handOver(m, conv) {
const to = m.from || m.from_user_id;
const contact = encodeURIComponent(to);
const reason = "customer asked for a person";
const summary = `${conv.name ?? "The customer"} wrote: "${(m.text ?? "").slice(0, 300)}"`;
// 1. The owner first: from now on no automatic answer reaches this contact. A failure here is retried.
await api("PUT", `/conversations/${contact}/owner`, { owner: "human", reason, summary, until_minutes: 480 });
// 2. The rest is best effort: logged, never retried, so nothing is done twice.
if (conv.window_open) {
await later(api("POST", "/messages", { to, type: "text",
text: { body: "Thanks! A person from our team will answer you here soon." } }, `handoff-${m.message_id}`), "message");
}
await later(api("PUT", `/conversations/${contact}/assignee`, { assignee: "auto" }), "assign");
await later(api("POST", `/conversations/${contact}/notes`, { text: `Bot handover: ${reason}. ${summary}` }), "note");
}
async function onMessage(m) {
const contact = encodeURIComponent(m.from || m.from_user_id);
const conv = await api("GET", `/conversations/${contact}`);
if (conv.owner && conv.owner !== "agent") return; // a person has it, or it is paused: stay quiet
if (wantsPerson(m)) return handOver(m, conv);
// ... your bot's normal answer goes here (see the chatbot guide)
}
async function onSolved(d) {
const contact = encodeURIComponent(d.contact);
const conv = await api("GET", `/conversations/${contact}`);
if (conv.owner === "human") {
await api("PUT", `/conversations/${contact}/owner`, { owner: "", reason: "solved by the team" });
}
}
const app = express();
app.post("/webhook", express.raw({ type: "application/json" }), async (req, res) => {
if (!verify(req.body, req.get("X-App2email-Signature"), WEBHOOK_SECRET)) return res.sendStatus(401);
const event = JSON.parse(req.body);
if (event.test || done.has(event.id)) return res.sendStatus(200);
try {
const d = event.data;
if (event.type === "message.received") await onMessage(d);
if (event.type === "conversation.status_changed" && d.status === "solved") await onSolved(d);
if (event.type === "conversation.owner_changed") {
console.log(`${d.contact}: ${d.previous_owner || "normal"} -> ${d.owner || "normal"} (${d.set_by ?? "?"})`);
}
if (event.type === "ai.handover") console.log(`AI handed ${d.contact} to the team: ${d.reason}`);
done.add(event.id); // only after it worked: a failed event comes again
res.sendStatus(200);
} catch (err) {
console.error("not handled, app2email will send it again:", event.id, err.message);
res.sendStatus(503);
}
});
app.listen(PORT, () => console.log(`handoff bot on http://localhost:${PORT}/webhook`));# Python 3.9 or newer. pip install flask requests then flask --app handoff run --port 3000
import hashlib, hmac, json, os, re, time
from urllib.parse import quote
import requests
from flask import Flask, request
NUMBER, API_KEY, SECRET = os.environ["NUMBER"], os.environ["API_KEY"], os.environ["WEBHOOK_SECRET"]
API = f"https://api.app2email.com/v1/{NUMBER}"
ASKS_FOR_PERSON = re.compile(r"\b(human|person|someone|staff|manager)\b", re.I)
done = set() # handled event ids: use a database table or Redis in production
def verify(raw: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
t = re.search(r"(?:^|,)\s*t=(\d+)", header or "")
v1 = re.findall(r"(?:^|,)\s*v1=([0-9a-f]+)", header or "") # two during a secret change
if not t or not v1 or abs(time.time() - int(t.group(1))) > tolerance:
return False
expected = hmac.new(secret.encode(), t.group(1).encode() + b"." + raw, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(v, expected) for v in v1)
def api(method, path, body=None, idempotency_key=None):
headers = {"Authorization": f"Bearer {API_KEY}"}
if idempotency_key:
headers["Idempotency-Key"] = idempotency_key
for attempt in (1, 2, 3):
res = requests.request(method, API + path, json=body, headers=headers, timeout=4)
data = res.json()
if res.ok:
return data
code = data.get("error", {}).get("code")
wait = int(res.headers.get("Retry-After", "1"))
if code == "rate_limited" and attempt < 3 and wait <= 3:
time.sleep(wait)
continue
if res.status_code >= 500 or res.status_code == 429:
raise RuntimeError(f"{code} {data.get('request_id')}")
print("not done:", method, path, code, data.get("error", {}).get("how_to_fix"), data.get("request_id"))
return data
def later(what, *args, **kwargs):
try:
api(*args, **kwargs)
except Exception as err: # best effort: logged, never retried
print(what, "failed:", err)
def wants_person(m):
return ((m.get("interactive") or {}).get("id") == "person"
or (m.get("button") or {}).get("payload") == "person"
or (m.get("type") == "text" and ASKS_FOR_PERSON.search(m.get("text") or "")))
def hand_over(m, conv):
to = m.get("from") or m.get("from_user_id")
contact = quote(to, safe="")
reason = "customer asked for a person"
summary = f'{conv.get("name") or "The customer"} wrote: "{(m.get("text") or "")[:300]}"'
# 1. The owner first: from now on no automatic answer reaches this contact. A failure here is retried.
api("PUT", f"/conversations/{contact}/owner",
{"owner": "human", "reason": reason, "summary": summary, "until_minutes": 480})
# 2. The rest is best effort, so nothing is done twice.
if conv.get("window_open"):
later("message", "POST", "/messages", {"to": to, "type": "text",
"text": {"body": "Thanks! A person from our team will answer you here soon."}},
idempotency_key=f"handoff-{m['message_id']}")
later("assign", "PUT", f"/conversations/{contact}/assignee", {"assignee": "auto"})
later("note", "POST", f"/conversations/{contact}/notes", {"text": f"Bot handover: {reason}. {summary}"})
def on_message(m):
contact = quote(m.get("from") or m.get("from_user_id"), safe="")
conv = api("GET", f"/conversations/{contact}")
if conv.get("owner") and conv.get("owner") != "agent":
return # a person has it, or it is paused: stay quiet
if wants_person(m):
return hand_over(m, conv)
# ... your bot's normal answer goes here (see the chatbot guide)
def on_solved(d):
contact = quote(d["contact"], safe="")
conv = api("GET", f"/conversations/{contact}")
if conv.get("owner") == "human":
api("PUT", f"/conversations/{contact}/owner", {"owner": "", "reason": "solved by the team"})
app = Flask(__name__)
@app.post("/webhook")
def webhook():
raw = request.get_data()
if not verify(raw, request.headers.get("X-App2email-Signature"), SECRET):
return "bad signature", 401
event = json.loads(raw)
if event.get("test") or event["id"] in done:
return "", 200
d = event.get("data", {})
try:
if event["type"] == "message.received":
on_message(d)
elif event["type"] == "conversation.status_changed" and d.get("status") == "solved":
on_solved(d)
elif event["type"] == "conversation.owner_changed":
print(f'{d["contact"]}: {d.get("previous_owner") or "normal"} -> {d.get("owner") or "normal"} ({d.get("set_by")})')
elif event["type"] == "ai.handover":
print(f'AI handed {d["contact"]} to the team: {d.get("reason")}')
except Exception as err:
print("not handled, app2email will send it again:", event["id"], err)
return "", 503
done.add(event["id"]) # only after it worked: a failed event comes again
return "", 200Why it is built this way:
owner human and stop at the check, so these steps would not run twice anyway."assignee": "auto" uses the number's auto-assign rule. Without the team inbox in the plan it answers 403 team_inbox_not_in_plan, which is logged; the handover itself still works.human. A chat that is paused stays paused.On WhatsApp the customer sees their own message, then "Thanks! A person from our team will answer you here soon.", then the answer of a person from your team. In the Inbox the chat is assigned to Ben, with the yellow note on top of the handover.
Your webhook gets these events, each in the usual envelope (id, type, created, number, data), with the type also in the header X-App2email-Event:
| Event | When |
|---|---|
conversation.owner_changed | The owner changed: human, agent, paused or back to normal; or WhatsApp's AI agent took or passed on the conversation (owner whatsapp_ai) |
conversation.assigned | The chat was given to a person on the team, or to nobody: in the Inbox, by the auto-assign rule, an automation, the AI answer or the API |
conversation.note_added | An internal note was added (never sent to the contact) |
conversation.status_changed | The chat was marked solved, or opened again (by a person, the API, or a new message from the contact) |
ai.handover | AI answers handed a chat to a person: the handover message was sent and the owner became human |
message.status | The "a person will answer" message was sent, delivered and read |
A person took over (conversation.owner_changed):
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs01",
"type": "conversation.owner_changed",
"created": "2026-11-21T01:21:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"owner": "human",
"reason": "customer asked for a person",
"summary": "John wrote: \"Can I talk to a person about my delivery?\"",
"until": "2026-11-21T09:21:00.000Z",
"set_by": "api",
"timestamp": "2026-11-21T01:21:00.000Z"
}
}Back to the bot (the same event, owner empty):
{
"id": "evt_Xq3k9m2Lw8Rt5Yp1Zs07",
"type": "conversation.owner_changed",
"created": "2026-11-21T02:15:01.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"owner": "",
"previous_owner": "human",
"reason": "solved by the team",
"set_by": "api",
"timestamp": "2026-11-21T02:15:01.000Z"
}
}Assigned (conversation.assigned):
{
"id": "evt_Team3k9m2Lw8Rt5Yp1Z01",
"type": "conversation.assigned",
"created": "2026-11-21T01:21:01.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"conversation_id": 1234,
"assignee": "k3x9q2m7p4z8w1v",
"assignee_name": "Ben",
"previous_assignee": null,
"by": "auto",
"timestamp": "2026-11-21T01:21:01.000Z"
}
}Solved (conversation.status_changed):
{
"id": "evt_Team3k9m2Lw8Rt5Yp1Z02",
"type": "conversation.status_changed",
"created": "2026-11-21T02:15:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"conversation_id": 1234,
"status": "solved",
"previous_status": "open",
"by": "dashboard:ben@example.com",
"timestamp": "2026-11-21T02:15:00.000Z"
}
}by and set_by tell you who made the change: dashboard:<email>, api:<key name> or api, automation: <rule>, ai, auto (the auto-assign rule), or contact (a new message opened the chat again).
The reference does not say that an event is sent when until_minutes runs out. Do not rely on an event for that: read owner with GET /conversations/{contact} before every answer, as the code above does.
If the number uses AI answers (app2email's assistant, on the Professional plan and the trial) instead of your own bot, the handover is built in. The assistant hands the chat to a person when its information does not cover the question, the customer asks for one, or the request needs the team. It sends the handover message, sets the owner to human, and sends ai.handover:
{
"id": "evt_Ai3k9m2Lw8Rt5Yp1Zs002",
"type": "ai.handover",
"created": "2026-11-21T01:00:00.000Z",
"number": "4976659348270",
"data": {
"contact": "61412345678",
"conversation_id": 1234,
"message_id": "wamid.HBgLNjE0MTIzNDU2NzgVAgARGBI5QTNDQTVCM0Q0Q0Q2RTY3RTgA",
"text": "Thanks, a person from our team will reply soon.",
"reason": "the customer asks for a refund",
"model": "claude-haiku-5-5",
"owner": "human",
"timestamp": "2026-11-21T01:00:00.000Z"
}
}message_id is null when the handover message could not be sent. The text the customer gets is handover_text in GET /ai-answers/settings (empty means the default; handover_text_sent shows what is sent). It is changed with PUT /ai-answers/settings (scope settings:manage, not with a sandbox key).
Chat automation rules can hand over too: "hand to a person" is one of their steps, next to assign, mark solved and add a note.
The MCP server https://api.app2email.com/mcp/conversations has the calls of this guide as tools, with the same Authorization: Bearer key: get_conversation, get_conversation_messages, set_conversation_owner, list_team_members, assign_conversation, set_conversation_status, add_conversation_note, list_conversation_notes. The full server https://api.app2email.com/mcp has them as well. See Let an AI agent run your WhatsApp with MCP and MCP.
The rule for agents is the same as for your bot: set human with a short reason and a summary when the contact asks for a person or the agent cannot help, and do not take a chat back (agent or "") that a person took, unless the user asked for it.
Verify every event. The header X-App2email-Signature is t=<unix seconds>,v1=<hex>: the HMAC-SHA256 of t, a dot and the raw body, with the webhook's signing secret (whsec_..., prefix included) as the key. Check every v1= (there are two while an old secret is kept after a secret change), compare in constant time, and refuse an old t (the code above allows 5 minutes). X-Hub-Signature-256 (sha256= and the HMAC-SHA256 of the raw body, as Meta signs) is there too, with the current secret only. More: Webhooks.
Answer fast and dedupe. Return 2xx within 10 seconds; redirects are not followed. A failed event is sent again after 10 s, 1 min, 5 min, 30 min, 1, 2, 4, 8 and 16 hours. The event id (also in X-App2email-Delivery) is the same on every retry: keep the ids you handled for at least two days, in a database or Redis rather than in memory.
Check the owner before every answer. Answer only when owner is "" (or your own agent marker). Events can arrive late or out of order, so read the conversation instead of trusting the last conversation.owner_changed you saw, and order events by data.timestamp.
Hand over once. Set the owner first; it is safe to repeat. Send the "a person will answer" message with an Idempotency-Key built from the customer's message_id (the same key within 24 hours is not sent again; the answer comes back with Idempotent-Replayed: true). Notes and "assignee": "auto" are not idempotent: run them once.
Respect the rate limit. Every answer has X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset (seconds until full again) and X-RateLimit-Policy. Over the limit: 429 rate_limited with a Retry-After header and error.retry_after_seconds; wait that long, then retry. More: Limits.
Mind the 24 hour window. Your bot's "a person will answer" message and your team's replies are free-form messages: they work only within 24 hours of the customer's last message (app2email stops 15 minutes early; window_closes_at is the exact time). After that, only an approved template. If a person picks up a chat late, check window_open first.
Respect an opt-out. The Do Not Call list does not apply to free-form replies, because the customer wrote to you. The exception: when their last message was the opt-out itself, a reply answers 403 recipient_opted_out until they write again. contact.opted_out tells you when it happens.
One answerer per number. The auto reply, chat automations, AI answers and your bot all see the same messages. Decide which one answers. An owner of agent keeps AI answers away while your bot handles a contact.
Write summaries for people. The summary reaches the people who read the WhatsApp messages by email, and the note is read in the Inbox. Keep them short and useful: the order number, what the customer wants, what the bot already tried. Never put secrets or payment details in them.
Least access. The handover needs messages:send and messages:read. Keep the key on your server, never in a web page or a log. A key can be limited to your server's IP addresses, have a daily cap, or expire.
| What you see | Why | Fix |
|---|---|---|
400 invalid_owner | owner is not "", agent, human or paused | Send eg {"owner": "human", "reason": "customer asked for a person"}; the other fields are optional |
400 invalid_json | The body is not valid JSON | Check quotes, commas and brackets |
400 invalid_phone | The contact in the URL is not a number or a business-scoped user id | Use the full number, country code first, or the from_user_id |
404 conversation_not_found | No conversation with this contact yet | A conversation with a business-scoped user id starts when the contact writes to the number |
400 invalid_assignee | assignee is not a user id, an email, auto or "" | Take a user_id or email from GET /team/members |
422 not_a_member | That person is not the number's owner or a member who may reply (viewers cannot be assigned) | GET /team/members lists who can be assigned |
400 invalid_conversation_status | status is not open or solved | Send {"status": "solved"} or {"status": "open"} |
400 invalid_conversation_note | The note is empty or longer than 4000 characters | Send {"text": "..."} with 1 to 4000 characters |
403 team_inbox_not_in_plan | Assignment, notes and open / solved are not in the number's plan | They come with the Trial and the Professional plan; the owner works without them |
503 team_database_pending | The team inbox waits for a database update on app2email's side | Try again later; everything else works as before |
403 insufficient_scope | The key lacks a permission (details.required_scope) | Use a key with messages:send and messages:read |
403 not_in_instant_sandbox | The demo number does not have this call (the team calls, for one) | Use a sandbox key on your own number, or a normal key |
403 plan_not_allowed, service_not_live | No paid plan, or the service is not live | Choose a plan; a paused service goes live with "Go Live" on the Settings page |
422 outside_24h_window | The customer last wrote more than 24 hours ago | Send an approved template instead |
403 recipient_opted_out | The customer's last message was the opt-out | Do not reply until they write again |
429 rate_limited | Too many calls for this key | Wait Retry-After seconds, then retry |
| The bot still answers after the handover | Your bot does not check owner, or another answerer runs on the number | Read GET /conversations/{contact} before every answer; check the auto reply, automations and AI answers on the dashboard |
| The A2A / OpenClaw agent still answers | The number's setting a2a.respect_owner is off | GET /settings/number shows it; it is on by default |
Every answer has a request_id. GET /requests/{request_id} shows what was logged for it (errors and requests that change something, kept 30 days), and support@app2email.com can find it too. All codes: Errors.
For app2email's automatic answers there is none: with either, the auto reply, the A2A / OpenClaw agent and AI answers leave the contact alone. Use human when a person has the chat, and paused when you only want the automatic answers to stop for this contact for a while, for example while you check something. Both can end by themselves with until_minutes.
agent says that an automation owns the contact. It is a marker for everyone else, and it keeps AI answers away (they answer only a conversation with no owner). Set it if several systems watch the same number and you want them to see that your bot is in the middle of something with this contact. Set "" again when the bot is done.
WhatsApp's own AI agent holds the conversation. conversation.owner_changed tells you when it takes or passes on the chat (set_by whatsapp, with handover control_taken or control_passed). While it holds the chat, a reply goes through only after it passes the conversation on.
Yes, for a phone number: a number that has never been in touch gets a conversation record, so the owner can be set first. A business-scoped user id needs the contact to write first (404 conversation_not_found otherwise).
Yes. The instant sandbox (POST https://api.app2email.com/v1/account/sandbox, no key, no body) gives a key (a2es_..., valid 7 days) for the demo number 12025550100. Its pretend customer 12025550105 asks for a person. Read the events with GET /events?wait=25 and set the owner with PUT /conversations/{contact}/owner; the team calls are not there. Nothing reaches WhatsApp.
Yes: GET /events?wait=25 (scope messages:read) returns the same events a webhook gets, with the same id. Keep the answer's cursor and pass it as after on the next call. Build a WhatsApp chatbot with the API shows the loop.
GET /conversations/{contact}/notes?include_activity=true (scope messages:read) lists the notes, oldest first, with the activity lines (assigned, unassigned, solved, reopened) when you add include_activity=true. GET /conversations/{phone}/messages lists the messages of both directions.
Receive messages on a signed webhook and answer them from your own code.
Approved utility templates for confirmations and reminders, with delivery status.
One template to a list or a segment, with consent records and the Do Not Call list.
Connect Claude or another agent to your number with scoped keys and approvals.
Send a payment link in the chat and hear when it is paid.