How to Build a Real Chatbot (With Code) for Your Website in 2026 [Step by Step]

How to Build a Real Chatbot (With Code) for Your Website in 2026 [Step by Step]

Most tutorials on adding a chatbot to Your Website will give you a floating button which triggers a JS function that searches for keywords such as hello and price. This is not a chatbot. This is a decision tree with an interface and will only be correct for 6 questions and incorrect for the 7th which will be from a real customer.In this tutorial we are going to go deeper. Starting from the chatbot widget (the base of any chatbot), we'll look at how to switch the keyword search to an actual language model. We'll also look at how to link it to a knowledge base so it knows about your business and deploy it to make it production ready. Once completed, you'll have a chatbot that can actually answer questions about your products, policies and services.Code Included. All files included so you can copy and paste.


What You Are Building

What You Will Build There are two versions of this guide. 

Version 1 (steps 1-6) creates a fully-functional keyword based chatbot widget that runs in the browser, has no backend and takes around an hour to build. This is a great learning project and can be used as a useful demo. 

Version 2 (steps 7-10) creates a production chatbot that can call a language model API to fetch answers from your company's knowledge base and fall back gracefully if it doesn't know the answer. The production chatbot requires a small amount of backend and an API key. It will take around a day to build and is what you would actually implement for a client. 

Start by building version 1 so you understand how the widget works and then upgrade it to version 2.


Prerequisites

  • Basic knowledge of HTML, CSS, and JavaScript
  • A code editor (VS Code, Sublime Text, or similar)
  • Your website files
  • For Version 2: Python 3.9+, a free OpenAI or Anthropic API key, and a hosting account (Render, Vercel, or Railway)

Step 1: Create the File Structure

Create a new folder called chatbot inside your website directory.

text

your-website/

├── index.html

├── style.css

├── script.js

└── chatbot/

    ├── chatbot.html

    ├── chatbot.css

    ├── chatbot.js

    └── app.py


Step 2: Create the Chatbot HTML

Create chatbot/chatbot.html:

html

<!DOCTYPE html>

<html>

<head>

    <title>Chatbot Widget</title>

    <link rel="stylesheet" type="text/css" href="chatbot.css">

</head>

<body>

    <!-- Chatbot Trigger Button -->

    <button class="chatbot-trigger" onclick="toggleChatbot()">

        💬

    </button>

 

    <!-- Chatbot Container -->

    <div class="chatbot-container" id="chatbotContainer">

        <div class="chatbot-header">

            <h3>Customer Support</h3>

            <button class="close-btn" onclick="toggleChatbot()">×</button>

        </div>

 

        <div class="chatbot-messages" id="chatMessages">

            <div class="bot-message">

                <p>Hello! How can I help you today?</p>

            </div>

        </div>

 

        <div class="chatbot-input">

            <input type="text" id="userInput" placeholder="Type your message..."

                   onkeypress="handleKeyPress(event)">

            <button onclick="sendMessage()">Send</button>

        </div>

    </div>

 

    <script src="chatbot.js"></script>

</body>

</html>


Step 3: Create the Chatbot CSS

Create chatbot/chatbot.css:

css

.chatbot-trigger {

    position: fixed;

    bottom: 20px;

    right: 20px;

    background: #007bff;

    border: none;

    border-radius: 50%;

    width: 60px;

    height: 60px;

    cursor: pointer;

    box-shadow: 0 4px 8px rgba(0,0,0,0.2);

    z-index: 1000;

    font-size: 24px;

    color: white;

}

 

.chatbot-container {

    position: fixed;

    bottom: 90px;

    right: 20px;

    width: 350px;

    height: 500px;

    background: white;

    border-radius: 10px;

    box-shadow: 0 5px 15px rgba(0,0,0,0.2);

    display: none;

    flex-direction: column;

    z-index: 1000;

}

 

.chatbot-header {

    background: #007bff;

    color: white;

    padding: 15px;

    border-radius: 10px 10px 0 0;

    display: flex;

    justify-content: space-between;

    align-items: center;

}

 

.close-btn {

    background: none;

    border: none;

    color: white;

    font-size: 20px;

    cursor: pointer;

}

 

.chatbot-messages {

    flex: 1;

    padding: 15px;

    overflow-y: auto;

    display: flex;

    flex-direction: column;

    gap: 10px;

}

 

