Python Chatbot Code You Can Copy and Paste [2026]

Expert written and reviewed by Voiceflow team
Table of contents
    Don't get left behind in AI
    Get the latest AI news and industry shifts weekly.

    If you're here, you want working code, not a lecture on what a chatbot is. Fair enough. This walks through three ways to build a chatbot in Python, each with code you can paste and run today: a rule-based bot with no libraries, a classic ChatterBot build, and the one most people should actually use in 2026, a chatbot backed by a large language model API. At the end, I'll be honest about when writing Python is the wrong move at all.

    Pick the level that matches what you're doing. If you're learning, start at the top. If you're shipping something real, skip to the LLM section.

    How Much Python Do You Actually Need?

    It depends on the bot. A keyword-matching bot that answers a handful of questions needs almost no Python: variables, a dictionary, a loop. You can write it in an afternoon.

    A bot that understands messy, real language and holds a conversation is a different job. That used to mean natural language processing work with libraries like NLTK or spaCy, training data, and intent models. In 2026, it mostly means calling an LLM and knowing how to feed it the right context. The hard part moved from parsing language to designing the system around the model.

    So the skill floor dropped, but the ceiling didn't. Getting a model to reply is easy. Getting it to reply correctly, every time, grounded in your data, is the part that takes real work.

    Approach 1: A Rule-Based Chatbot (No Libraries)

    Start here if you've never built one. This bot matches keywords to canned answers. No dependencies, no install, nothing to break.

    # Rule-based chatbot: pure Python, no libraries
    responses = {
        "hours": "We're open 9am to 5pm, Monday to Friday.",
        "pricing": "Plans start at $10/month. Ask me for a link.",
        "support": "You can reach a human at support@example.com.",
    }
    
    def get_response(message):
        text = message.lower().strip()
        for keyword, reply in responses.items():
            if keyword in text:
                return reply
        return "Sorry, I didn't catch that. Try 'hours', 'pricing', or 'support'."
    
    while True:
        user_input = input("You: ")
        if user_input.lower().strip() in {"bye", "quit", "exit"}:
            print("Bot: Thanks for stopping by.")
            break
        print("Bot:", get_response(user_input))

    Run it, type hours, and it answers. That's a chatbot. It's rigid and it doesn't understand anything, but it shows the loop every bot follows: take input, decide on a response, reply, repeat. Everything else is just a smarter way to do the middle step.

    {{blue-cta}}

    Approach 2: A Chatbot With ChatterBot

    ChatterBot is the library most Python chatbot tutorials reach for. It's a machine-learning bot that picks responses based on similarity to conversations it has been trained on. Here's a minimal build:

    # pip install chatterbot chatterbot_corpus
    from chatterbot import ChatBot
    from chatterbot.trainers import ChatterBotCorpusTrainer
    
    bot = ChatBot("Assistant")
    
    trainer = ChatterBotCorpusTrainer(bot)
    trainer.train("chatterbot.corpus.english")
    
    while True:
        try:
            user_input = input("You: ")
            print("Bot:", bot.get_response(user_input))
        except (KeyboardInterrupt, EOFError):
            break

    You can also train it on your own conversation pairs:

    from chatterbot.trainers import ListTrainer
    
    trainer = ListTrainer(bot)
    trainer.train([
        "How do I reset my password?",
        "Go to Settings, then Security, and click Reset Password.",
        "What are your hours?",
        "We're open 9am to 5pm, Monday to Friday.",
    ])

    Here's the honest part, and most tutorials won't tell you this: the original chatterbot package on PyPI has been essentially unmaintained for years and often won't install cleanly on current Python versions because of old dependency pins. There's a community-maintained fork that keeps it working, so check which package you're installing. ChatterBot is a fine way to learn how retrieval-based bots work. For anything a customer will touch, don't build on it. Use the approach below.

    Approach 3: An AI Chatbot With an LLM API (The 2026 Way)

    This is what "chatbot" means now. Instead of matching keywords or similarity scores, you send the conversation to a large language model and it writes the reply. It understands phrasing you never anticipated, and it sounds human because it is generating language, not looking it up.

    # pip install openai
    from openai import OpenAI
    
    client = OpenAI()  # reads OPENAI_API_KEY from your environment
    
    messages = [
        {"role": "system", "content": "You are a friendly support assistant for Acme Co. Keep answers short."}
    ]
    
    while True:
        user_input = input("You: ")
        if user_input.lower().strip() in {"bye", "quit", "exit"}:
            break
    
        messages.append({"role": "user", "content": user_input})
    
        response = client.chat.completions.create(
            model="gpt-4o",  # swap for whatever chat model you have access to
            messages=messages,
        )
    
        reply = response.choices[0].message.content
        print("Bot:", reply)
        messages.append({"role": "assistant", "content": reply})

    The one thing to notice: messages grows with every turn. You append the user's line, then the model's reply, and pass the whole list back next time. That running history is how the bot remembers what you just said. Drop it, and every message starts a brand-new conversation with a bot that has amnesia.

    The same pattern works with Anthropic's or Google's SDK, or a hosted chatbot API. You're not locked to one provider, and the tokens you send and receive are what you pay for, so keeping that history trim matters as it grows.

    This version already beats the first two for real use. But it also has a problem the code doesn't show.

    Where the Copy-Paste Code Stops Being Enough

    That LLM loop is maybe 10% of a production chatbot. The other 90% is everything the snippet quietly ignores:

    • Grounding. Left alone, the model will confidently make things up. Real bots pull answers from your docs and help center with a knowledge base so replies come from your content, not the model's guesses. That's the practical way to cut hallucinations.
    • Control. Some steps must happen the same way every time (verify an account, check an order, hand off to a human). A free-form model won't guarantee that. You need deterministic logic around it.
    • Context assembly. Deciding what to put in front of the model on each turn (history, user data, retrieved docs) is its own discipline, context engineering, and it's most of what separates a good bot from a frustrating one.
    • Deploy, test, watch. Getting it onto your site, phone line, or WhatsApp, testing it before launch, and seeing what it does with real users is work the snippet doesn't touch.

    You can build all of that in Python. Teams do. Just know that's the project you're signing up for, not the twenty lines above.

    The No-Code Alternative: When Not to Write Python

    If your goal is a working customer-facing agent and not the experience of hand-coding one, a platform gets you there faster. Voiceflow is where a lot of teams build the parts the snippet skips, without wiring them together yourself:

    • Model-agnostic. Run OpenAI, Anthropic, Google, or Amazon Bedrock models and switch on a given step without a rewrite. No vendor lock-in.
    • Workflows and Playbooks. Deterministic Workflows for steps that must go the same way every time, Playbooks for the reasoning steps. Most real agents need both.
    • Knowledge Base grounding. Point the agent at your docs so answers come from your content.
    • Evaluations, Observability, and Environments. Test before launch, watch production, and promote changes through staging like real software.
    • Enterprise controls. SOC 2 Type 2 and PII masking, which teams like Turo, StubHub, Sanlam, and Trilogy rely on.

    The honest split: write Python when the point is to learn, or when you need control a platform won't give you. Reach for no-code when the point is to ship something customers use and keep it running. Plenty of teams start in Python, hit the 90% wall, and move the production version onto a platform.

    {{blue-cta}}

    Frequently Asked Questions

    Can you build a chatbot in Python?

    Yes. Python is one of the most common languages for chatbots. You can write a simple rule-based bot with no libraries, a retrieval bot with a library like ChatterBot, or an AI bot that calls a large language model API. The right choice depends on whether you're learning or shipping something real.

    Is ChatterBot still maintained?

    Not really. The original chatterbot package on PyPI stalled years ago and often fails to install on current Python versions because of outdated dependencies. A community fork keeps it working, so check which one you install. It's useful for learning, but for a production bot, use a large language model API or a platform instead.

    Which Python library is best for building a chatbot?

    For learning the basics, ChatterBot or plain Python. For understanding language, spaCy or NLTK. For anything a real user will touch, skip the classic NLP libraries and call an LLM directly with the OpenAI, Anthropic, or Google SDK. The model does the language work those libraries used to.

    How do I make a Python chatbot with GPT or another AI model?

    Install the provider's SDK, set your API key, and send the conversation as a list of messages to the chat endpoint. Append each user message and model reply to that list so the bot keeps context across turns. The Approach 3 snippet above is a complete, runnable example.

    Do you need to know Python to build a chatbot?

    No. Python gives you full control, but no-code platforms like Voiceflow let you build, test, and deploy a real agent without writing any. Many teams prototype in Python and move the production version to a platform once they hit the work beyond the model call.

    background lines
    background lines