Build a Chatbot from Scratch Using JavaScript

Build an AI chatbot tutorial banner

Welcome to our chatbot tutorial! In this tutorial, we will be building a chatbot from scratch using JavaScript.

What is a chatbot?

Chatbots are computer programs that can simulate human conversation through text or voice interactions. They are becoming increasingly popular in various industries, including customer service, healthcare, and e-commerce.

Building a Basic Chatbot

Our chatbot will be able to answer basic questions about products, including their price, specifications, and usage instructions. We will be using a dataset of products and questions to train our chatbot to recognize different types of questions and provide appropriate responses.

Chatbot structure

First, let me explain the basic structure of our AI chatbot. It will consist of three main components:

  1. User interface: This is the part of the chatbot that interacts with the user. It displays the messages from the chatbot and allows the user to type their input. The user interface will be designed using HTML and CSS, which are languages for creating web pages. HTML defines the structure and content of the web page, while CSS defines the style and layout of the web page.
  2. Chatbot logic: This is the part of the chatbot that processes the user input and generates the chatbot response. It will be programmed using JavaScript, which is a language for adding interactivity and functionality to web pages. JavaScript will access the HTML elements and manipulate them using the Document Object Model (DOM).
  3. Chatbot data: This is the part of the chatbot that stores the information that the chatbot needs to function. It can be a simple dataset with predefined messages, or a complex database with dynamic data.

Now that you have an overview of the chatbot structure, let's start building it. Our chatbot layout will have an input and send button at the bottom of the screen. It will be able to understand greetings, answer a few questions, and handle different types of statements. Let's create an HTML file and add the following code for our chatbot user interface:

Javascript
                        
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Chatbot Tutorial</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <div class="card">
      <div class="header">
        <h1>AI Chatbot Tutorial</h1>
      </div>
      <div class="message-section" id="message-section">
        <div class="message bot-message">
          <p>Hello, this is a simple AI chatbot. You can ask me some questions or chat with me.</p>
        </div>
      </div>
      <div class="input-section">
        <input type="text" id="user-input" placeholder="Type your message here...">
        <button id="send-button">Send</button>
      </div>
    </div>
  <script src="script.js"></script>
  </body>
</html>

That's our HTML to give our chatbot some structure. If you open the file in your browser, it will look as shown below:

chatbot layout without css styling

Now let's move on to the next step and add some styling to our chatbot. Create a CSS file, name it style and save it in the same folder as our html. In our CSS file, add the following code:

Javascript
                        
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.card {
  width: 80%;
  max-width: 600px;
  margin: 20px auto;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}