.user-message, .bot-message {

    max-width: 80%;

    padding: 10px;

    border-radius: 10px;

    margin: 5px 0;

}

 

.user-message {

    background: #007bff;

    color: white;

    align-self: flex-end;

}

 

.bot-message {

    background: #f1f1f1;

    color: #333;

    align-self: flex-start;

}

 

.chatbot-input {

    padding: 15px;

    border-top: 1px solid #ddd;

    display: flex;

    gap: 10px;

}

 

.chatbot-input input {

    flex: 1;

    padding: 10px;

    border: 1px solid #ddd;

    border-radius: 5px;

}

 

.chatbot-input button {

    background: #007bff;

    color: white;

    border: none;

    padding: 10px 15px;

    border-radius: 5px;

    cursor: pointer;

}

 

.typing {

    font-style: italic;

    color: #666;

}


Step 4: Create the Chatbot JavaScript (Version 1 — Keyword Matching)

Create chatbot/chatbot.js:

javascript

let isChatbotOpen = false;

 

function toggleChatbot() {

    const container = document.getElementById('chatbotContainer');

    isChatbotOpen = !isChatbotOpen;

    container.style.display = isChatbotOpen ? 'flex' : 'none';

}

 

function handleKeyPress(event) {

    if (event.key === 'Enter') {

        sendMessage();

    }

}

 

async function sendMessage() {

    const userInput = document.getElementById('userInput');

    const message = userInput.value.trim();

 

    if (!message) return;

 

    addMessage(message, 'user');

    userInput.value = '';

 

    showTypingIndicator();

 

    try {

        const response = getSimpleResponse(message);

 

        setTimeout(() => {

            removeTypingIndicator();

            addMessage(response, 'bot');

        }, 1000);

 

    } catch (error) {

        removeTypingIndicator();

        addMessage('Sorry, I encountered an error. Please try again.', 'bot');

        console.error('Error:', error);

    }

}

 

function getSimpleResponse(message) {

    const messageLower = message.toLowerCase();

 

    if (messageLower.includes('hello') || messageLower.includes('hi')) {

        return "Hello! How can I help you today?";

    } else if (messageLower.includes('price') || messageLower.includes('cost')) {

        return "Our pricing varies by product. Please visit our pricing page for details.";

    } else if (messageLower.includes('contact') || messageLower.includes('email')) {

        return "You can contact us at support@yourwebsite.com or call (555) 123-4567.";

    } else if (messageLower.includes('hours')) {

        return "We're available Monday to Friday, 9 AM to 6 PM.";

    } else if (messageLower.includes('thank')) {

        return "You're welcome! Is there anything else I can help with?";

    } else if (messageLower.includes('bye') || messageLower.includes('goodbye')) {

        return "Goodbye! Feel free to reach out if you have more questions.";

    } else {

        return "I understand you're asking about: " + message + ". For more detailed assistance, please contact our support team.";

    }

}

 

function addMessage(text, sender) {

    const messagesContainer = document.getElementById('chatMessages');

    const messageDiv = document.createElement('div');

    messageDiv.className = `${sender}-message`;

 

    const messageP = document.createElement('p');

    messageP.textContent = text;

    messageDiv.appendChild(messageP);

 

    messagesContainer.appendChild(messageDiv);

    scrollToBottom();

}

 

function showTypingIndicator() {

    const messagesContainer = document.getElementById('chatMessages');

    const typingDiv = document.createElement('div');

    typingDiv.id = 'typing-indicator';

    typingDiv.className = 'bot-message typing';

    typingDiv.innerHTML = '<p>Typing...</p>';

    messagesContainer.appendChild(typingDiv);

    scrollToBottom();

}

 

function removeTypingIndicator() {

    const typingIndicator = document.getElementById('typing-indicator');

    if (typingIndicator) {

        typingIndicator.remove();

    }

}

 

function scrollToBottom() {

    const messagesContainer = document.getElementById('chatMessages');

    messagesContainer.scrollTop = messagesContainer.scrollHeight;

}

 

// Auto-open chatbot after 30 seconds

setTimeout(() => {

    if (!isChatbotOpen) {

        toggleChatbot();

    }

}, 30000);


Step 5: Integrate the Chatbot into Your Main Website

