# Answer with an FAQ, then an AI, then hand over to a human

_Yes — you plug your own LLM into the message.inbound webhook; the FAQ, then AI, then human order is your code, and so is the "silent bot" (a per-number flag, lifted by "menu")._

Keywords: FAQ, chatbot, bot, AI, LLM, ChatGPT, DeepSeek, artificial intelligence, human agent, advisor, hand over to a human, handoff, transfer, human takeover, silent bot, frequently asked questions, auto reply, customer service

## Scenario

A customer asks a question. Your server answers in this order: (1) a pre-written answer if the question is in your FAQ, (2) otherwise your LLM, with your instructions and your information, (3) and if the customer asks for a human, or the AI does not know, you hand over: the bot **goes silent** for that customer until they write "menu".

**Yes, it can be done with the Dev-API**, and without a template as long as the customer wrote less than 24 h ago (every question guarantees it). The point to understand: the API has **no built-in AI in this flow** and decides nothing. It hands you each message on your webhook and sends what you tell it to send; the FAQ, AI, human routing is **your code**. Plugging in an LLM is detailed in [Wire the webhook to n8n, Zapier, a CRM or an LLM](https://console.geskap.com/docs/webhook-n8n-zapier-crm-llm?lang=en).

## Conversation

```text
Customer : What time do you open?
You      : Monday to Saturday, 7:30 to 18:00.      (FAQ)
           [ Menu ]  [ A person ]
Customer : Do you quote for a wedding of 80 guests?
You      : (your LLM answers with your rates and conditions)
Customer : I want to talk to someone
You      : An advisor is taking over and will answer here.
           Type "menu" to go back to the assistant.
           — the bot no longer answers this customer —
Customer : menu
You      : Hello! What would you like to do?       (the bot resumes)
```

## Code

FAQ answer with two exit buttons:

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages/interactive" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "body": "Du lundi au samedi, 7h30 à 18h.",
  "buttons": [
    { "id": "menu", "title": "Menu" },
    { "id": "human", "title": "Un conseiller" }
  ]
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages/interactive", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "body": "Du lundi au samedi, 7h30 à 18h.",
    "buttons": [
      { "id": "menu", "title": "Menu" },
      { "id": "human", "title": "Un conseiller" }
    ]
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages/interactive");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "body" => "Du lundi au samedi, 7h30 à 18h.",
    "buttons" => [
      ["id" => "menu", "title" => "Menu"],
      ["id" => "human", "title" => "Un conseiller"],
    ],
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages/interactive",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "body": "Du lundi au samedi, 7h30 à 18h.",
        "buttons": [
            {"id": "menu", "title": "Menu"},
            {"id": "human", "title": "Un conseiller"},
        ],
    },
    timeout=15,
)
print(res.status_code, res.json())
```

Server-side routing, called by the webhook handler:

```js
// Node.js
// Express — receive the webhook, verify it, then react.
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.GESKAP_WEBHOOK_SECRET; // shown once when you register the webhook

// Keep the RAW bytes: the signature covers them, not a re-serialized JSON.
app.post("/webhooks/whatsapp", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
  const got = req.get("X-Camairetech-Signature") || "";
  if (got.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer fast: one attempt, 8 s timeout, no retry
  const { event, data } = JSON.parse(req.body.toString("utf8"));
  if (event === "message.inbound") onInbound(data); // your code
});

app.listen(3000);
```

```php
// PHP
<?php
// Receive the webhook, verify it, then react.
$raw = file_get_contents("php://input"); // raw bytes, before json_decode
$expected = "sha256=" . hash_hmac("sha256", $raw, getenv("GESKAP_WEBHOOK_SECRET"));
$got = $_SERVER["HTTP_X_CAMAIRETECH_SIGNATURE"] ?? "";
if (!hash_equals($expected, $got)) {
    http_response_code(401);
    exit;
}
http_response_code(200);
$payload = json_decode($raw, true);
if ($payload["event"] === "message.inbound") {
    on_inbound($payload["data"]); // your code
}
```

```python
# Python
# Flask — receive the webhook, verify it, then react.
import hashlib, hmac, json, os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["GESKAP_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/whatsapp")
def whatsapp_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Camairetech-Signature", "")):
        abort(401)
    payload = json.loads(raw)
    if payload["event"] == "message.inbound":
        on_inbound(payload["data"])  # your code
    return "", 200
