Chatbot Code Python You Can Run Today: Generate a Script From Your Own FAQ, Then Add Memory, Lead Capture and a Web Endpoint (Free Code Generator)

Chatbot code Python tutorials usually stop at a toy that answers “hello” and forgets everything you said a line ago. This guide gives you four small files you can copy and run: an FAQ matcher with no dependencies, a bot that remembers where it is in a conversation and collects a callback request, a runner that joins the two, and a Flask endpoint with one memory per visitor. A free generator writes the first file from your own questions and answers, and shows you exactly what it will reply before you run it. At the end, we look honestly at when a ready-made chat widget is the better choice.

4files, each run before publishing
0dependencies for the first three
1pip install for the web version
3.9+Python version that runs all four

⚡ In short

  • Script 1 matches a visitor’s words against your FAQ with a simple overlap score. Standard library only.
  • Script 2 is a tiny state machine: it asks for a name, a valid mobile number and a time slot, one step at a time, and saves the lead to a CSV file.
  • Script 3 joins them, and script 4 puts them behind a Flask endpoint where every visitor gets their own memory.
  • The free generator turns your FAQ into script 1 and previews every answer, including close calls that would pick the wrong reply.
  • Writing the bot is the easy part. A team inbox, alerts, opening hours and handover are the hard part, and that’s where a hosted widget usually wins.
Chatbot code python in LiveChatBot: the one-line install code for WordPress, Shopify, Wix and other sites
How it looks in LiveChatBot: the one-line install code for WordPress, Shopify, Wix and other sites.

Before you start

What you need, and what you’ll have at the end

You need Python 3.9 or newer and a terminal. On a Mac or Linux the command is usually python3; on Windows, install Python from python.org and use py. Check with python3 --version before anything else, because most “the code doesn’t work” problems are really the wrong Python.

Make a folder for the project and a virtual environment inside it, so anything you install stays in this project and doesn’t touch the rest of your computer. The commands are below. You only need the virtual environment for script 4, which uses Flask, but it’s a good habit from the start.

By the end you’ll have four files in one folder:

  • faq_bot.py answers common questions from a list you write. You can generate it with the tool further down.
  • callback_bot.py remembers which step of a conversation it’s on and collects a callback request.
  • chat.py gives the callback flow first say and lets the FAQ matcher answer everything else.
  • app.py serves the bot over HTTP, with a test page, so a browser can talk to it.

All four were run before this guide was published, and the example conversations below are their real output. Every business detail in them (delivery days, ₹999 free shipping, ₹5,000 COD limit) is illustrative; swap in your own.

If you’d rather see a language-model version, our AI chatbot Python tutorial covers grounded AI answers with a fallback, and tool calling in Python shows how a model can run your own functions. This guide stays model-free on purpose: everything here runs offline, costs nothing per message and behaves the same way every time.

mkdir shop-bot
cd shop-bot
python3 -m venv .venv
source .venv/bin/activate        # Windows: .venv\Scripts\activate
python3 --version                # 3.9 or newer

Script 1 · FAQ matcher

Answer common questions with about 80 lines of plain Python

Save this as faq_bot.py and run python3 faq_bot.py. Type quit to stop.

# faq_bot.py: a small FAQ chatbot. Python 3.8+, standard library only.
# Run it with:  python3 faq_bot.py   (on Windows:  py faq_bot.py)
import re

GREETING = "Hi! Ask me about delivery, returns, payment or our hours. Type quit to stop."
FALLBACK = "Sorry, I'm not sure about that. Leave your number and our team will call you."
THRESHOLD = 0.34  # 0 to 1. Raise it if you get wrong answers, lower it if you get too many fallbacks.

STOP = set("""a an the is are am do does did you your we our i my me can could will would
to of in on for at it this that please have has any there what when how much many""".split())

# Words customers use that mean the same thing. Left side -> word used for matching.
SYNONYMS = {"deliver": "delivery", "shipping": "delivery", "ship": "delivery", "courier": "delivery",
            "cod": "cash", "refund": "return", "exchange": "return", "timing": "hour",
            "open": "hour", "price": "cost", "charge": "cost", "fee": "cost"}

