By the WeTakeFwd team. We build AI and WhatsApp automation for small businesses in India, and this is the pattern we use most.
Most WhatsApp chatbots fail in the same way. They answer the easy questions well, then keep answering when they shouldn't: a refund request, an angry customer, or a question the bot simply doesn't understand.
The fix isn't a smarter model. It's a clear rule for when the bot should stop and hand the chat to a person.
In this post we'll build a small Node.js webhook for the WhatsApp Cloud API with:
- an AI reply step (bring your own LLM)
- a handoff function that decides when a human takes over
- a "human mode", where the bot stays silent once a person is handling the chat
- Meta's signature check, so nobody can fake messages to your webhook
The handoff rules
Before any code, decide the rules. Ours are simple:
- The customer asks for a person ("talk to someone", "call me", "agent"), so hand off immediately.
- Sensitive topics (refunds, complaints, payment failures, anything medical or urgent), so hand off immediately.
- The bot is unsure (low confidence), so ask one clarifying question. If it's still unsure, hand off.
- A person has taken over, so the bot stays silent for that chat.
Rule 4 is the one most bots get wrong. Nothing annoys a customer more than a bot interrupting a human conversation.
The decision function
Keeping the logic in one pure function makes it easy to test and easy to change per business:
// Decide whether the bot may answer, or a person must take over. const HUMAN_WORDS = /\b(human|agent|person|call me|talk to (someone|a person)|manager)\b/i; const SENSITIVE = /\b(refund|complaint|legal|payment failed|chest pain|emergency|cancel my)\b/i; export function decide({ text, mode, botReply, failedTurns = 0 }) { if (mode === "human") return { action: "stay_silent", reason: "a person is handling this chat" }; if (HUMAN_WORDS.test(text)) return { action: "handoff", reason: "customer asked for a person" }; if (SENSITIVE.test(text)) return { action: "handoff", reason: "sensitive topic" }; if (!botReply || botReply.confidence < 0.7) { return failedTurns >= 1 ? { action: "handoff", reason: "bot unsure twice in a row" } : { action: "clarify", reason: "bot unsure, ask one clarifying question" }; } return { action: "reply", reason: "confident answer" }; } Testing it
import { decide } from "./handoff.mjs"; const ok = { text: "Is Dr. Mehta free today?", mode: "bot", botReply: { text: "Yes, 11:30 is free.", confidence: 0.92 } }; decide(ok); // { action: 'reply', reason: 'confident answer' } decide({ ...ok, text: "Can I talk to a person please" }); // { action: 'handoff', reason: 'customer asked for a person' } decide({ ...ok, text: "I want a refund" }); // { action: 'handoff', reason: 'sensitive topic' } decide({ ...ok, botReply: { text: "?", confidence: 0.4 } }); // { action: 'clarify', reason: 'bot unsure, ask one clarifying question' } decide({ ...ok, botReply: { text: "?", confidence: 0.4 }, failedTurns: 1 }); // { action: 'handoff', reason: 'bot unsure twice in a row' } decide({ ...ok, mode: "human" }); // { action: 'stay_silent', reason: 'a person is handling this chat' } The keyword lists are deliberately simple. In production you can ask your LLM to classify intent too, but keep the keyword check as a safety net. It never misses an explicit "refund".
The webhook server
You'll need a WhatsApp Business account on the Cloud API, a phone number ID, an access token and your app secret from the Meta developer dashboard. Then:
npm install express import express from "express"; import crypto from "node:crypto"; import { decide } from "./handoff.mjs"; const { VERIFY_TOKEN, APP_SECRET, WA_TOKEN, PHONE_NUMBER_ID, GRAPH_VERSION = "v21.0" } = process.env; const app = express(); // Keep the raw body so we can verify Meta's signature app.use(express.json({ verify: (req, _res, buf) => { req.rawBody = buf; } })); // In production, store this in a database (Redis, Postgres...) const chats = new Map(); // phone -> { mode: "bot" | "human", failedTurns: 0 } // 1. Webhook verification (Meta calls this once when you set up the webhook) app.get("/webhook", (req, res) => { const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN; return ok ? res.status(200).send(req.query["hub.challenge"]) : res.sendStatus(403); }); // 2. Incoming messages app.post("/webhook", async (req, res) => { if (!validSignature(req)) return res.sendStatus(401); res.sendStatus(200); // reply fast; Meta retries slow webhooks const msg = req.body?.entry?.[0]?.changes?.[0]?.value?.messages?.[0]; if (!msg || msg.type !== "text") return; const from = msg.from; const text = msg.text.body; const chat = chats.get(from) ?? { mode: "bot", failedTurns: 0 }; const botReply = chat.mode === "bot" ? await generateReply(text) : null; const { action, reason } = decide({ text, mode: chat.mode, botReply, failedTurns: chat.failedTurns }); if (action === "reply") { chat.failedTurns = 0; await sendText(from, botReply.text); } else if (action === "clarify") { chat.failedTurns += 1; await sendText(from, "Sorry, I want to get this right. Could you tell me a little more?"); } else if (action === "handoff") { chat.mode = "human"; await sendText(from, "I'm passing you to a member of our team. They'll reply here shortly."); await notifyTeam({ from, text, reason }); } chats.set(from, chat); }); function validSignature(req) { const header = req.get("x-hub-signature-256") ?? ""; const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.rawBody ?? "").digest("hex"); return header.length === expected.length && crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected)); } async function sendText(to, body) { await fetch(`https://graph.facebook.com/${GRAPH_VERSION}/${PHONE_NUMBER_ID}/messages`, { method: "POST", headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" }, body: JSON.stringify({ messaging_product: "whatsapp", to, type: "text", text: { body } }), }); } // Plug in your LLM of choice here. Ask it to answer ONLY from your business // information and to return a confidence score between 0 and 1. async function generateReply(text) { return { text: "Yes, 11:30 is free. Shall I book it for you?", confidence: 0.9 }; } // Send the chat to your team: Slack, email, a CRM task or a shared inbox. async function notifyTeam({ from, text, reason }) { console.log(`Handoff needed for ${from}: "${text}" (${reason})`); } app.listen(3000, () => console.log("Webhook listening on :3000")); A few things worth explaining:
- Reply
200immediately. Meta expects a fast response and retries slow webhooks, which can cause duplicate replies. Do the work after acknowledging. - Signature check. Every request carries an
X-Hub-Signature-256header. Comparing it against an HMAC of the raw body with your app secret means only Meta can call your webhook. -
GRAPH_VERSIONis an environment variable because Meta releases new Graph API versions regularly. Check the current one in their docs. - The 24-hour window. You can send free-form replies within 24 hours of the customer's last message. Outside that window, WhatsApp requires approved template messages, so your human team should reply promptly after a handoff.
Plugging in the AI
generateReply() is a stub on purpose. Whatever model you use, three instructions make the biggest difference:
- Answer only from the business's own information (timings, prices, services). Pass it in the prompt or retrieve it from a document store.
- Return a confidence score with every answer, so
decide()can act on it. - Never invent prices, availability or policies. If the answer isn't in the data, say so and let the handoff rule take over.
Handing back to the bot
When your team finishes, set the chat back to { mode: "bot", failedTurns: 0 }. Do this from your CRM or shared inbox with a "resolve" button, or automatically after a quiet period, for example 2 hours with no messages from the team.
What this pattern gives you
- Customers get instant answers to routine questions, at any hour.
- Anything sensitive or unclear reaches a person, with the reason attached.
- Your team never has to fight the bot for the conversation.
The AI does the busywork. People stay in control of the decisions that matter.
If you'd like help setting up something like this for your business, that's what we do at WeTakeFwd: https://wetakefwd.online
What rules do you use for bot-to-human handoff? We'd like to hear them in the comments.