Add this code just before the closing </body> tag in your main HTML file:

html

<!-- Chatbot Widget -->

<div id="chatbot-widget">

    <button class="chatbot-trigger" onclick="toggleChatbot()">

        💬

    </button>

 

    <div class="chatbot-container" id="chatbotContainer">

        <div class="chatbot-header">

            <h3>Customer Support</h3>

            <button class="close-btn" onclick="toggleChatbot()">×</button>

        </div>

 

        <div class="chatbot-messages" id="chatMessages">

            <div class="bot-message">

                <p>Hello! How can I help you today?</p>

            </div>

        </div>

 

        <div class="chatbot-input">

            <input type="text" id="userInput" placeholder="Type your message..."

                   onkeypress="handleKeyPress(event)">

            <button onclick="sendMessage()">Send</button>

        </div>

    </div>

</div>

 

<link rel="stylesheet" href="chatbot/chatbot.css">

<script src="chatbot/chatbot.js"></script>


Step 6: Test Version 1

Open your website in a browser. You should see:

  • A chat button in the bottom-right corner
  • A chat window that opens when clicked
  • Responses when you type "hello," "hours," "price," or "contact"

If it does not work, open the browser console (F12) and check for errors. The most common issues are incorrect file paths and JavaScript errors from typos.

What you have now: a working chatbot widget with keyword-based responses. It is a legitimate demo. It is not a production chatbot, because it will fail on any question it was not explicitly programmed to answer.


Step 7: Upgrade to a Real Chatbot — The Python Backend

Now replace the keyword matching with a language model. Create chatbot/app.py:

python

import os

from flask import Flask, request, jsonify

from flask_cors import CORS

from openai import OpenAI

 

app = Flask(__name__)

CORS(app)

 

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

 

# This is the system prompt. It defines the chatbot's role and constraints.

SYSTEM_PROMPT = """

You are a helpful customer support assistant for [Your Business Name].

Answer questions using only the information provided in the context below.

If the answer is not in the context, say: "I don't have that information,

but I can connect you with our support team at support@yourwebsite.com."

Do not invent information. Do not answer questions unrelated to the business.

Keep responses concise, friendly, and under 100 words.

 

Context:

- Business hours: Monday to Friday, 9 AM to 6 PM

- Contact: support@yourwebsite.com, (555) 123-4567

- Return policy: 30 days, no questions asked

- Shipping: Free on orders over $50

- Pricing: See the pricing page at yourwebsite.com/pricing

"""

 

@app.route('/chat', methods=['POST'])

def chat():

    data = request.get_json()

    user_message = data.get('message', '')

 

    if not user_message:

        return jsonify({'response': 'Please send a message.'}), 400

 

    try:

        response = client.chat.completions.create(

            model="gpt-4o-mini",

            messages=[

                {"role": "system", "content": SYSTEM_PROMPT},

                {"role": "user", "content": user_message}

            ],

            temperature=0.3,

            max_tokens=200

        )

 

        bot_response = response.choices[0].message.content

        return jsonify({'response': bot_response})

 

    except Exception as e:

        print(f"Error: {e}")

        return jsonify({

            'response': 'I am having trouble right now. Please email support@yourwebsite.com.'

        }), 500

 

if __name__ == '__main__':

    app.run(debug=True, port=5000)

Install the dependencies:

bash

pip install flask flask-cors openai

Set your API key:

bash

export OPENAI_API_KEY="your-api-key-here"

Run the backend:

bash

python chatbot/app.py

The backend now runs at http://localhost:5000.


Step 8: Update the JavaScript to Call the Backend

Replace the sendMessage function in chatbot.js with this version:

javascript

async function sendMessage() {

    const userInput = document.getElementById('userInput');

    const message = userInput.value.trim();

 

    if (!message) return;

 

    addMessage(message, 'user');

    userInput.value = '';

    showTypingIndicator();

 

    try {

        const response = await fetch('http://localhost:5000/chat', {

            method: 'POST',

            headers: { 'Content-Type': 'application/json' },

            body: JSON.stringify({ message: message })

        });

 

        const data = await response.json();

        removeTypingIndicator();

        addMessage(data.response, 'bot');

 

    } catch (error) {

        removeTypingIndicator();

        // Fallback if the backend is unreachable

        addMessage(

            "I'm having trouble connecting. Please email support@yourwebsite.com.",

            'bot'

        );

        console.error('Error:', error);

    }

}