```

```js
async function onInbound(data) {
  const text = (data.text || "").trim().toLowerCase();
  const session = await db.getSession(data.from);

  // 3. a human holds the conversation: the bot stays silent, except for "menu"
  if (session.handoff) {
    if (text !== "menu") return;                       // your team answers on its own
    await db.setHandoff(data.from, false);
  }
  if (data.button_id === "human" || /advisor|human|agent|person/.test(text)) {
    await db.setHandoff(data.from, true);              // the bot is now silent
    await notifyTeam(data.from, data.text);            // alert your team
    return sendText(data.from, "An advisor is taking over. Type \"menu\" to go back to the assistant.");
  }
  // 1. FAQ: pre-written answer
  const hit = FAQ.find(([re]) => re.test(text));
  if (hit) return sendFaqButtons(data.from, hit[1]);
  // 2. AI: your LLM, with your instructions
  const answer = await askYourLLM(data.text);
  if (answer) return sendText(data.from, answer);
  // the AI does not know: offer the human
  return sendFaqButtons(data.from, "I would rather hand you to an advisor.");
}
```

`sendText` is a `POST /v1/messages/reply` ([Reply in free text](https://console.geskap.com/docs/repondre-texte-libre?lang=en)) and `sendFaqButtons` is the `POST /v1/messages/interactive` above. The demo application follows exactly this order: tapped option, then FAQ, then keywords, then AI; the advisor relay sets a flag and stops answering until the customer writes "menu".

## Exact limits

| Item | Limit |
|---|---|
| Free-text reply (`text`) | 4,096 characters |
| Button message (`body`) | 1,024 characters, 3 buttons of 20 characters |
| Cost of a reply | 1 credit per 4 messages by default; receiving: 1,000 free messages a month, then 1 credit per 20 |
| Time to reply | 24 h after the customer's last message |

> **Pitfall:** "the bot goes silent" is not an API setting: if you do not keep a per-number flag in your database, your code will keep answering at the same time as your advisor. The API does not tell your bot from a human who writes either: both go through the same calls.

> **Pitfall:** an LLM can make things up. Do not let it announce a price, a stock level or a payment status it did not read in your data, and provide the exit to a human when it hesitates. See [Questions an AI assistant asks](https://console.geskap.com/docs/questions-llm?lang=en).

_Proof — verified in the API source: public_api.py, webhooks.py ; applied by the WhatsApp demo: engine._

---

# Répondre par une FAQ, puis par une IA, puis passer la main à un humain

_Oui — vous branchez votre propre LLM sur le webhook message.inbound ; l'ordre FAQ, puis IA, puis humain est de votre code, et le « bot qui se tait » aussi (un drapeau par numéro, levé par « menu »)._

Mots-clés: FAQ, chatbot, bot, IA, LLM, ChatGPT, DeepSeek, intelligence artificielle, agent humain, conseiller, passer à un humain, handoff, transfert, relais humain, bot silencieux, questions fréquentes, réponse automatique, service client

## Scénario

Un client pose une question. Votre serveur répond dans cet ordre : (1) une réponse écrite d'avance si la question est dans votre FAQ, (2) sinon votre LLM, avec vos consignes et vos informations, (3) et si le client demande un humain, ou si l'IA ne sait pas, vous passez la main : le bot **se tait** pour ce client jusqu'à ce qu'il écrive « menu ».

**Oui, c'est faisable avec la Dev-API**, et sans template tant que le client a écrit il y a moins de 24 h (chaque question le garantit). Le point à comprendre : l'API **n'a pas d'IA intégrée dans ce parcours** et ne décide de rien. Elle vous remet chaque message sur votre webhook et envoie ce que vous lui dites d'envoyer ; l'aiguillage FAQ, IA, humain est **votre code**. Le branchement d'un LLM est détaillé dans [Brancher le webhook sur n8n, Zapier, un CRM ou un LLM](https://console.geskap.com/docs/webhook-n8n-zapier-crm-llm).

## Conversation

```text
Client  : Vous ouvrez à quelle heure ?
Vous    : Du lundi au samedi, 7h30 à 18h.          (FAQ)
          [ Menu ]  [ Un conseiller ]
