识别 WhatsApp 客户何时想找真人,带着摘要把对话转交给您的团队并分配给具体人员,在真人回复期间让所有机器人和 AI 回答保持安静,问题解决后再把对话交还给机器人。
机器人处理简单问题很快。但有些对话需要真人:退款、投诉、出了问题的订单,或者只是输入“can I talk to someone?”的客户。
在本指南中,您的机器人会把这样的对话转交给您的团队,并在团队处理完后收回。
客户看到的内容: 他们要求找真人,机器人回答“Thanks! A person from our team will answer you here soon.”。从那时起只有您的团队回复,仍在同一个 WhatsApp 对话中。机器人回答和 AI 回答都不会插进来。
您看到的内容: 对话出现在 app2email 收件箱中,分配给您团队里的一个人,并附有一条内部备注,说明机器人为什么转交,以及客户问了什么。每次变化,您的 webhook 都会收到一个事件:谁是对话的负责人、对话分配给了谁、何时标记为已解决。
每个对话(每个联系人一个)都有一个负责人(owner)。负责人表示此刻由谁来回复该联系人。您用一个调用来设置它:PUT /conversations/{contact}/owner。
owner | 含义 | 会发生什么 |
|---|---|---|
""(空) | 正常路由 | 号码的自动回复、对话自动化、AI 回答以及 A2A / OpenClaw 代理,按您设置的方式工作。 |
agent | 由某个自动化负责 | 给其他所有人的标记:“有一个自动化正在处理这个联系人”。AI 回答保持安静,因为它们只回答没有负责人的对话。 |
human | 由真人负责 | app2email 的自动回复和 A2A / OpenClaw 代理不再处理该联系人,AI 回答也一样。由您的团队回复。 |
paused | 自动回答已暂停 | 对自动回复、A2A / OpenClaw 代理和 AI 回答而言,与 human 相同。 |
无论负责人是谁,邮件转发都会继续进行,所以通过邮件接收 WhatsApp 消息的人仍会继续收到。
本指南中的转交流程如下:
message.received。GET /conversations/{contact})。如果已有真人负责,机器人什么都不做。human,并附上 reason 和 summary,告诉客户会有真人来回复,把对话分配给团队中的某个人,并添加一条内部备注。"",并再次回答下一条消息。until_minutes 也可以在设定时间之后让对话自动交还。您的 webhook 仍会收到号码的每个事件,包括由真人负责的对话的 message.received。app2email 自己的自动回复、A2A / OpenClaw 代理和 AI 回答会自行检查负责人。您自己的机器人也必须检查,在每次回答之前。
plan_not_allowed;服务已暂停时会返回 403 service_not_live。请参阅入门指南。POST /webhooks、签名密钥)。本指南在它的基础上加入转交功能。| 权限范围 | 在这里的用途 |
|---|---|
messages:send | 设置负责人(PUT /conversations/{contact}/owner),分配对话(PUT /conversations/{contact}/assignee),标记为已解决(PUT /conversations/{contact}/status),添加备注(POST /conversations/{contact}/notes),给客户发送消息(POST /messages) |
messages:read | 读取单个对话(GET /conversations/{contact})、对话列表、团队(GET /team/members)和备注 |
webhooks:manage | 注册一次 webhook(POST /webhooks),或在 API 密钥页面添加 |
team_inbox_not_in_plan;负责人功能本身在每个付费套餐上都可用。先试一试。 即时沙盒不需要账户:使用 POST https://api.app2email.com/v1/account/sandbox(不带密钥、不带请求体),或 Management MCP 服务器 https://api.app2email.com/mcp/manage 的 create_sandbox 工具,会给您一个演示号码 12025550100 的密钥。它的虚拟客户 12025550105 会要求找真人,所以您可以测试识别功能。即时沙盒有 PUT /conversations/{contact}/owner、GET /conversations、POST /messages 和 GET /events(请在那里读取事件,它没有 webhook)。团队相关的调用(成员、负责人分配、状态、备注)在那里会返回 403 not_in_instant_sandbox。详情:沙盒。
您自己号码上的沙盒密钥不会向 WhatsApp 发送任何内容,但负责人、被分配人、状态和备注是对您对话的真实更改,使用沙盒密钥也一样。请在您自己的联系人上测试这些调用,例如您自己的手机。
在每个请求中,YOUR_NUMBER 是您发送消息所用的 WhatsApp 号码:国家代码在前,只写数字。联系人是客户的号码(国家代码在前),或者他们的 business-scoped 用户 ID(如 AU.1234567890123456),即事件中的 from 或 from_user_id。
GET /conversations/{contact}(权限范围 messages:read)会告诉您负责人、现在是否可以发送自由文本回复,以及是否有邮件回复在等待。请在机器人每次回答之前调用它。
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"))您会得到的响应(由真人负责的对话):
{
"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_..."
}| 字段 | 它告诉您的机器人什么 |
|---|---|
owner | "" 为正常路由,agent、human 或 paused。仅当它是 "" 时才回答(或者 agent,如果 agent 是您自己机器人的标记) |
owner_set_by | 谁设置的,例如 api:Support bot(密钥的名称) |
owner_reason、owner_summary | 转交时附带的内容 |
owner_until | 临时负责人何时结束。过去的时间表示又变回 "" |
owner_set | 设置的内容,即使 owner_until 已过 |
window_state、window_open | open:现在可以发送自由文本回复。closed:只能发送已批准的模板 |
window_closes_at | 窗口关闭的确切时间 |
held_replies | true:邮件回复在等待联系人点按“Show reply”,因为 24 小时窗口已经关闭 |
没有值的字段会从响应中省略,所以正常路由的对话可能完全没有 owner_* 字段。从未发过消息的联系人会返回 404 conversation_not_found。
您的机器人根据 message.received 事件来判断。三种信号效果很好:
type 为 interactive 和 interactive.id 的形式送达。点按回复按钮时,送达的内容如下:
{
"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"
}
}按钮本身是一条普通的交互式消息,在 24 小时窗口内发送:
{
"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" } }
]
}
}
}使用 AI 回答(app2email 的助手)而不是您自己的机器人?它会自行发现并转交:请参阅 AI 回答会自行转交。
PUT /conversations/{contact}/owner(权限范围 messages:send),带上 "owner": "human":
| 字段 | 是否必填 | 填写内容 |
|---|---|---|
owner | 是 | human。也可以是 agent、paused,或用 "" 恢复正常 |
reason | 否 | 原因,用几个词说明(最多 200 个字符),例如 customer asked for a person |
summary | 否 | 到目前为止对话的内容,供接手的人阅读(最多 2000 个字符)。通过邮件阅读 WhatsApp 消息的人也会收到 |
until_minutes | 否 | 1 到 43200。经过这么多分钟后,负责人会自动变回 "" |
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())您会得到的响应(200):更新后的对话,字段与第 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_..."
}
}从现在起,app2email 的自动回复、A2A / OpenClaw 代理和 AI 回答都不再处理这个联系人,号码的每个 webhook 都会收到 conversation.owner_changed。重复设置相同的负责人是无害的,所以可以放心地重试这个调用。
请根据您的营业时间选择 until_minutes。设为 480(8 小时)时,没人接手的对话会自动回到机器人手里。省略它则对话一直留给您的团队,直到有人交还。
在 24 小时窗口开启期间(window_open 为 true,而且确实如此,因为客户刚刚发过消息),用 POST /messages 发送一条简短的自由文本。请用客户的 message_id 构造一个 Idempotency-Key,这样重试永远不会重复发送。
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,
)您会得到的响应(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_..."
}窗口已经关闭了?那么发送会返回 422 outside_24h_window,只有已批准的模板才能联系到客户。
GET /team/members(权限范围 messages:read)会列出可以接手对话的人:号码的所有者和可以回复的成员(查看者不能被分配)。
curl https://api.app2email.com/v1/YOUR_NUMBER/team/members \
-H "Authorization: Bearer YOUR_API_KEY"您会得到的响应:
{
"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 表示自动分配规则暂时跳过这个人;in_rotation: true 表示轮询会给他们分配对话。
然后调用 PUT /conversations/{contact}/assignee(权限范围 messages:send)。assignee 可以是:
user_id 或 email,"auto":由号码的自动分配规则来选择(在选定的成员中轮询,或者回到最后一位回答的人)。规则为 off 时,不会有任何变化,"":没有人。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())您会得到的响应:
{
"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 会收到推送提醒(如果他打开了提醒),收件箱会显示一行活动记录,例如 API (Support bot) assigned this to Ben,每个 webhook 都会收到 conversation.assigned。
负责人和被分配人是两个独立的字段:负责人表示自动回答是否要回避,被分配人表示团队里哪个人处理这个对话。
POST /conversations/{contact}/notes(权限范围 messages:send)会添加一条内部备注:团队在收件箱的对话中会看到它显示为黄色备注,与消息按时间顺序排列。客户永远看不到它。长度为 1 到 4000 个字符。
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,
)您会得到的响应:
{
"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"
}
}备注不是幂等的:重试会再添加一条。每次转交只添加一次(下面的代码在设置负责人之后添加,并且不会重试)。
POST /messages 回复。owner,当它是 human 或 paused 时什么都不做。a2a.respect_owner(默认开启;GET /settings/number 会显示它)。GET /conversations/{contact} 中的 held_replies 为 true。窗口之后,只有已批准的模板才能重新开启对话。GET /conversations?assignee=k3x9q2m7p4z8w1v&status=open(权限范围 messages:read)会列出某个人的未解决对话;assignee=none 会列出未分配的对话。每个条目包含 owner(正常路由时省略)、assignee、assignee_name、status 和 window_open。
有三种方式,您可以全部使用:
PUT /conversations/{contact}/owner 并带上 "owner": ""。真人也可以在控制面板上更改负责人(此时事件中的 set_by 为 dashboard)。until_minutes。到时间之后,owner 又显示为 "",而 owner_set 仍会显示当时设置的内容。PUT /conversations/{contact}/status 带上 "status": "solved"(或在收件箱中点“Solved”)会发送 conversation.status_changed;您的机器人对此作出反应,把负责人设回 ""。# 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)状态调用会得到的响应:
{
"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"
}
}联系人发来新消息会自动重新打开已解决的对话(conversation.status_changed,by 为 contact)。发送回复不会改变状态。
不要自作主张从真人手里收回对话。只在您的团队约定的信号下才交还(已解决、设定的时间,或某个人自己的决定)。owner_set_by 会告诉您是谁设置的负责人。
这段代码把转交功能加到用 API 构建 WhatsApp 聊天机器人中的机器人上。它会校验签名,跳过已处理的事件,在真人负责对话期间保持安静,在客户要求时转交,并在团队标记为已解决时交还对话。请先设置 NUMBER(您的 WhatsApp 号码,数字)、API_KEY 和 WEBHOOK_SECRET(您的 webhook 的 whsec_... 值)。
// 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 "", 200为什么这样设计:
owner 是 human 并在检查处停止,所以这些步骤本来也不会运行两次。"assignee": "auto" 使用号码的自动分配规则。如果套餐中没有团队收件箱,它会返回 403 team_inbox_not_in_plan,这会被记录下来;转交本身仍然有效。human 的情况。paused 的对话仍保持暂停。在 WhatsApp 上,客户会看到自己的消息,然后是“Thanks! A person from our team will answer you here soon.”,再然后是您团队中某位真人的回答。在收件箱中,对话被分配给了 Ben,转交记录之上有那条黄色备注。
您的 webhook 会收到这些事件,每个都在常规的信封中(id、type、created、number、data),类型也在头 X-App2email-Event 中:
| 事件 | 何时发送 |
|---|---|
conversation.owner_changed | 负责人发生变化:human、agent、paused 或回到正常;或者 WhatsApp 的 AI 代理接管或移交了对话(负责人为 whatsapp_ai) |
conversation.assigned | 对话被分配给团队中的某个人,或者没有人:通过收件箱、自动分配规则、自动化、AI 回答或 API |
conversation.note_added | 添加了一条内部备注(永远不会发送给联系人) |
conversation.status_changed | 对话被标记为已解决,或被重新打开(由真人、API 或联系人的新消息触发) |
ai.handover | AI 回答把对话转交给了真人:转交消息已发送,负责人变成了 human |
message.status | “会有真人来回复”的消息已发送、已送达和已读 |
真人已接手(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"
}
}回到机器人(同一个事件,负责人为空):
{
"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"
}
}已分配(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"
}
}已解决(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 和 set_by 会告诉您是谁做出的更改:dashboard:<email>、api:<key name> 或 api、automation: <rule>、ai、auto(自动分配规则),或 contact(新消息重新打开了对话)。
参考文档没有说明 until_minutes 到期时会发送事件。不要依赖事件来判断:请像上面的代码那样,在每次回答之前用 GET /conversations/{contact} 读取 owner。
如果号码使用的是 AI 回答(app2email 的助手,包含在 Professional 套餐和试用中)而不是您自己的机器人,转交功能是内置的。当助手掌握的信息不能覆盖问题、客户要求找真人,或者请求需要团队处理时,助手会把对话转交给真人。它会发送转交消息,把负责人设为 human,并发送 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 为 null。客户收到的文字是 GET /ai-answers/settings 中的 handover_text(为空表示使用默认文字;handover_text_sent 显示实际发送的内容)。可以用 PUT /ai-answers/settings 更改它(权限范围 settings:manage,不能使用沙盒密钥)。
对话自动化规则也可以转交:“hand to a person”是其中的一个步骤,与分配、标记为已解决和添加备注并列。
MCP 服务器 https://api.app2email.com/mcp/conversations 把本指南中的调用做成了工具,使用同样的 Authorization: Bearer 密钥:get_conversation、get_conversation_messages、set_conversation_owner、list_team_members、assign_conversation、set_conversation_status、add_conversation_note、list_conversation_notes。完整的服务器 https://api.app2email.com/mcp 也有这些工具。请参阅用 MCP 让 AI 代理运行您的 WhatsApp 和 MCP。
代理的规则与您的机器人相同:当联系人要求找真人,或者代理无法帮忙时,设置 human,并附上简短的 reason 和 summary;不要收回(agent 或 "")真人已经接手的对话,除非用户要求这样做。
校验每个事件。 头 X-App2email-Signature 的格式是 t=<unix seconds>,v1=<hex>:以 webhook 的签名密钥(whsec_...,包含前缀)为密钥,对 t、一个点和原始请求体计算 HMAC-SHA256。检查每个 v1=(更换密钥后旧密钥仍保留期间会有两个),用恒定时间比较,并拒绝过旧的 t(上面的代码允许 5 分钟)。X-Hub-Signature-256(sha256= 加上原始请求体的 HMAC-SHA256,与 Meta 的签名方式相同)也在其中,仅使用当前密钥。更多内容:Webhooks。
快速响应并去重。 在 10 秒内返回 2xx;不会跟随重定向。失败的事件会在 10 秒、1 分钟、5 分钟、30 分钟、1、2、4、8 和 16 小时后再次发送。事件的 id(也在 X-App2email-Delivery 中)在每次重试时都相同:把您已处理的 id 至少保留两天,保存在数据库或 Redis 中,而不是内存里。
在每次回答之前检查负责人。 仅当 owner 是 ""(或您自己的 agent 标记)时才回答。事件可能延迟或乱序到达,所以请读取对话,而不是相信您看到的最后一个 conversation.owner_changed,并按 data.timestamp 给事件排序。
只转交一次。 先设置负责人;重复设置是安全的。发送“会有真人来回复”的消息时,用客户的 message_id 构造 Idempotency-Key(24 小时内相同的密钥不会再次发送;响应会带有 Idempotent-Replayed: true)。备注和 "assignee": "auto" 不是幂等的:只运行一次。
遵守速率限制。 每个响应都有 X-RateLimit-Limit、X-RateLimit-Remaining、X-RateLimit-Reset(距离恢复满额的秒数)和 X-RateLimit-Policy。超过限制时:429 rate_limited,带有 Retry-After 头和 error.retry_after_seconds;等待相应时间,然后重试。更多内容:限制。
留意 24 小时窗口。 您机器人的“会有真人来回复”消息和您团队的回复都是自由文本消息:它们只在客户最后一条消息之后的 24 小时内有效(app2email 会提前 15 分钟停止;window_closes_at 是确切时间)。之后只能用已批准的模板。如果真人较晚才接手对话,请先检查 window_open。
尊重退订。 Do Not Call 名单不适用于自由文本回复,因为是客户先给您发的消息。例外情况:当他们的最后一条消息就是退订本身时,回复会返回 403 recipient_opted_out,直到他们再次发消息。contact.opted_out 会告诉您何时发生这种情况。
每个号码只有一个回答者。 自动回复、对话自动化、AI 回答和您的机器人看到的是同样的消息。请决定由谁来回答。当您的机器人在处理某个联系人时,负责人设为 agent 可以让 AI 回答回避。
为人来写摘要。 summary 会送到通过邮件阅读 WhatsApp 消息的人那里,备注则在收件箱中被阅读。请保持简短而有用:订单号、客户想要什么、机器人已经尝试过什么。永远不要在其中放入机密或付款信息。
最小权限。 转交需要 messages:send 和 messages:read。把密钥保存在您的服务器上,永远不要放在网页或日志里。密钥可以限制为您服务器的 IP 地址、设置每日上限或设置过期时间。
| 您看到的现象 | 原因 | 解决方法 |
|---|---|---|
400 invalid_owner | owner 不是 ""、agent、human 或 paused | 发送例如 {"owner": "human", "reason": "customer asked for a person"};其他字段是可选的 |
400 invalid_json | 请求体不是有效的 JSON | 检查引号、逗号和括号 |
400 invalid_phone | URL 中的联系人不是号码,也不是 business-scoped 用户 ID | 使用完整号码(国家代码在前),或使用 from_user_id |
404 conversation_not_found | 还没有与此联系人的对话 | 与 business-scoped 用户 ID 的对话在联系人给号码发消息时开始 |
400 invalid_assignee | assignee 不是用户 ID、电子邮件、auto 或 "" | 从 GET /team/members 中取一个 user_id 或 email |
422 not_a_member | 这个人不是号码的所有者,也不是可以回复的成员(查看者不能被分配) | GET /team/members 会列出可以被分配的人 |
400 invalid_conversation_status | status 不是 open 或 solved | 发送 {"status": "solved"} 或 {"status": "open"} |
400 invalid_conversation_note | 备注为空或超过 4000 个字符 | 发送 {"text": "..."},长度为 1 到 4000 个字符 |
403 team_inbox_not_in_plan | 号码的套餐中不包含分配、备注和未解决 / 已解决 | 它们包含在 Trial 和 Professional 套餐中;负责人功能无需它们也能工作 |
503 team_database_pending | 团队收件箱在等待 app2email 一侧的数据库更新 | 请稍后再试;其他一切照常工作 |
403 insufficient_scope | 密钥缺少某项权限(details.required_scope) | 使用带有 messages:send 和 messages:read 的密钥 |
403 not_in_instant_sandbox | 演示号码没有这个调用(例如团队相关的调用) | 使用您自己号码上的沙盒密钥,或普通密钥 |
403 plan_not_allowed、service_not_live | 没有付费套餐,或服务未上线 | 选择一个套餐;已暂停的服务可在设置页面点“Go Live”恢复上线 |
422 outside_24h_window | 客户上次发消息已超过 24 小时 | 改为发送已批准的模板 |
403 recipient_opted_out | 客户的最后一条消息是退订 | 在他们再次发消息之前不要回复 |
429 rate_limited | 此密钥的调用过多 | 等待 Retry-After 秒,然后重试 |
| 转交之后机器人仍在回答 | 您的机器人没有检查 owner,或者号码上还有另一个回答者在运行 | 在每次回答之前读取 GET /conversations/{contact};在控制面板上检查自动回复、自动化和 AI 回答 |
| A2A / OpenClaw 代理仍在回答 | 号码的设置 a2a.respect_owner 已关闭 | GET /settings/number 会显示它;默认是开启的 |
每个响应都有一个 request_id。GET /requests/{request_id} 会显示为它记录的内容(错误和会产生更改的请求,保留 30 天),support@app2email.com 也可以查到。所有错误码:错误。
对于 app2email 的自动回答来说没有区别:无论哪一种,自动回复、A2A / OpenClaw 代理和 AI 回答都不再处理该联系人。当真人处理对话时用 human;当您只想让自动回答对这个联系人暂时停止一段时间时用 paused,例如在您查证某件事的时候。两者都可以用 until_minutes 自动结束。
agent 表示由某个自动化负责这个联系人。它是给其他所有人的标记,并让 AI 回答回避(它们只回答没有负责人的对话)。如果有多个系统在监视同一个号码,而您希望它们看到您的机器人正在处理这个联系人的某件事,就设置它。机器人处理完后,再设回 ""。
WhatsApp 自己的 AI 代理接管了对话。当它接管或移交对话时,conversation.owner_changed 会告诉您(set_by 为 whatsapp,handover 为 control_taken 或 control_passed)。在它接管对话期间,只有在它把对话移交出去之后,回复才能发出。
对于电话号码可以:从未联系过的号码会得到一条对话记录,所以可以先设置负责人。business-scoped 用户 ID 需要联系人先发消息(否则返回 404 conversation_not_found)。
可以。即时沙盒(POST https://api.app2email.com/v1/account/sandbox,不带密钥、不带请求体)会给您一个演示号码 12025550100 的密钥(a2es_...,有效期 7 天)。它的虚拟客户 12025550105 会要求找真人。用 GET /events?wait=25 读取事件,用 PUT /conversations/{contact}/owner 设置负责人;团队相关的调用在那里没有。不会有任何内容送到 WhatsApp。
可以:GET /events?wait=25(权限范围 messages:read)会返回 webhook 收到的同样的事件,id 也相同。请保存响应中的 cursor,并在下一次调用时把它作为 after 传入。用 API 构建 WhatsApp 聊天机器人展示了这个循环。
GET /conversations/{contact}/notes?include_activity=true(权限范围 messages:read)会按从旧到新的顺序列出备注;加上 include_activity=true 后,还会列出活动记录(assigned、unassigned、solved、reopened)。GET /conversations/{phone}/messages 会列出双向的消息。