You can delete the getSimpleResponse function. It is no longer used.


Step 9: Add a Knowledge Base (Retrieval-Augmented Generation)

The system prompt in Step 7 is a small, hardcoded knowledge base. For a real business, the knowledge is too large to fit in a prompt. The solution is retrieval-augmented generation (RAG) : store the business's documents as embeddings, retrieve the relevant chunks for each question, and include them in the prompt.

Here is a minimal RAG implementation. Create chatbot/rag.py:

python

import os

import numpy as np

from openai import OpenAI

 

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))

 

# Your business documents. In production, load these from files or a database.

DOCUMENTS = [

    "Our business hours are Monday to Friday, 9 AM to 6 PM.",

    "We offer a 30-day return policy with no questions asked.",

    "Shipping is free on all orders over $50.",

    "Our pricing plans are Starter ($19/month), Pro ($49/month), and Enterprise (custom).",

    "You can contact support at support@yourwebsite.com or call (555) 123-4567.",

    "We accept Visa, Mastercard, American Express, and PayPal.",

]

 

def get_embedding(text):

    response = client.embeddings.create(

        model="text-embedding-3-small",

        input=text

    )

    return response.data[0].embedding

 

# Precompute embeddings for all documents (do this once at startup)

DOC_EMBEDDINGS = [get_embedding(doc) for doc in DOCUMENTS]

 

def retrieve(query, top_k=3):

    query_embedding = get_embedding(query)

    similarities = [

        np.dot(query_embedding, doc_emb) /

        (np.linalg.norm(query_embedding) * np.linalg.norm(doc_emb))

        for doc_emb in DOC_EMBEDDINGS

    ]

    top_indices = np.argsort(similarities)[-top_k:][::-1]

    return [DOCUMENTS[i] for i in top_indices]

 

def answer(query):

    context = "\n".join(retrieve(query))

    system_prompt = f"""

You are a customer support assistant. Answer using only the context below.

If the answer is not in the context, say you don't know and offer the support email.

 

Context:

{context}

"""

    response = client.chat.completions.create(

        model="gpt-4o-mini",

        messages=[

            {"role": "system", "content": system_prompt},

            {"role": "user", "content": query}

        ],

        temperature=0.3

    )

    return response.choices[0].message.content

Update app.py to use rag.answer() instead of the hardcoded system prompt:

python

from rag import answer

 

@app.route('/chat', methods=['POST'])

def chat():

    data = request.get_json()

    user_message = data.get('message', '')

 

    if not user_message:

        return jsonify({'response': 'Please send a message.'}), 400

 

    try:

        bot_response = answer(user_message)

        return jsonify({'response': bot_response})

    except Exception as e:

        print(f"Error: {e}")

        return jsonify({

            'response': 'I am having trouble right now. Please email support@yourwebsite.com.'

        }), 500

This is a minimal RAG implementation. For a production system, replace the hardcoded DOCUMENTS list with a vector database (Pinecone, Weaviate, or Supabase Vector) and a document loader that chunks and embeds the business's actual content.


Step 10: Deploy the Chatbot

The chatbot now has three parts: the front-end widget, the Flask backend, and the OpenAI API. To deploy:

Deploy the backend. Render, Railway, and Vercel all support Flask. Push the chatbot/ folder to a GitHub repository, connect it to the hosting platform, add the OPENAI_API_KEY as an environment variable, and deploy. The platform will give you a URL like https://your-chatbot.onrender.com.

Update the front-end. In chatbot.js, replace http://localhost:5000/chat with your deployed backend URL.

Test in production. Open your website, click the chat button, and ask a question. If the bot responds correctly, the deployment is complete.


Troubleshooting Checklist

Problem

Fix

Chatbot not appearing

Check browser console (F12). Verify file paths.

Styles not loading

Confirm CSS path. Check for CSS conflicts.

JavaScript not working

Check console for errors. Ensure JS is enabled.

Backend not responding

Check that Flask is running. Verify the port and URL.

CORS error

Ensure flask-cors is installed and CORS(app) is in app.py.

API error

Check that OPENAI_API_KEY is set correctly.

Bot gives wrong answers