Client  : Vous faites des devis pour un mariage de 80 personnes ?
Vous    : (votre LLM répond avec vos tarifs et conditions)
Client  : Je veux parler à quelqu'un
Vous    : Un conseiller prend le relais et vous répond ici même.
          Tapez « menu » pour revenir à l'assistant.
          — le bot ne répond plus à ce client —
Client  : menu
Vous    : Bonjour ! Que souhaitez-vous faire ?     (le bot reprend)
```

## Code

Réponse FAQ avec deux boutons de sortie :

```bash
# curl
curl -X POST "https://wa-api.geskap.com/v1/messages/interactive" \
  -H "Authorization: Bearer $GESKAP_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "to": "+237690000001",
  "body": "Du lundi au samedi, 7h30 à 18h.",
  "buttons": [
    { "id": "menu", "title": "Menu" },
    { "id": "human", "title": "Un conseiller" }
  ]
}'
```

```js
// Node.js
const res = await fetch("https://wa-api.geskap.com/v1/messages/interactive", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.GESKAP_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    "to": "+237690000001",
    "body": "Du lundi au samedi, 7h30 à 18h.",
    "buttons": [
      { "id": "menu", "title": "Menu" },
      { "id": "human", "title": "Un conseiller" }
    ]
  }),
});
console.log(res.status, await res.json());
```

```php
// PHP
$ch = curl_init("https://wa-api.geskap.com/v1/messages/interactive");
curl_setopt_array($ch, [
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("GESKAP_API_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POSTFIELDS => json_encode([
    "to" => "+237690000001",
    "body" => "Du lundi au samedi, 7h30 à 18h.",
    "buttons" => [
      ["id" => "menu", "title" => "Menu"],
      ["id" => "human", "title" => "Un conseiller"],
    ],
  ]),
]);
$res = curl_exec($ch);
echo curl_getinfo($ch, CURLINFO_HTTP_CODE), " ", $res;
```

```python
# Python
import os, requests

res = requests.request(
    "POST",
    "https://wa-api.geskap.com/v1/messages/interactive",
    headers={"Authorization": f"Bearer {os.environ['GESKAP_API_KEY']}"},
    json={
        "to": "+237690000001",
        "body": "Du lundi au samedi, 7h30 à 18h.",
        "buttons": [
            {"id": "menu", "title": "Menu"},
            {"id": "human", "title": "Un conseiller"},
        ],
    },
    timeout=15,
)
print(res.status_code, res.json())
```

Aiguillage côté serveur, appelé par le gestionnaire du webhook :

```js
// Node.js
// Express — receive the webhook, verify it, then react.
import express from "express";
import crypto from "node:crypto";

const app = express();
const SECRET = process.env.GESKAP_WEBHOOK_SECRET; // shown once when you register the webhook

