偵測 WhatsApp 客戶想找真人,附上摘要把對話轉交給團隊並指派給某人,在真人回覆期間讓所有機器人和 AI 回覆保持安靜,問題解決後再把對話交還給機器人。
機器人處理簡單問題很快。但有些對話需要真人:退款、投訴、出了問題的訂單,或是只想打字問「我可以和真人談談嗎?」的客戶。
在本指南中,您的機器人會把這類對話轉交給團隊,並在團隊處理完畢後收回來。
客戶看到的內容: 他們要求找真人,機器人回覆「謝謝!我們團隊的專人很快會在這裡回覆您。」之後只由您的團隊在同一個 WhatsApp 對話中回覆。機器人和 AI 都不會插話。
您看到的內容: app2email 收件匣(Inbox)中的對話已指派給團隊中的一位成員,並附有一則內部備註,說明機器人為何轉交,以及客戶問了什麼。每一次變更,您的 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(不帶金鑰、不帶內容),或管理 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 號碼:國碼在前,只用數字。聯絡人是客戶的號碼(國碼在前),或是他們的企業範圍使用者 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:電子郵件回覆正在等待聯絡人點選「顯示回覆」,因為 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"(或在收件匣中按「已解決」)會發送 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 上,客戶會看到自己的訊息,然後是「謝謝!我們團隊的專人很快會在這裡回覆您。」,接著是您團隊中某位真人的回覆。在收件匣中,對話已指派給 Ben,轉交備註的黃色標記位於最上方。
您的 webhook 會收到下列事件,每個事件都使用一般的封包格式(id、type、created、number、data),類型也會出現在標頭 X-App2email-Event 中:
| 事件 | 時機 |
|---|---|
conversation.owner_changed | 擁有者變更:真人、代理、暫停,或回到一般狀態;或 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,沙盒金鑰不可用)。
聊天自動化規則也可以轉交:「轉交給真人」是它們的步驟之一,與指派、標示為已解決和加入備註並列。
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>:以 t、一個點和原始內容的 HMAC-SHA256,並以 webhook 的簽署密鑰(whsec_...,包含前綴)作為金鑰。請檢查每個 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。
尊重退訂。 「請勿聯絡」名單不適用於自由格式回覆,因為是客戶先寫給您。例外:當他們的最後一則訊息就是退訂本身時,回覆會回應 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 | 網址中的聯絡人不是號碼或企業範圍使用者 id | 使用完整號碼(國碼在前),或 from_user_id |
404 conversation_not_found | 尚未與這位聯絡人有任何對話 | 使用企業範圍使用者 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 | 號碼的方案不包含指派、備註和開啟 / 已解決 | 試用版和 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)。在它接管對話期間,只有等它交出對話後,回覆才能送出。
可以,對電話號碼而言:從未聯絡過的號碼會得到一筆對話記錄,所以可以先設定擁有者。企業範圍使用者 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 會列出雙向的訊息。