Improve the knowledge base. Add more documents. Test retrieval.


Final Checklist

  • Chatbot button appears on the website
  • Chat window opens when clicked
  • Messages send and receive
  • Bot responds using the language model (Version 2)
  • Bot retrieves relevant context from the knowledge base (Step 9)
  • Fallback works when the API is unreachable
  • No errors in the browser console or backend logs

What You Have Built

Version 1 is a working widget with keyword matching. It is a learning project.

Version 2 is a production chatbot with a language model, a knowledge base, and a fallback. It can answer questions the developer did not anticipate, and it can be deployed for a real business.

The difference between the two is the difference between a demo and a product. The demo is worth building—it teaches you how the widget works. The product is worth selling—it solves a real problem for a client. The step from one to the other is the work that separates a freelancer who follows tutorials from one who delivers solutions.


Related Posts (Freelancing)


The World of Virtual Assistants: A Comprehensive Guide to Working and Earning from Home

Amazon Virtual Assistant: Get a Profitable Job From Home

Fiverr: The Game-Changer for Freelancers Around the Globe Essay

Free YouTube Tools Every Creator Needs in 2026: Copyright-Safe Resources and Editing Software

Free YouTube Tools and Udemy: The Complete 2026 Guide for Creators and Freelancers

Creating a YouTube Channel Using Free Resources in 2026: The Road to Success and the Pitfall to Avoid

123apps Isn't a Money-Making Tool, But the People Viewing It as a Supply Source Are Quietly Profiting From an Information Gap

Faceless Audio Channels on YouTube in 2026: The License Trap To Avoid, and The One To Seek

What JustAnswer Actually Pays in 2026: The 10% Acceptance Rate, the $2-$20 Answer Fee, and the Experts Clearing $10,000 a Month

Canva Is Not a Magic Money Button: What It Actually Takes to Earn From It in 2026

LinkedIn in 2026: Why Your 500-Connection Network Is Now Worth Less Than 50 Right Followers

Five Remote Work Platforms That Actually Pay in 2026-and the One I Left Out on Purpose

Writesonic vs ChatGPT in 2026: The “Better AI” Question Is the Wrong Question—Here’s What Actually Matters

How Article Writers Get Clients in 2026: Overlooking the Platform Trap, the Country Myth and the Strategy No One Teaches

How to Write Articles With ChatGPT in 2026: The 2021 Advice That's Costing Bloggers Their Traffic

Google News in 2026: The 24-Billion-Click Tool Bloggers Misunderstand – And How To Avoid Copyright Issues

The 17 Habits Of Successful People Are Mostly Survivorship Bias And Here Are The 6 That Are Actually Effective

Fiverr’s 2026 Algorithm Doesn’t Rank Keywords – Majority Optimise Wrong

7 Easy Freelance Jobs To Learn In A Weekend and Why You Should Know About This

Freelancing In 2026: Is this the ultimate career path or risky option? What you need to know as an aspiring freelancer

The Freelance Paradox: How Freedom Can Become Responsibility

Hostinger’s 60% Affiliate Commission – A Mirage?

How To Resolve Arguments With 85% Of Late-Paying Freelancers

The $47,000 Gap - Why 90% of Freelancers Get Stuck in Local Markets & How the Other 10% Reach Global Markets

The 3-Million Podcast Graveyard: How to Create Your Podcast and Not Become One of Them

The 3 PM Wall: Why Freelancers Struggle To Stay Focused At The Same Time Everyday + How To Fix It

What happens to your proposals on Upwork in 2026?

The First 72 Hours – Why your welcome pack determines if your client has a good experience

The Rejection Hangover – Why One "No" From a Client Feels Like the End of Your Career and How to Bounce Back From It in 48 Hours

The $3,200 Question: Should Freelancers Get Vision Insurance?

The Curiosity Gap Is A Penalty: How To Write Click-Inducing Blog Headlines

Your Email Is a Postcard: Why "Send as Attachment" Is the Most Dangerous Habit

A $200k Freelance Career - How to Legally Penetrate Systems + Why There's Never Been More Demand For Pen Testers

YouTube Has Said Three Things You Can’t Get Paid For With AI – And Most Creators Have Got It Wrong

The 20 Remote Job Sites List Is Half Accurate And Will Waste Your Time If You Get It Wrong

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.