Use cases

WhatsApp AI chatbot with ChatGPT or Claude

A WhatsApp AI chatbot is a loop: HelloHop posts each inbound message to your webhook, your code asks ChatGPT or Claude for an answer, and your code sends the reply with the send API. Reply only to messages people send you, dedupe on the event id, and hand over to a person on a keyword.

Facts (as of October 2026, API v1)

  • HelloHop posts a signed message event to your receiver for each inbound message. The payload has chat_jid, sender_jid, type, text, from_me and is_group.
  • from_me is true when your own number sent the message, for example from the paired phone. A bot that does not check it can answer itself.
  • The delivery id, X-HelloHop-Delivery, equals the id in the event body. Deliveries are retried, so save the id before you answer.
  • Your receiver must answer 2xx within 10 seconds by default. Do the model call after you answer.
  • With the Anthropic SDK, messages.create needs model, max_tokens and messages, and returns the text in content blocks. OpenAI Chat Completions needs model and messages and returns the reply text in the content of the first choice.
  • The unified POST /v1/sessions/{channel}/messages route accepts an Idempotency-Key of up to 255 characters. Repeating the same key and body within 24 hours returns the first result without another send, with the response header Idempotent-Replayed: true.
  • A 504 send_unconfirmed, a timeout, a 409 idempotency_uncertain or a 503 with ambiguous true means the message may have gone out. Treat it as possibly delivered and look at the chat before you send it again.
  • The free sandbox channel allows 180 messages sent a day and 10 new chats a month, counted in Bangkok time. That is enough to build and test the whole flow before you pay.
  • Prices: from $20 USD per number per month, billed annually, with a free sandbox and no per-message fees.

Steps

  1. Add a webhook receiver. PUT your HTTPS URL and a secret of at least 24 characters to /v1/sessions/{channel}/webhooks with the event message.
  2. Verify and save the event. Check X-HelloHop-Signature on the raw body, save the event under its id, then answer 200.
  3. Filter what you answer. Skip your own messages, groups, non-text messages and chats a person has taken over.
  4. Ask the model. Send the message text and a short system prompt. If the call fails, send the handoff text instead of staying silent.
  5. Send once. Save the reply text, then send it with an Idempotency-Key built from the event id.

The loop

A person writes to your number. HelloHop stores the event and posts it to your receiver. The receiver verifies the signature, saves the event and answers 200. Then it asks the model for a reply and sends it with POST /v1/sessions/{channel}/messages to the chat the message came from. The bot speaks only when a person has spoken to it.

Subscribe to inbound messages

curl
API=https://api.hellohop.app/v1

curl -s -X PUT "$API/sessions/$CHANNEL_ID/webhooks" \
  -H "Authorization: Bearer $CHANNEL_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"receivers":[{"url":"https://example.com/webhooks/whatsapp","events":["message"],"secret":"REPLACE_WITH_24_PLUS_CHARACTERS"}]}'

The receiver (Node.js)

The sample implements the guardrails below. The database helpers and a timer that runs recovery before it re-runs pending rows are yours to add. It saves the reply text before sending, so a retry sends the same text and never a second, different answer. The system prompt is a placeholder: write your own.

Node.js: webhook, model, reply
// npm install @anthropic-ai/sdk express
// Anthropic SDK: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript
// Anthropic Messages API: https://platform.claude.com/docs/en/api/messages
// OpenAI Chat Completions: https://developers.openai.com/api/reference/resources/chat
import crypto from 'node:crypto';
import express from 'express';
import Anthropic from '@anthropic-ai/sdk';

const API = 'https://api.hellohop.app/v1';
const { CHANNEL_ID, CHANNEL_TOKEN } = process.env;