# Each entry: (ways people ask it, the answer). Add as many wordings as you like.
FAQ = [
    (["do you deliver to my city", "how many days for delivery", "delivery time"],
     "We deliver across India in 3 to 6 working days."),
    (["delivery charges", "is shipping free"],
     "Delivery is free on orders over ₹999. Below that it costs ₹60."),
    (["is cash on delivery available", "can i pay cod"],
     "Yes, cash on delivery is available on orders up to ₹5,000."),
    (["how do i return a product", "refund policy", "can i exchange size"],
     "You can return or exchange unused items within 7 days of delivery."),
    (["what are your opening hours", "are you open on sunday"],
     "Our team is online Monday to Saturday, 10 am to 7 pm."),
]


def words(text):
    """Lower-case words, minus filler words, with simple plurals and synonyms folded."""
    out = set()
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        if w in STOP:
            continue
        if len(w) > 3 and w.endswith("s"):
            w = w[:-1]
        out.add(SYNONYMS.get(w, w))
    return out


def score(a, b):
    """Share of words two questions have in common (Dice score, 0 to 1)."""
    if not a or not b:
        return 0.0
    return 2 * len(a & b) / (len(a) + len(b))


def best_answer(text):
    """Return (answer, score) for the closest FAQ wording, or the fallback."""
    q = words(text)
    best, best_score = None, 0.0
    for variants, answer in FAQ:
        for v in variants:
            s = score(q, words(v))
            if s > best_score:
                best, best_score = answer, s
    if best is None or best_score < THRESHOLD:
        return FALLBACK, best_score
    return best, best_score


