Here is the goal in one sentence: a customer writes in a messenger, gets an answer in seconds drawn from your own data (stock, price, order status), and the conversation lands in your CRM as a lead — even if the customer closes the app mid-reply.
You will know it works when you can open the CRM, find a lead created from a test message, see the customer's text and the bot's answer attached, and confirm that sending the same message twice did not create two leads.
That last part is where most home-built bots quietly break. The build below is ordered so you hit that problem deliberately, not in production.
What you are actually building
It is not a chatbot in the sense of a language model answering anything. It is a webhook handler with three jobs in a fixed order:
- Receive the incoming message and store it before doing anything else.
- Fetch the facts from an external API (availability, price, order status) and compose a reply from a template.
- Send the reply and write the lead to the CRM, keyed by a stable identifier so retries never duplicate.
Everything else — a language model for phrasing, a fallback to a human — is a layer on top. Get the three jobs right first.
The scope depends on your team. If you are one person, this is a single script behind one endpoint. If you have a support desk, it is the same script plus a rule for when to hand the conversation to a human. Both start from the same handler.
Step 1: Pick the messenger and confirm it has webhooks — owner: you
The AI cannot make this decision for you, and it is the one that kills projects. Before writing a line of code, open the messenger platform's developer documentation and answer three questions:
- Does it support a webhook (a POST to your URL on each message), or only polling?
- What is the reply timeout — how long you have to answer before the platform gives up or retries?
- What identifier comes with each message that you can use as a deduplication key?
If the answer to the first is "polling only", the design changes: you need a scheduler and a cursor of the last processed message, and deduplication becomes mandatory rather than a precaution. If a platform has no API at all, stop — you cannot build this on it, and no amount of prompting changes that. More on the topic: “Building MCP Servers: How to Build Tools and Servers That an AI Agent Actually Uses”.
Done when: you have written down the timeout number and the name of the message ID field from the official docs. Not from a blog post — from the docs, because field names change between API versions.
Step 2: Collect access before you build — owner: you, with the AI telling you what to request
Ask the AI to list every credential the handler touches, then go get each one yourself. Nobody can generate these for you.
| Credential | Where it comes from | What to check by hand |
|---|---|---|
| Messenger bot token | The platform's app dashboard | Scope: send messages, read messages. Nothing more. |
| Webhook verify token | You invent it | Stored in an env var, not in code |
| External data API key | The vendor's account page | Read-only if the API allows it; rate limit in the docs |
| CRM API token | CRM settings, integrations | Scope: create/update contacts and deals only |
The check that matters: open each token's permission list and remove everything the bot does not need. A token with delete rights on your CRM contacts is one prompt-injection or one bug away from a very bad afternoon.
If a vendor only issues a full-access token, put the bot behind a proxy you control that whitelists the three endpoints it calls. That is more work than a scoped token, but it is the only way to bound the damage.
Step 3: Write the handler — owner: AI writes, you read every line
This is the part an AI agent does well: a small, well-defined function. Give it the messenger's payload shape from the docs and ask for a handler that stores the message, fetches data, replies, and writes to the CRM.
A shape that works, in Node.js 20 with the built-in fetch (no SDK needed for a first version):
// handler.js — Node 20+, ESM
const seen = new Map(); // replace with a real store in production
export async function handleMessage(payload) {
const msgId = payload.message.id;
const userId = payload.message.from;
const text = payload.message.text ?? '';
if (seen.has(msgId)) return { status: 'duplicate' };
seen.set(msgId, Date.now());
let facts;
try {
facts = await fetchFacts(text);
} catch (err) {
facts = { error: true };
}
const reply = facts.error
? 'One moment, a colleague will pick this up.'
: composeReply(facts);
await sendMessage(userId, reply);
await upsertLead({ msgId, userId, text, reply });
return { status: 'ok' };
}
async function fetchFacts(text) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 2500);
try {
const res = await fetch(`${process.env.DATA_API}/lookup?q=${encodeURIComponent(text)}`, {
headers: { Authorization: `Bearer ${process.env.DATA_API_KEY}` },
signal: controller.signal,
});
if (!res.ok) throw new Error(`API ${res.status}`);
return await res.json();
} finally {
clearTimeout(timer);
}
}
The AbortController is not decoration. Your external API will occasionally hang, and without a timeout your handler hangs with it, the messenger's retry timer fires, and you get the same message three times. The 2500 ms number is an example — set it below the messenger's reply timeout from Step 1, leaving room for the send and CRM calls.
Done when: you can read the handler and point to the line that handles a duplicate, the line that handles an API failure, and the line that handles an API timeout. If any of those three is missing, the AI's output is not finished.
Step 4: Map the fields between three systems — owner: AI drafts, you verify against live data
Field mapping is where the AI is most confident and most often wrong, because it guesses at field names. Have it draft the mapping, then run one real record through each system and compare.
| Your data | Messenger payload | CRM field |
|---|---|---|
| Customer ID | message.from |
Contact external ID |
| Message text | message.text |
Lead description |
| Bot reply | your reply variable |
Activity note |
| Dedup key | message.id |
Custom field msg_id |
The dedup key belongs in the CRM as its own field, not buried in the description text. That is what lets you run a query later — "how many leads have a msg_id that appears twice" — and get zero.
Done when: a test lead in the CRM shows the customer ID, the message text, the reply, and the msg_id, all populated from one real send.
Step 5: Handle failures on purpose — owner: you define scenarios, AI writes the branches
List the failures you care about, then have the AI write one branch per failure. For this project the list is short and specific:
- External API returns 5xx or times out. Reply with a holding message, still create the lead. The customer must never see silence.
- External API returns "not found". That is a valid answer, not an error — reply that you have no record and hand to a human.
- CRM is down. The reply has already gone out; you cannot lose the lead. Write the payload to a local queue file and retry on a schedule.
- Messenger send fails. Log it with the
msg_idand retry once; if it fails again, alert a human.
The order matters: reply first, then CRM. If the CRM call fails after the reply, the customer is still served and you have a queue to drain. If you write to the CRM first and the reply fails, the customer waits and you have a lead with no conversation.
Done when: you can trigger each failure by hand (point the API URL at a dead host, revoke the CRM token temporarily) and see the expected branch run.
Step 6: Prove nothing gets lost — owner: you, by hand
This is the check people skip, and it is the one that answers the question in the title of this section. Run these by hand, in this order:
- Happy path. Send one message. Success sign: reply arrives, one lead in the CRM with the
msg_id. - Duplicate. Replay the exact same webhook payload (most messenger dashboards have a "resend" button). Success sign: second reply may or may not send depending on your design, but the CRM still has exactly one lead.
- Timeout. Point the external API at a slow endpoint (a
sleeproute you control). Success sign: customer gets the holding message within the timeout, lead still created. - CRM outage. Break the CRM token. Success sign: reply sent, payload in the queue file, and after you restore the token the queue drains and the lead appears once.
- Volume. Send 20 messages in a minute. Success sign: 20 replies, 20 leads, no duplicates, no 429 errors you did not handle.
The fifth test is the one that reveals rate limits you did not read about. If the external API returns 429, your handler must back off and retry, not fail the customer.
Where this breaks in real use
Three failures account for most of the pain, and each has a cheap fix if you plan for it:
- Duplicate leads from retries. The messenger retries when your handler is slow. Fix: the
msg_idcheck must happen before any external call, and the store must survive a restart — aMapin memory does not. Use a table or Redis with a TTL of a day or two. - Personal data leaving your control. Message text and customer IDs are personal data. Under the applicable data protection legislation, you need a lawful basis and a retention limit. Fix: decide how long you keep message text in your queue and CRM, and delete on schedule. The AI will not raise this; you have to.
- API limits you did not read. The external API may cap requests per minute or per day. Fix: cache lookups for a few minutes per customer, and handle 429 with exponential backoff. Check the documented limit — do not guess it.
If the build starts to feel like more than a script — multiple messengers, a real support queue, retention rules — that is the point where handing it off makes sense. asibiont.com takes such integrations on turnkey: the developer names a price, you top up the balance, and the bot, the CRM mapping and the failure handling come back working. Details at https://asibiont.com/en/subscription-tiers.
What it costs you
In time: a single-messenger, single-API bot is a few evenings for one person who can read code, most of it spent on the failure branches, not the happy path. With an AI agent writing the handler, the code appears in minutes; the hours go into verifying field names, reading rate limits, and running the five tests above.
In money: the external data API and the CRM are usually subscription costs you already have or will pay per seat or per call. Hosting one small endpoint is in the lowest tier of any cloud or a few dollars a month on a small VPS. The variable that can surprise you is per-call pricing on the data API — a busy support inbox at a few calls per message adds up, which is why the short cache in Step 6 matters.
In short: the code is the cheap part. The access checks, the field verification and the duplicate test are where the project succeeds or fails, and none of them can be delegated to the AI without you reading the result.
When you are done, the test is simple: send a message, close the app, open the CRM. If the lead is there once, with the conversation attached, and the customer got an answer — the bot works.
If you would rather not build it yourself: we take such a project on — you describe the task, we build it and bring it to a working result, and the developer names the price. The payment goes through a balance top-up on the payment page.