// Keep the RAW bytes: the signature covers them, not a re-serialized JSON.
app.post("/webhooks/whatsapp", express.raw({ type: "application/json" }), (req, res) => {
  const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
  const got = req.get("X-Camairetech-Signature") || "";
  if (got.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  res.sendStatus(200); // answer fast: one attempt, 8 s timeout, no retry
  const { event, data } = JSON.parse(req.body.toString("utf8"));
  if (event === "message.inbound") onInbound(data); // your code
});

app.listen(3000);
```

```php
// PHP
<?php
// Receive the webhook, verify it, then react.
$raw = file_get_contents("php://input"); // raw bytes, before json_decode
$expected = "sha256=" . hash_hmac("sha256", $raw, getenv("GESKAP_WEBHOOK_SECRET"));
$got = $_SERVER["HTTP_X_CAMAIRETECH_SIGNATURE"] ?? "";
if (!hash_equals($expected, $got)) {
    http_response_code(401);
    exit;
}
http_response_code(200);
$payload = json_decode($raw, true);
if ($payload["event"] === "message.inbound") {
    on_inbound($payload["data"]); // your code
}
```

```python
# Python
# Flask — receive the webhook, verify it, then react.
import hashlib, hmac, json, os
from flask import Flask, abort, request

app = Flask(__name__)
SECRET = os.environ["GESKAP_WEBHOOK_SECRET"].encode()

@app.post("/webhooks/whatsapp")
def whatsapp_webhook():
    raw = request.get_data()  # raw bytes, before any JSON parsing
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-Camairetech-Signature", "")):
        abort(401)
    payload = json.loads(raw)
    if payload["event"] == "message.inbound":
        on_inbound(payload["data"])  # your code
    return "", 200
```

```js
async function onInbound(data) {
  const text = (data.text || "").trim().toLowerCase();
  const session = await db.getSession(data.from);

  // 3. un humain tient la conversation : le bot se tait, sauf « menu »
  if (session.handoff) {
    if (text !== "menu") return;                       // votre équipe répond de son côté
    await db.setHandoff(data.from, false);
  }
  if (data.button_id === "human" || /conseiller|humain|agent/.test(text)) {
    await db.setHandoff(data.from, true);              // le bot se tait désormais
    await notifyTeam(data.from, data.text);            // alerte votre équipe
    return sendText(data.from, "Un conseiller prend le relais. Tapez « menu » pour revenir à l'assistant.");
  }
  // 1. FAQ : réponse écrite d'avance
  const hit = FAQ.find(([re]) => re.test(text));
  if (hit) return sendFaqButtons(data.from, hit[1]);
  // 2. IA : votre LLM, avec vos consignes
  const answer = await askYourLLM(data.text);
  if (answer) return sendText(data.from, answer);
  // l'IA ne sait pas : proposez l'humain
  return sendFaqButtons(data.from, "Je préfère vous passer un conseiller.");
}
```

`sendText` est un `POST /v1/messages/reply` ([Répondre en texte libre](https://console.geskap.com/docs/repondre-texte-libre)) et `sendFaqButtons` le `POST /v1/messages/interactive` ci-dessus. L'application de démonstration suit exactement cet ordre : option touchée, puis FAQ, puis mots-clés, puis IA ; le relais conseiller met un drapeau et ne répond plus tant que le client n'a pas écrit « menu ».

## Limites exactes

| Élément | Limite |
|---|---|
| Réponse texte libre (`text`) | 4 096 caractères |
| Message à boutons (`body`) | 1 024 caractères, 3 boutons de 20 caractères |
| Coût d'une réponse | 1 crédit pour 4 messages par défaut ; recevoir : 1 000 messages gratuits par mois, puis 1 crédit pour 20 |
| Délai pour répondre | 24 h après le dernier message du client |

> **Piège :** « le bot se tait » n'est pas un réglage de l'API : si vous ne mettez pas de drapeau par numéro dans votre base, votre code continuera de répondre en même temps que votre conseiller. L'API ne fait pas non plus la différence entre votre bot et un humain qui écrit : les deux passent par les mêmes appels.

> **Piège :** un LLM peut inventer. Ne le laissez pas annoncer un prix, un stock ou un statut de paiement qu'il n'a pas lu dans vos données, et prévoyez la sortie vers l'humain quand il hésite. Voir [Questions que pose un assistant IA](https://console.geskap.com/docs/questions-llm).

_Preuve — vérifié dans le code de l'API : public_api.py, webhooks.py ; appliqué par la démo WhatsApp : engine._

Support: WhatsApp +237 6 56 09 88 31 · All recipes: https://wa-api.geskap.com/llms.txt