def main():
    print("Bot:", GREETING)
    while True:
        try:
            text = input("You: ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if text.lower() in {"quit", "exit", "bye"}:
            break
        if text:
            reply, s = best_answer(text)
            print("Bot:", reply, f"  [score {s:.2f}]")


if __name__ == "__main__":
    main()

How the matching works

The words() function lower-cases the text, keeps only letters and digits, drops filler words like “is”, “the” and “do you”, turns simple plurals into singulars and folds synonyms together, so “shipping”, “ship” and “courier” all become “delivery”, and “COD” becomes “cash”.

The score() function compares two sets of words with a Dice score: twice the number of shared words, divided by the total number of words in both. It runs from 0 (nothing shared) to 1 (identical). A worked example: “COD available?” becomes {cash, available}; the stored wording “is cash on delivery available” becomes {cash, delivery, available}. They share two words, so the score is 2 × 2 ÷ (2 + 3) = 0.8, comfortably above the 0.34 threshold.

best_answer() tries every wording of every answer and keeps the highest score. Below the threshold, it returns the fallback instead of guessing. That one rule matters more than any clever matching: a bot that says “I’m not sure, leave your number” loses far less trust than one that answers the wrong question confidently.

Real output

Typing “shipping charges?” gives the delivery-cost answer with a score of 1.00. “refund kab milega” gives the returns answer at 0.40, because “refund” is folded into “return”. “do you have a discount code” gets the fallback at 0.00, which is exactly right: there’s no answer for it.

Free tool

Generate your chatbot code Python file from your own FAQ

Write each answer once, with every wording customers use. Add the questions you want to test. The tool previews each reply with the same rules the script uses, flags lines that can never match, and writes faq_bot.py for you.

Your FAQ, one answer per line: wording 1; wording 2 | answer. Add every way customers ask it, separated by semicolons.

Test questions, one per line, written the way customers really type.

Runs only in your browser; nothing is sent or saved. The preview uses exactly the same matching rules as the generated script.

Reading the preview

Fix close calls before you ever run the script

The preview table is the most useful part of the generator, because it shows the mistakes a script makes silently. Load the example and look at three rows.

“size for 40 chest” gets the returns answer. Its words are {size, 40, chest}. The returns entry has the wording “can i exchange size”, which shares “size”, and so does “size chart”. Both score 0.40, a tie, and the entry listed first wins. The tool marks this as a close call. The fix is to add a more specific wording to the size answer, such as “size for chest”, and test again. Now the size answer scores far higher and the tie disappears.

“is the blue kurta in stock” falls back. No stored wording shares a single word with it. That’s the right behaviour if you don’t want the bot answering stock questions, which change daily. If you do, add an entry, but only when the answer is stable.

“do you ship to kerala” is a close call. It shares “delivery” with both delivery entries. The bot picks the delivery-time answer, which is probably what the customer wants, but a visitor asking about cost would get the same reply. Adding “ship to” wordings to the right entry makes the choice deliberate.

Three rules keep the matcher honest:

  • Add wordings, not answers. Five wordings for one answer beats five near-identical answers competing with each other.
  • Use real customer text. Copy questions from WhatsApp, email and call notes, typos and Hinglish included. Our guide on building a chatbot from the questions you already get shows how to collect them.
  • Move the threshold last. Lowering it to 0.25 answers more questions but makes more wrong guesses. Fix wordings first, then adjust.

For a proper measurement, with a labelled test set, pytest and a confusion table, see our chatbot Python testing guide.

Script 2 · Memory

A bot that knows which question it asked last

Most beginner bots treat every message as brand new. This one keeps a small state, so “Riya” is understood as a name because the bot just asked for one.

# callback_bot.py: remembers where it is in a conversation and collects
# a name, a mobile number and a time slot, one question at a time.
import csv
import re
from datetime import datetime
from pathlib import Path

LEADS_FILE = Path("leads.csv")
SLOTS = ("morning", "afternoon", "evening")
TRIGGER = re.compile(r"\b(call ?back|call me|phone me|ring me|talk to (a|someone|a person))\b")


def normalise_phone(text):
    """Return a 10-digit Indian mobile number, or None if it isn't one."""
    digits = re.sub(r"\D", "", text)
    if len(digits) == 12 and digits.startswith("91"):
        digits = digits[2:]
    elif len(digits) == 11 and digits.startswith("0"):
        digits = digits[1:]
    if re.fullmatch(r"[6-9]\d{9}", digits):
        return digits
    return None


def save_lead(data):
    new_file = not LEADS_FILE.exists()
    with LEADS_FILE.open("a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        if new_file:
            writer.writerow(["time", "name", "phone", "slot"])
        writer.writerow([datetime.now().isoformat(timespec="seconds"),
                         data["name"], data["phone"], data["slot"]])


class CallbackBot:
    def __init__(self):
        self.state = "idle"   # idle -> name -> phone -> slot -> idle
        self.data = {}

    def reply(self, text):
        """Return a reply, or None when this bot has nothing to say."""
        text = text.strip()
        low = text.lower()
        if self.state != "idle" and low in {"cancel", "stop"}:
            self.state, self.data = "idle", {}
            return "No problem, I've cancelled that. Ask me anything else."

        if self.state == "idle":
            if TRIGGER.search(low):
                self.state = "name"
                return "Sure, we can call you. What's your name?"
            return None

        if self.state == "name":
            if not 2 <= len(text) <= 60:
                return "Please type your name (2 to 60 characters)."
            self.data["name"] = text
            self.state = "phone"
            return f"Thanks, {text}. Which mobile number should we call?"

        if self.state == "phone":
            phone = normalise_phone(text)
            if phone is None:
                return "That doesn't look like a 10-digit mobile number. Try again, e.g. 98765 43210."
            self.data["phone"] = phone
            self.state = "slot"
            return "When suits you: morning, afternoon or evening?"

        if self.state == "slot":
            slot = next((s for s in SLOTS if s in low), None)
            if slot is None:
                return "Please choose morning, afternoon or evening."
            self.data["slot"] = slot
            save_lead(self.data)
            name = self.data["name"]
            self.state, self.data = "idle", {}
            return f"Done, {name}. We'll call you in the {slot}. Anything else?"

Why a state machine

The bot is always in one of four states: idle, name, phone or slot. Each message is handled according to the current state, and a valid answer moves it to the next one. That’s all “memory” means here: one variable that remembers where the conversation is, and one dictionary that holds what’s been collected so far.

Validation at every step

The phone step accepts “98765 43210”, “+91 98765 43210” and “098765 43210”, strips everything except digits, removes a leading 91 or 0, and checks for ten digits starting with 6 to 9, the pattern Indian mobile numbers follow. Anything else gets a friendly retry message, not a crash. The name step rejects empty or very long text. Typing “cancel” or “stop” mid-flow resets it, which visitors need more often than you’d think.

Where the lead goes

Each completed request is appended to leads.csv with a timestamp, so you can open it in Excel or Google Sheets. That file contains personal data: keep it out of public folders and version control, and delete old rows you no longer need. India’s DPDP Act 2023 expects you to collect only what you need and protect it.

Script 3 · Putting them together

The flow gets first say, the FAQ answers the rest

# chat.py: the callback flow gets first say; the FAQ matcher answers the rest.
from callback_bot import CallbackBot
from faq_bot import GREETING, best_answer


def respond(bot, text):
    flow_reply = bot.reply(text)
    if flow_reply is not None:
        return flow_reply
    answer, _ = best_answer(text)
    return answer


if __name__ == "__main__":
    bot = CallbackBot()
    print("Bot:", GREETING)
    while True:
        try:
            text = input("You: ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if text.lower() in {"quit", "exit"}:
            break
        if text:
            print("Bot:", respond(bot, text))

respond() asks the callback bot first. If it returns None, the visitor isn’t in a flow and didn’t ask for a call, so the FAQ matcher answers. This pattern, specific handlers first and a general matcher last, scales well: add an order-status flow or a booking flow the same way, each returning None when the message isn’t theirs.

This is a real run of chat.py, typed line by line:

  • You: is cod available → Bot: Yes, cash on delivery is available on orders up to ₹5,000.
  • You: please call me back → Bot: Sure, we can call you. What’s your name?
  • You: Riya → Bot: Thanks, Riya. Which mobile number should we call?
  • You: 12345 → Bot: That doesn’t look like a 10-digit mobile number. Try again, e.g. 98765 43210.
  • You: +91 98765 43210 → Bot: When suits you: morning, afternoon or evening?
  • You: tomorrow evening is fine → Bot: Done, Riya. We’ll call you in the evening. Anything else?
  • You: refund policy? → Bot: You can return or exchange unused items within 7 days of delivery.

leads.csv now holds one row with the time, “Riya”, “9876543210” and “evening”. (Illustrative name and number.)

Script 4 · Web endpoint

One bot memory per visitor, behind Flask

Install Flask inside your virtual environment with python3 -m pip install flask, then run python3 app.py and open http://127.0.0.1:5050 in your browser.

# app.py: the same bot behind a web endpoint, with one memory per visitor.
# python3 -m pip install flask      then      python3 app.py
import os
import secrets
from flask import Flask, jsonify, request, session

from callback_bot import CallbackBot
from chat import respond

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET", secrets.token_hex(16))
MAX_CHARS = 500
BOTS = {}   # session id -> CallbackBot. In memory: lost on restart, one process only.

PAGE = """<!doctype html><meta charset="utf-8"><title>Chat test</title>
<div id="log"></div>
<form id="f"><input id="m" maxlength="500" autocomplete="off"><button>Send</button></form>
<script>
const log = document.getElementById("log");
function add(who, text) {
  const p = document.createElement("p");
  p.textContent = who + ": " + text;   // textContent, so replies can't inject HTML
  log.appendChild(p);
}
document.getElementById("f").addEventListener("submit", async (e) => {
  e.preventDefault();
  const box = document.getElementById("m");
  const text = box.value.trim();
  if (!text) return;
  add("You", text);
  box.value = "";
  const res = await fetch("/chat", {method: "POST",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({message: text})});
  const data = await res.json();
  add("Bot", data.reply || data.error);
});
</script>"""


@app.get("/")
def page():
    return PAGE


@app.post("/chat")
def chat():
    data = request.get_json(silent=True) or {}
    text = str(data.get("message", "")).strip()
    if not text:
        return jsonify(error="Empty message"), 400
    if len(text) > MAX_CHARS:
        return jsonify(error="Message too long"), 413
    sid = session.setdefault("sid", secrets.token_hex(8))
    bot = BOTS.setdefault(sid, CallbackBot())
    return jsonify(reply=respond(bot, text))


if __name__ == "__main__":
    app.run(port=5050)  # debug stays off; 5000 is often taken on macOS

What each part does

The /chat route reads a JSON message, refuses empty or over-long text, and looks up a CallbackBot for this visitor. Flask’s signed session cookie carries a random id, so two people chatting at once each get their own state: if one is halfway through giving a phone number, the other’s “Asha” isn’t mistaken for it. We tested exactly that with Flask’s test client before publishing.

The test page at / adds every message with textContent, never innerHTML, so a reply containing HTML can’t run code in the page. It’s served from the same Flask app, which avoids cross-origin (CORS) errors.

What this version doesn’t do

The BOTS dictionary lives in memory. Restart the server and every conversation is forgotten; run several worker processes and each has its own dictionary. For anything beyond a test, store state in a database or Redis, add rate limits, put it behind HTTPS, and keep FLASK_SECRET in an environment variable so sessions survive restarts. Our source code review checklist has 12 checks to run before strangers can reach your endpoint.

Troubleshooting

When chatbot code Python scripts won’t run: eight common errors

Most failures happen before the bot says a word. Find your error message in the left column.

What you seeWhyFix
python: command not foundPython isn’t on your PATH, or it’s installed as python3 or pyTry python3 (Mac, Linux) or py (Windows); reinstall from python.org and tick “Add to PATH”
ModuleNotFoundError: No module named ‘flask’Flask isn’t installed in the Python you’re runningActivate .venv, then python3 -m pip install flask
SyntaxError on an f-string or a type hintAn old Python, often 2.7 or 3.5Check python3 –version; use 3.9 or newer
Every question gets the fallbackVisitor words and stored wordings share nothing, or the threshold is too highPaste the questions into the generator’s preview and add wordings or synonyms
Confident wrong answersTwo answers share common words, and the first listed wins tiesAdd specific wordings; watch for close calls in the preview
UnicodeEncodeError when printing ₹An older Windows console that isn’t using UTF-8Use Windows Terminal, or run set PYTHONIOENCODING=utf-8 first
Address already in use on port 5000On recent macOS, AirPlay Receiver uses port 5000app.py already uses 5050; change the port if that’s taken too
Browser shows a CORS errorYour page and the endpoint are on different originsServe the page from the same app, as app.py does, or add CORS headers deliberately

From script to service

What a customer-facing bot still needs

Four files give you a bot that answers, remembers and collects leads. Put it in front of real visitors and a different list of problems appears, none of which is about Python:

  • A person to hand over to. The fallback says “our team will call you”. Someone has to see that, quickly, on a phone as well as a laptop, and reply in the same conversation.
  • Alerts. A CSV file doesn’t ring. You need a notification the moment a lead arrives or a visitor asks for a person.
  • Opening hours and an away message. At 11 pm the bot should say when the team is back and collect a contact, not promise a reply in minutes.
  • A widget visitors trust. A launcher that loads quickly, works on mobile, fits your brand colours and doesn’t block the checkout button.
  • History and tickets. Conversations that need follow-up should become tickets with an owner and a status, not rows nobody opens.
  • Upkeep. Prices, delivery times and policies change; someone has to update the answers, and that someone is often not a developer.

Each item is a project of its own. The development stages guide estimates where those hours go. If the point of your project is learning, building them is a great exercise. If the point is answering customers next week, it usually isn’t.

Build or plug in

When to keep your code, and when a no-code widget is the better choice

You’re learning, or it’s a college project
🚩 AvoidA hosted widget teaches you nothing about how bots work.
✅ Do thisWrite the code. The four files here are a good base; our [student project plan](ai-based-chatbot-project) shows how to scope and evaluate it.
A shop or service that needs answers on its website this week
🚩 AvoidWeeks spent on hosting, alerts, a widget and an inbox before the first customer chat.
✅ Do thisA no-code widget: paste one snippet, write your answers, and use the inbox and Android app for handover.
The bot must read your own systems (order status, stock)
🚩 AvoidRebuilding chat, inbox and alerts just to add one lookup.
✅ Do thisKeep that lookup in your Python back end and connect it to a hosted chat through its JavaScript API, REST API, webhooks or Zapier.
Strict rules: the data must never leave your servers
🚩 AvoidA third-party chat tool you can’t control.
✅ Do thisSelf-host your own code, and budget for the service work in the list above.

The chatbot code Python skills you’ve practised here don’t go to waste with a hosted tool. LiveChatBot answers from the knowledge you give its AI Agent, falls back to a free keyword bot built from saved replies, and hands chats to your team in a shared inbox and Android app. Developers can open, hide or pre-fill the widget from their own pages with the window.LiveChatBot JavaScript API, and back-end code can react to new and solved tickets through the REST API and webhooks. See the integrations page, or ask our team for developer documentation. To weigh it all up, read our make-vs-buy guide.

Checklist

Before your script talks to real visitors

Ready to launch

Getting started

An evening to a working bot

Tonight, set up the folder and run faq_bot.py as it is, to prove your Python works. Then open the generator, paste ten real customer questions with your answers, add the questions you want to test, and fix every close call the preview shows. Copy the generated file over faq_bot.py and run it again. Add callback_bot.py and chat.py, and try the callback flow with a wrong number to see the retry. When that works, install Flask and talk to app.py from your browser.

If you finish that evening thinking the bot is the easy bit and the inbox, alerts and widget are the real job, you’ve learned the most important lesson in chatbot work. You can keep building, or put your answers into a hosted widget. LiveChatBot’s free plan covers two websites with 100 visitors per website each month, the AI Agent with a small free monthly allowance, the free keyword bot, the team inbox, the Android app, Flows, opening hours with an away form, and tickets. See pricing and start at livechatbot.in.

Frequently asked questions

Can I use this chatbot code Python script in a commercial project?

Yes. The four files on this page are short examples written for this guide; copy and change them freely. They use only Python’s standard library and Flask, which is released under the BSD licence.

Do I need machine learning or an API key to run these scripts?

No. They match words with a simple overlap score and keep conversation state in plain variables. They run offline and cost nothing per message. Add a language model later if you need to answer questions you haven’t written down.

Why does my bot give the wrong answer instead of the fallback?

Two answers share common words, so the score passes the threshold for the wrong one. Add more specific wordings to the right answer, check the generator’s close-call notes, and only then raise the threshold.

How do I put the Python bot on my website?

Run app.py on a server with HTTPS and call its /chat endpoint from a chat box on your page. You’ll also need hosting, alerts and a way for your team to reply. A hosted widget gives you those by pasting one snippet.

Does the generator send my FAQ anywhere?

No. It runs entirely in your browser; nothing is sent or saved. The code it writes is shown on the page for you to copy.

Keep reading

Related guides

📘

Chatbot Chat Without Repeats: Stop Making Visitors Give Their Order Number, Email or Question Twice (Free Repeat Spotter)

Read the guide →

🧭

Chatbot Companies: Send These 12 Questions in Writing Before Any Demo, Then Grade the Reply (Free Vendor Reply Checker)

Read the guide →

🛠️

Chatbot Characteristics You Can Test in 10 Minutes: Ten Messages That Show What Any Bot Is Really Like (Free Test Script Builder)

Read the guide →

Prefer to skip the plumbing?

Put your answers into a ready-made widget with an AI Agent, a free keyword bot, a team inbox and an Android app. Start free on livechatbot.in.