// One send. Repeating the same key with the same body returns the first result.
async function sendWhatsApp(key, message) {
  try {
    const res = await fetch(`${API}/sessions/${CHANNEL_ID}/messages`, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${CHANNEL_TOKEN}`,
        'Content-Type': 'application/json',
        'Idempotency-Key': key,
      },
      body: JSON.stringify(message),
      signal: AbortSignal.timeout(15000),
    });
    const data = await res.json().catch(() => ({}));
    const result = { status: res.status, code: data.code, ambiguous: data.ambiguous, id: data.id };
    if (classify(result) === 'retry') {
      // 429 whatsapp_rate_limited carries no Retry-After, so it falls back to 1 second. This helper waits at most 30 seconds;
      // a longer Retry-After is not slept through: result.retryAt (Unix ms) says when the row is due, and your sweep or timer retries then.
      const h = res.headers.get('Retry-After');
      const ms = Math.max(0, (h ? (/^\d+$/.test(h) ? Number(h) * 1000 : Date.parse(h) - Date.now()) : 1000) || 1000);
      result.retryAt = Date.now() + ms;
      await new Promise((resolve) => setTimeout(resolve, Math.min(30000, ms)));
    }
    return result;
  } catch {
    return { status: 0 }; // timeout or lost connection: the message may have gone out
  }
}

// One answer per send: sent (server_ack), queued, retry, unknown or failed.
function classify({ status, code, ambiguous }) {
  if (status === 200) return 'sent'; // server_ack, not delivered
  if (status === 202) return 'queued'; // observe webhooks, do not resend
  // Refused before sending: repeat the same key and body later.
  const refused = ['upstream_unavailable', 'hopsmart_settings_unavailable', 'operator_unresolved'];
  if (status === 429 || (status === 503 && (ambiguous === false || refused.includes(code)))) return 'retry';
  // Possibly sent: look at the chat, never resend.
  if (status === 0 || status >= 500 || code === 'idempotency_uncertain') return 'unknown';
  return 'failed'; // an unlinked channel, idempotency_conflict, a bad request: fix it, do not retry
}
// Your events table: unique key, payload, state, claimed_at (Unix ms), message_id, next_attempt (Unix ms, default 0). Helpers:
//   saveEvent(key, payload)  insert a pending row once; a repeat changes nothing
//   claimSend(key)           atomic pending -> claimed, only when next_attempt <= now; sets claimed_at; true for one caller only
//   finish(key, expected, state, id, nextAttempt) UPDATE only WHERE state = expected; save the message id
//     retry returns to pending and saves nextAttempt (the helper's retryAt); all other outcomes stop automatic sends
//   skipPending(key)         UPDATE pending -> skipped only; never overwrites a claim or an outcome
//   saveBody(key, text) / savedBody(key)  keep the exact text, so a retry sends the same body
// Your timer calls recoverAbandonedClaims first, then re-runs pending rows. Never re-send unknown rows.
// db.run(sql, params) executes SQL in your database; claimed_at is Unix milliseconds.
async function recoverAbandonedClaims() {
  await db.run("UPDATE events SET state = 'unknown' WHERE state = 'claimed' AND (claimed_at IS NULL OR claimed_at < ?)",
    [Date.now() - 5 * 60 * 1000]);
}
const app = express();

const { WEBHOOK_SECRET } = process.env;
if (!WEBHOOK_SECRET || WEBHOOK_SECRET.length < 24) throw new Error('Set WEBHOOK_SECRET to the receiver secret (24 characters or more) before you start');
function validSignature(raw, header) {
  const expected = crypto.createHmac('sha256', WEBHOOK_SECRET).update(raw).digest('hex');
  return typeof header === 'string' && header.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(header), Buffer.from(expected));
}
// Also needed: setHandoff(chat, eventKey) / handoffOwner(chat), a durable event key per chat that a person clears.
const SYSTEM = 'You answer customer questions for ExampleCo in at most three sentences. If you are not sure, say a person will follow up.';
const HANDOFF = 'A person will pick this up and reply here soon.';

// Pick one model call. Both return the reply text, or null when the call fails.
const { ANTHROPIC_API_KEY, ANTHROPIC_MODEL, OPENAI_API_KEY, OPENAI_MODEL } = process.env;
const claude = new Anthropic({ apiKey: ANTHROPIC_API_KEY, timeout: 20000 });
async function askClaude(userText) {
  try {
    const out = await claude.messages.create({ model: ANTHROPIC_MODEL, max_tokens: 300, system: SYSTEM, messages: [{ role: 'user', content: userText }] });
    return out.content.find((b) => b.type === 'text')?.text ?? null;
  } catch {
    return null;
  }
}

async function askChatGPT(userText) {
  try {
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: { Authorization: `Bearer ${OPENAI_API_KEY}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ model: OPENAI_MODEL, messages: [{ role: 'system', content: SYSTEM }, { role: 'user', content: userText }] }),
      signal: AbortSignal.timeout(20000),
    });
    if (!res.ok) return null;
    return (await res.json()).choices?.[0]?.message?.content ?? null;
  } catch {
    return null;
  }
}
const askModel = askClaude;