.header {
  background-color: #f0f0f0;
  padding: 15px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.header h1 {
  font-family: Arial, sans-serif;
  font-size: 24px;
  color: #333;
  text-align: center;
}

.message-section {
  height: 400px;
  overflow-y: scroll;
  padding: 10px;
}

.message {
  display: flex;
  align-items: flex-end;
  margin-bottom: 10px;
}

.message p {
  max-width: 70%;
  word-wrap: break-word;
  padding: 10px;
  border-radius: 10px;
  font-family: Arial, sans-serif;
  font-size: 16px;
  color: #fff;
}

.bot-message {
  justify-content: flex-start;
}

.bot-message p {
  background-color: #0084ff;
}

.user-message {
  justify-content: flex-end;
}

.user-message p {
  background-color: #44bec7;
}

.input-section {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
}

.input-section input {
  flex: 1;
  border: none;
  outline: none;
  padding: 10px;
  font-family: Arial, sans-serif;
  font-size: 16px;
}

.input-section button {
  width: 80px;
  padding: 8px 12px;
  border: none;
  outline: none;
  background-color: #0084ff;
  color: #fff;
  font-family: Arial, sans-serif;
  font-size: 16px;
  border-radius: 5px;
  cursor: pointer;
}

.input-section button:hover {
  background-color: #006cce;
}

That's it for our chatbot's user interface. If you refresh your browser, our chatbot will now look like the one below:


our chatbot ui after adding css styling

Now let's move on to the fun part- adding some functionality to our chatbot. Let's create a javascript file named script.js and save it in the same folder as our html and css files. In our script.js file, add the following code:

Javascript
                        
// Get the HTML elements
const messageSection = document.getElementById("message-section");
const userInput = document.getElementById("user-input");
const sendButton = document.getElementById("send-button");

// Define the datasets
const greetings = [
  "Hi there!",
  "Hello!",
  "Greetings!"
];

const questions = [
  {
    input: ["What is the price of", "How much does"],
    output: "The price of {product} is {price}.",
    topic: "price"
  },
  {
    input: ["What are the specs of", "Tell me about"],
    output: "The specs for {product} are {specs}.",
    topic: "specs"
  },
  {
    input: ["How do I use", "What is the usage of"],
    output: "To use {product}, {usageInstructions}.",
    topic: "usageInstructions"
  }
];

const products = [
  {
    name: "Product A",
    specs: "Specs for Product A",
    price: "$100",
    usageInstructions: "do this and that"
  },
  {
    name: "Product B",
    specs: "Specs for Product B",
    price: "$200",
    usageInstructions: "do this and that"
  },
  {
    name: "Product C",
    specs: "Specs for Product C",
    price: "$300",
    usageInstructions: "do this and that"
  }
];

const complaints = [
  "I am really sorry about that.",
  "My sincerest apologies.",
  "I apologize for that"
];

const compliments = [
  "You're doing great!",
  "Keep up the good work!",
  "You're awesome!"
];

// Define the function to classify the input
function classifyInput(input) {
  // Convert the input to lowercase
  input = input.toLowerCase();

  // Check if the input is a greeting
  if (input.includes("hello") || input.includes("hi") || input.includes("hey")) {
     return "greeting";
  }

  // Check if the input is a question
  for (let i = 0; i < questions.length; i++) {
    for (let j = 0; j < questions[i].input.length; j++) {
      if (input.includes(questions[i].input[j].toLowerCase())) {
        return {
          type: "question",
          topic: questions[i].topic,
          product: getProduct(input)
        };
      }
    }
  }

  // Check if the input is a compliment
  if (input.includes("not working") || input.includes("is broken") || input.includes("failing")) {
    return "complaint";
  }

  // Check if the input is a compliment
  if (input.includes("good job") || input.includes("well done") || input.includes("awesome")) {
    return "compliment";
  }

  // If no match is found, return "unknown"
  return "unknown";
}

// Define the function to get the product name from the input
function getProduct(input) {
  for (let i = 0; i < products.length; i++) {
    if (input.includes(products[i].name.toLowerCase())) {
      return products[i].name;
    }
  }

  return "";
}

// Define the function to generate the response
function generateResponse(input) {
  // Classify the input
  const classification = classifyInput(input);

  // Generate the response based on the input classification
  switch (classification) {
    case "greeting":
      return greetings[Math.floor(Math.random() * greetings.length)];
    case "complaint":
      return complaints[Math.floor(Math.random() * complaints.length)];
    case "compliment":
      return compliments[Math.floor(Math.random() * compliments.length)];
    case "unknown":
      return "I'm sorry, I didn't understand that.";
    default:
      for (let i = 0; i < questions.length; i++) {
        if (questions[i].topic === classification.topic) {
          return questions[i].output
            .replace("{product}", classification.product)
            .replace("{price}", products.find(p => p.name === classification.product)?.price || "unspecified")
            .replace("{specs}", products.find(p => p.name === classification.product)?.specs || "Product not found")
            .replace("{usageInstructions}", products.find(p => p.name === classification.product)?.usageInstructions || "unspecified");
        }
      }
  }
}

// Define the function to handle user input
function handleInput() {
  // Get the user input
  const userInputValue = userInput.value;

  // Check if the user input is not empty
  if (userInputValue) {
    // Display the user message
    displayMessage(userInputValue, "user-message");

    // Generate the chatbot's response
    let chatbotResponse = generateResponse(userInputValue);

    // Display the chatbot response
    displayMessage(chatbotResponse, "bot-message");

  }

  // Clear the user input
  userInput.value = "";
}

// A function to display a message
function displayMessage(message, messageClass) {
  // Create a div element for the message
  let messageDiv = document.createElement("div");

  // Add the message class to the div element
  messageDiv.classList.add("message");
  messageDiv.classList.add(messageClass);

  // Create a p element for the message text
  let messageText = document.createElement("p");

  // Set the inner text of the p element to the message
  messageText.innerText = message;

  // Append the p element to the div element
  messageDiv.appendChild(messageText);

  // Append the div element to the message section
  messageSection.appendChild(messageDiv);

  // Scroll to the bottom of the message section
  messageSection.scrollTop = messageSection.scrollHeight;
}

// Add an event listener to the send button
sendButton.addEventListener("click", handleInput);

This code defines multiple datasets for different types of user input, including greetings, questions, products, and compliments. The classifyInput function takes an input and returns its classification based on whether it matches any of the datasets. The generateResponse function takes an input classification and generates a response based on the appropriate dataset.

To handle questions about the products, the generateResponse function searches through the products array to find the relevant product and return the appropriate information based on the type of question.


screenshot of the conversation with our AI chatbot

The Future of Chatbots

Chatbots are here to stay for the foreseeable future. They are changing the way businesses communicate and understand their customers. With the advancements in AI and machine learning, chatbots are becoming more sophisticated and capable of handling complex interactions.

Comparing Our Chatbot to ChatGPT and BARD

Our chatbot uses a rule-based algorithm to classify user input and generate responses. It is a simple chatbot that is designed to handle basic questions about products. In contrast, ChatGPT and BARD are more complex chatbots that use deep learning algorithms to generate responses.

To improve on what we have built, you can add more products to the dataset, include more types of questions, or use a more advanced NLP library to handle more complex questions. You can also use machine learning algorithms to train your chatbot to recognize different variations of questions and provide appropriate responses.

Conclusion

We hope you found this tutorial informative and fun. Chatbots are becoming increasingly popular in various industries, and building your own chatbot can be a great way to learn about the technology and its applications. With the advancements in AI and machine learning, chatbots are becoming more sophisticated and capable of handling complex interactions.

We encourage you to experiment with different approaches and to continue learning about chatbots and their applications. Who knows, you might just build the next ChatGPT or BARD!