A customer types "hi, do you deliver to Leeds, and how much for the 2-door wardrobe?" into the chat widget on your site. The widget fires back "Thanks, we'll get back to you soon!" — and that is the end of it. The visitor closes the tab, the message sits in a chat log nobody opens, and by evening the lead is gone. The bot answered. It did not save anything.
That gap is the whole point of this build. At the end you get a pipeline that takes every chat message, turns the free text into structured fields, checks the fields a human must confirm, writes the inquiry to your database, pings a manager in a messenger, and tracks whether the notification was actually delivered. You will see it works when a test message lands in the database, the manager gets a ping, and the manager's "got it" reply is written back to the same record.
An auto-reply is not a lead-capture system. The model that actually holds leads is a conveyor, and this article builds it step by step.
What you get at the end, and how you see it working
Picture the finished thing: a customer sends a message; within a few seconds a row appears in your inquiries table with phone, city, and what they want; a manager sees a messenger card with those fields and taps a button; the row gets a confirmed flag. If the manager does not tap within a set time, the record is flagged as undelivered and shows up in a daily list.
That is the result in human terms — not "a chatbot," but a queue where nothing silently disappears. The difference between this and a plain auto-reply is the difference between a doorman who says "welcome" and a receptionist who writes your name in the book. More on the topic: “Auto-Replying to Customer Inquiries: One Queue from Email and Messenger Chats So No Request Gets Lost”.
Auto-reply bot vs. lead-capture pipeline
Before writing code, be clear which of the two you are building, because they fail in completely different ways. More on the topic: “No API? Build a Webhook Bridge to Your Messenger”.
| Criterion | Auto-reply bot | Lead-capture pipeline |
|---|---|---|
| What it does with the message | Sends a canned reply | Parses, validates, stores, notifies |
| Where the inquiry lives | Chat log | Your database |
| What happens if the manager is busy | Nothing | Record flagged, resurfaces |
| What you can measure | Reply rate | Leads captured, confirmed, lost |
An auto-reply suits a FAQ widget — opening hours, return policy, where to park. A pipeline suits anyone whose income depends on someone calling the customer back: renovation quotes, equipment orders, clinic bookings. More on the topic: “Auto-reply to messenger requests with queuing and payment: wiring an n8n bot, a spreadsheet and a payment webhook in one evening”.
The conveyor in five stages
Here is the shape of the whole thing before we touch any code.
Each stage has an owner. Stage 1 (webhook) is infrastructure. Stage 2 (parsing free text into fields) is the AI's job. Stage 3 (confirming phone, city, and what they want) is the human's job — either the customer via a follow-up question, or the manager. Stage 4 (database write + notification) is code. Stage 5 (delivery tracking and repeat-inquiry control) is a scheduled job plus a human reviewing the exceptions list.
A step without a check is not a step. So every stage below ends with what a person verifies.
Access and data you need before building
You cannot start without these, and some of them take longer to obtain than the code itself.
- Chat webhook access. Whoever runs your chat widget (Intercom, Crisp, a custom widget, LiveChat) must let you register an outgoing webhook URL. Some plans gate this behind a higher tier or an app — check the provider's docs for "webhooks" and "outgoing events." If the widget has no webhook and no API, this build is impossible on that widget; you either switch widgets or scrape, which is fragile and not recommended.
- A bot token for the messenger where managers live (Telegram Bot API, Slack app, WhatsApp Business API). For Telegram you create a bot via @BotFather and get a token; for Slack you create an app and get a bot token with chat:write scope. Confirm the exact scope names in the official docs — they change.
- A webhook signing secret, if the chat provider offers one. This lets you verify that incoming calls really come from the provider and not from anyone who found your URL.
- Database access. A Postgres or MySQL instance you can write to, with a dedicated user and password. Even a managed free tier is fine to start.
- An LLM API key for the field-parsing step, with a spending limit set.
Where access is impossible: if the chat provider has no webhook and no API, or if your messenger is a consumer app with no bot API, stop and pick different tools. Do not build around a wall. More on the topic: “Build a Messenger Bot That Answers and Logs Leads in CRM”.
Step 1 — Receive the webhook and verify it (AI scaffolds, human confirms the secret)
The AI writes the endpoint. You confirm that it verifies the signature and returns a 200 fast, before doing any slow work.
# app.py — Flask 3.0+, verify with pip install flask==3.0.3
import hmac, hashlib, os, json
from flask import Flask, request
app = Flask(__name__)
SECRET = os.environ["CHAT_WEBHOOK_SECRET"].encode()
@app.post("/webhook/chat")
def chat_webhook():
raw = request.get_data()
signature = request.headers.get("X-Signature", "")
expected = hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(signature, expected):
return "bad signature", 401
payload = json.loads(raw)
enqueue_for_parsing(payload) # push to a queue, do NOT parse inline
return "ok", 200
The header name (X-Signature) is a placeholder — check your provider's docs for the real one. The important design choice: the endpoint enqueues and returns immediately. Parsing, database writes, and messenger calls happen in a worker. If you do it inline and the LLM is slow, the provider times out, retries, and you get duplicate inquiries — the first real risk below.
Human checks: send a test event from the provider's dashboard, confirm the endpoint returns 200, and confirm a tampered signature returns 401.
Step 2 — Turn free text into fields (AI does this; you check the schema)
The customer's message is prose. The database wants columns. This is where the LLM earns its place: it reads "hi, do you deliver to Leeds, and how much for the 2-door wardrobe?" and returns structured JSON.
# parser.py — openai>=1.40,<2 ; pip install "openai>=1.40,<2"
import json
from openai import OpenAI
client = OpenAI()
SCHEMA_PROMPT = """Extract an inquiry. Return JSON only with keys:
phone (string or null), city (string or null), item (what they want, string or null),
budget (number or null), raw_summary (one sentence).
If a field is not stated, use null. Never invent a phone number."""
def parse_inquiry(text: str) -> dict:
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": SCHEMA_PROMPT},
{"role": "user", "content": text},
],
response_format={"type": "json_object"},
temperature=0,
)
return json.loads(resp.choices[0].message.content)
The model name and response_format are real OpenAI API features as of the current API surface, but model names rotate — confirm the exact model string in OpenAI's docs before deploying. temperature=0 makes output steadier.
Human checks: run ten real past inquiries through the parser and compare the extracted phone, city, and item against what a person would write. Watch specifically for invented phone numbers — the prompt forbids it, but you must verify.
Step 3 — Check the required fields (human decides what is required)
This is the step most auto-reply bots skip entirely, and it is why leads evaporate. The AI gives you fields; a person must decide which ones are non-negotiable and what happens when they are missing.
REQUIRED = ["phone", "city", "item"]
def missing_fields(parsed: dict) -> list[str]:
return [f for f in REQUIRED if not parsed.get(f)]
If fields are missing, the bot asks one follow-up question in the chat — for the phone, for the city. If the customer goes quiet, the record is still written with an incomplete flag so a manager can call the partial info. An incomplete lead you saved beats a complete lead you lost.
Human checks: send a message with no phone and confirm the bot asks for it once, not in a loop; send one with everything and confirm no follow-up question is sent.
Step 4 — Write to the database and notify the manager
Two writes, one transaction-ish flow: insert the inquiry, then send the manager card. The card carries the fields and a confirm button.
# worker.py — psycopg 3.x ; pip install "psycopg[binary]>=3.1"
import psycopg, requests, os
BOT_TOKEN = os.environ["TG_BOT_TOKEN"]
MANAGER_CHAT = os.environ["TG_MANAGER_CHAT_ID"]
def save_and_notify(parsed: dict, chat_id: str):
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
row = conn.execute(
"INSERT INTO inquiries (chat_id, phone, city, item, budget, raw_summary, status) "
"VALUES (%s,%s,%s,%s,%s,%s,%s) RETURNING id",
(chat_id, parsed["phone"], parsed["city"], parsed["item"],
parsed["budget"], parsed["raw_summary"], "new"),
).fetchone()
inquiry_id = row[0]
text = f"New inquiry #{inquiry_id}\nPhone: {parsed['phone']}\nCity: {parsed['city']}\nItem: {parsed['item']}"
requests.post(
f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage",
json={"chat_id": MANAGER_CHAT, "text": text,
"reply_markup": {"inline_keyboard": [[
{"text": "Confirm", "callback_data": f"confirm:{inquiry_id}"}]]}},
timeout=10,
)
When the manager taps Confirm, Telegram sends a callback_query to your bot's webhook; you update inquiries to status='confirmed'. That round-trip is what turns a notification into a confirmation — and it is what lets you later find the ones nobody confirmed.
Human checks: send a test inquiry and confirm the row exists with status new, the messenger card arrives, and tapping Confirm flips the row to confirmed.
Step 5 — Control undelivered and repeat inquiries
Two scheduled jobs close the loop. Neither is glamorous; both are what keep the pipeline honest.
- Undelivered check. Every few minutes, find rows still
newafter N minutes and re-notify or escalate. This catches the case where the messenger call failed silently. - Repeat check. Before inserting, look for an existing inquiry from the same
chat_idwithin a short window. If found, append to it instead of creating a duplicate row.
Where it breaks, and what to do
Three failure modes hit this exact build often.
Duplicates from retries. The chat provider does not get a fast 200 and retries the webhook; you insert the same inquiry twice. Fix: enqueue and return 200 immediately (Step 1), and de-duplicate on the provider's message ID before inserting.
Empty fields from a chatty customer. "Hi, saw your site, interested" parses to nulls everywhere. Fix: the required-field check in Step 3, plus a single follow-up question — and save the incomplete record anyway.
Timeouts on the LLM call. The API is slow or rate-limited; the worker stalls and the queue backs up. Fix: a timeout on the LLM request, a retry with backoff, and a fallback that saves the raw text with item=null so the lead is never dropped. Never let a parsing failure mean a lost customer.
How to verify before you trust it
Run these by hand; each has a clear success sign.
- Happy path: send a complete inquiry. Success: one row, status
new, messenger card, Confirm flips toconfirmed. - Missing phone: send one without a phone. Success: bot asks once, row saved with
incomplete. - Duplicate: send the same message twice within a minute. Success: one row, not two.
- Bad signature: POST to the webhook with a wrong signature. Success: 401, no row created.
- LLM down: temporarily break the API key. Success: row saved with raw text, manager still notified.
- Delivery failure: block the messenger call. Success: undelivered job flags the row and resurfaces it.
If all six pass, the pipeline holds leads the way an auto-reply never could.
What it costs in time and money
Order of magnitude: the code is a day or two of focused work, but obtaining webhook access and bot tokens can take another day depending on your provider's plan. Ongoing cost is small — one LLM call per inquiry, so tens of thousands of inquiries a month is a modest API bill, and a small database and a free-tier server cover the rest. The real variable is your chat provider's plan: some charge for webhook access, some don't. Check that before committing.
If you would rather not assemble this yourself, asibiont.com takes such projects on turnkey — the developer names the price, you top up your balance, and you get the working conveyor. You can see how that works at https://asibiont.com/en/subscription-tiers.
The thing to remember: an auto-reply says hello and forgets. A conveyor remembers, checks, notifies, and follows up when the notification fails. Build the conveyor — the friendly reply is the easy part.
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.