async function processMessage(event) {
  const m = event.payload;
  const key = `reply-${event.id}`;
  // Reply only to a person who wrote to you, in a direct chat, in plain text.
  if (m.from_me || m.is_group || m.type !== 'text' || !m.text) return skipPending(key);
  const owner = await handoffOwner(m.chat_jid);
  if (owner && owner !== key) return skipPending(key); // allow the original acknowledgement to retry
  if (!(await claimSend(key))) return; // one reply per inbound event
  let reply = await savedBody(key);
  if (!reply) {
    if (/^\s*(human|agent|person)\s*$/i.test(m.text)) {
      reply = HANDOFF;
    } else {
      reply = (await askModel(m.text)) ?? HANDOFF; // a failed model call hands over instead of staying silent
    }
    reply = reply.slice(0, 1000);
    await saveBody(key, reply); // a retry must send this exact text
  }
  if (reply === HANDOFF) await setHandoff(m.chat_jid, key); // saved body first; retry belongs to this event
  const result = await sendWhatsApp(key, { type: 'text', to: m.chat_jid, text: reply });
  await finish(key, 'claimed', classify(result), result.id);
}

app.post('/webhooks/whatsapp', express.raw({ type: 'application/json' }), async (req, res) => {
  if (!validSignature(req.body, req.get('X-HelloHop-Signature'))) return res.sendStatus(401);

  const event = JSON.parse(req.body.toString('utf8'));
  if (event.type !== 'message' || event.payload.from_me) return res.sendStatus(200);
  try {
    await saveEvent(`reply-${event.id}`, req.body.toString('utf8')); // durable first; the event id is the key
  } catch {
    return res.sendStatus(500); // the webhook is delivered again
  }
  res.sendStatus(200);
  processMessage(event).catch(console.error); // a failure leaves a row for the timer
});

app.listen(3003);

Guardrails the sample applies

What the handler does with each send result

Send resultWhat your handler does
200 server_ackWhatsApp acknowledged the send. Mark it sent and save id; this is not a delivery receipt.
202 queuedPersisted in the queue, not delivered. A channel that queues its sends (for example while accepted sends drain) answers every text send this way, with id, status queued, position and expires_at. Mark it queued and save id. Observe the result through webhooks without resending.
429, or 503 with ambiguous false or code upstream_unavailable, hopsmart_settings_unavailable or operator_unresolvedRefused before sending. Honor Retry-After, keep the same key and body, and retry later. The Node helper waits at most 30 seconds before returning retry with a retryAt time, and the pages that keep a due time skip the row until then; the other Node timer pages retry on their next run. The Flask, Python reminder and PHP samples return the time to retry instead of waiting; the Sheets helper saves next_attempt_at and skips the row until then.
504 send_unconfirmed, 409 idempotency_uncertain, 503 with ambiguous true, a timeout or a lost responsePossibly delivered. Mark it unknown and look at the chat before any resend. Never force a resend of an uncertain key with a new key.
409 idempotency_conflictThe same key was used for a different message. Fix how you build the key. The first message is unchanged.
Any other 409Mark it failed. Fix the channel before scheduling another attempt.
Other 4xxThe request is wrong and a retry will not fix it. Log it and move on.

Subscribe to message and message.status webhooks and verify their signatures. The result of a queued send arrives as a message event: match the saved response id to payload.id. message.status reports delivered or read for each id in payload.ids. A send held by HopSmart™ expires 72 hours after acceptance, and the 202 carries expires_at. If no event arrives, read the job with GET /hopsmart/jobs/{id}. Save event ids to deduplicate. Do not resend queued work while waiting for a result.

Who may be messaged

This bot answers people who wrote to you first. To start a conversation yourself, message only people who agreed to hear from you on WhatsApp, and keep to the topic they agreed to.

Questions

Can I use ChatGPT or Claude to answer WhatsApp messages?
Yes. Your webhook receives the message from HelloHop, calls the model API you choose, and sends the answer back with the send API. The sample shows both providers.
How do I stop the bot answering itself?
Skip every event where from_me is true. That flag is set for messages your own number sends, including ones from the paired phone.
How do I avoid answering the same message twice?
Save the event under its id before you answer 200 and claim it before you send. Use the same id in the Idempotency-Key.
How does a person take over?
The sample treats a message that is just human, agent or person as a handoff request. A failed model call hands over the same way, so a model outage reaches a person. It flags the chat, sends the handoff text and stops answering there. Clear the flag when the person is done.
Which model should I use?
Set the model id in an environment variable from your provider's model list. The sample reads it from ANTHROPIC_MODEL or OPENAI_MODEL.

Free sandbox, forever. Upgrade when you're ready.

Start free

HelloHop is an independent WhatsApp API for developers: send and receive messages, automate groups and communities, and get signed webhooks. Not affiliated with WhatsApp or Meta. You link your own number.

WhatsApp AI Chatbot with ChatGPT or Claude | HelloHop