Chatbot using JavaScript

Create Chatbot using JavaScript in 3 Easy Steps

Introduction

In this tutorial, I’ll guide you through creating a simple and functional custom chatbot using the power of JavaScript for logic, HTML for structure, and CSS for styling. While going through this tutorial we’ll learn many important concepts in JavaScript. At the end of the tutorial, you’ll be able to understand the concepts of Regex, DOM, Arrays in JavaScript, and many more useful topics. Let’s begin to build your personalized chatbot.

Demo of ChatBot Application

What is ChatBot?

A chatbot is a program that is designed to make conversation with human users, especially on the internet. These programs are often taken by artificial intelligence (AI) and can be easily integrated into messaging platforms, websites, or applications to interact with users conversationally. You’ve often seen chatbots on many Websites while suffering the internet and must be curious about How to make a Custom ChatBot using JavaScript ? So let’s start with what is the procedure of creating a chatbot using JavaScript.

30+ Javascript Projects with Source Code

Procedure for Creating ChatBot

There are several steps including for creating custom ChatBot:-

  1. Create HTML File(Index.html)
  2. Create CSS File(style.css)
  3. Create a Script.js File that will be a JavaScript file containing our logic for functionality.
  4. Create a Constant.js File that will be a JavaScript file containing the custom phrases(Will describe later in brief).

HTML Code

Create an HTML File, name as “Index.html” and paste the following code:-

<!DOCTYPE html>
<html>

<head>
	<title>Chatbot</title>
	<link rel="icon" href="bot.png" />
	<link rel="stylesheet" href="style.css" />
</head>

<body>
	<div id="container" class="container">
		<div id="chat" class="chat">
			<div id="messages" class="messages"></div>
			<input id="input" type="text" placeholder="Say something..." autocomplete="off" autofocus="true" />
		</div>
		<img src="bot.jpeg" alt="Robot cartoon" height="500vh">
	</div>
</body>
<script type="text/javascript" src="script.js" ></script>
<script type="text/javascript" src="constants.js" ></script>

</html>

Let’s BreakDown the above code:-

<body> Contains the content of the HTML document. In the body we’ve defined the container class for two elements first one is class `chat` that will work as input for the messages and second one is for image that will be our Bot image for attraction and better user Interface. Image of a robot cartoon with an alternative text and a fixed height of 500vh (viewport height).

At last of the body, we’ve added the script tag that will refer to JavaScript Files.

Preview of HTML Code

Chatbot using JavaScript

CSS Code

Make Another file name as `style.css` and paste the following code:-

* {
  box-sizing: border-box;
}

html {
	height: 100%;

}

body {
  font-family: 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', Arial, Helvetica,
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
	background-color: rgb(255, 255, 255);
	height: 100%;
	margin: 0;
}

span {
	padding-right: 15px;
	padding-left: 15px;
}

.container {
	display: flex;
  justify-content: center;
	align-items: center;
	width: 100%;
	height: 100%;
}

.chat {
	height: 300px;
	width: 50vw;
	display: flex;
	flex-direction: column;
  justify-content: center;
	align-items: center;
} 

::-webkit-input-placeholder { 
	color: .711 
}
 
input { 
	border: 10; 
	padding: 15px; 
	margin-left: auto;
	border-radius: 10px; 
}

.messages {
	display: flex;
	flex-direction: column;
	overflow-y: scroll;
	height: 90%;
	width: 100%;
	background-color: rgb(10, 229, 245);
	padding: 15px;
	margin: 15px;
	border-radius: 10px;
}

#bot {
	margin-left: auto;
}

.bot {
	font-family: Consolas, 'Courier New', Menlo, source-code-pro, Monaco,  
	monospace;
}

.avatar {
	height: 25px;
}

.response {
	display: flex;
	align-items: center;
	margin: 1%;
}


/* Mobile */

@media only screen and (max-width: 980px) {
  .container {
		flex-direction: column; 
		justify-content: flex-start;
	}
	.chat {
		width: 75vw;
		margin: 10vw;
	}
}

Let’s go through the key components of the code:

.container Class styles the main container for the chatbot, it is centering the content both horizontally and vertically.

.chat Class styles the chat interface, setting there dimensions, and centering the content.

response This class will style the response container, including display and margin. You can modify it according to your need for better practice.

.messages This class styles the message container, including background color, padding, and border-radius.

After understanding the CSS Code part of ChatBot, you can make changes and modifications according to your preferences for better practice, and for learning purposes, you can design the interface according to your needs.

Preview After Using CSS Code

ChatBot Using JavaScript

JavaScript Code

So finally we’re going to the main part of the code where the magic happens. Create a File name as Constants.js and add the following code:-

// Options the user could type in
const prompts = [
    ["hi","hiii", "hey", "hello", "good morning", "good afternoon"],
    ["how are you", "how is life", "how are things"],
    ["what are you doing", "what is going on", "what is up"],
    ["how old are you"],
    ["who are you", "are you human", "are you bot", "are you human or bot"],
    ["who created you", "who made you"],
    [
      "your name please",
      "your name",
      "may i know your name",
      "what is your name",
      "what call yourself"
    ],
    ["i love you"],
    ["happy", "good", "fun", "wonderful", "fantastic", "cool"],
    ["bad", "bored", "tired"],
    ["help me", "tell me story", "tell me joke"],
    ["ah", "yes", "ok", "okay", "nice"],
    ["bye", "good bye", "goodbye", "see you later"],
    ["what should i eat today"],
    ["bro"],
    ["what", "why", "how", "where", "when"],
    ["no","not sure","maybe","no thanks"],
    [""],
    ["haha","ha","lol","hehe","funny","joke"]
  ]
  
  // Possible responses, in corresponding order
  
  const replies = [
    ["Hello!", "Hi!", "Hey!", "Hi there!","Howdy"],
    [
      "Fine... how are you?",
      "Pretty well, how are you?",
      "Fantastic, how are you?"
    ],
    [
      "Nothing much",
      "About to go to sleep",
      "Can you guess?",
      "I don't know actually"
    ],
    ["I am infinite"],
    ["I am just a bot", "I am a bot. What are you?"],
    ["The one true God, JavaScript"],
    ["I am nameless", "I don't have a name"],
    ["I love you too", "Me too"],
    ["Have you ever felt bad?", "Glad to hear it"],
    ["Why?", "Why? You shouldn't!", "Try watching TV"],
    ["What about?", "Once upon a time..."],
    ["Tell me a story", "Tell me a joke", "Tell me about yourself"],
    ["Bye", "Goodbye", "See you later"],
    ["Sushi", "Pizza","veg-omellet","healthy food"],
    ["Bro!"],
    ["Great question"],
    ["That's ok","I understand","What do you want to talk about?"],
    ["Please say something :("],
    ["Haha!","Good one!"]
  ]
  
  // Random for any other user input
  
  const alternative = [
    "Same",
    "Go on...",
    "Bro...",
    "Try again",
    "I'm listening...",
    "I don't understand :/"
  ]
  
  // Whatever else you want :)
  
  const coronavirus = ["Please stay home", "Wear a mask", "Fortunately, I don't have COVID", "These are uncertain times"]

The above code defines an easy structure for a chatbot that provides arrays(An array in JavaScript is a data structure that stores a collection of items.) of prompts, possible responses, and alternative responses we can say that these phrases are custom we can modify as according to us regarding any response. The chatbot uses these arrays to generate appropriate replies based on user input. You can experiment with these custom constants for better understanding.

Create Another File, name it Script.js and paste the following code:-

document.addEventListener("DOMContentLoaded", () => {
    const inputField = document.getElementById("input");
    inputField.addEventListener("keydown", (e) => {
      if (e.code === "Enter") {
        let input = inputField.value;
        inputField.value = "";
        output(input);
      }
    });
  });
  
  function output(input) {
    let product;
  
    // Regex remove non word/space chars
    // Trim trailing whitespce
    // Remove digits - not sure if this is best
    // But solves problem of entering something like 'hi1'
  
    let text = input.toLowerCase().replace(/[^\w\s]/gi, "").replace(/[\d]/gi, "").trim();
    text = text
      .replace(/ a /g, " ")   // 'tell me a story' -> 'tell me story'
      .replace(/i feel /g, "")
      .replace(/whats/g, "what is")
      .replace(/please /g, "")
      .replace(/ please/g, "")
      .replace(/r u/g, "are you");
  
    if (compare(prompts, replies, text)) { 
      // Search for exact match in `prompts`
      product = compare(prompts, replies, text);
    } else if (text.match(/thank/gi)) {
      product = "You're welcome!"
    } else if (text.match(/(corona|covid|virus)/gi)) {
      // If no match, check if message contains `coronavirus`
      product = coronavirus[Math.floor(Math.random() * coronavirus.length)];
    } else {
      // If all else fails: random alternative
      product = alternative[Math.floor(Math.random() * alternative.length)];
    }
  
    // Update DOM
    addChat(input, product);
  }
  
  function compare(promptsArray, repliesArray, string) {
    let reply;
    let replyFound = false;
    for (let x = 0; x < promptsArray.length; x++) {
      for (let y = 0; y < promptsArray[x].length; y++) {
        if (promptsArray[x][y] === string) {
          let replies = repliesArray[x];
          reply = replies[Math.floor(Math.random() * replies.length)];
          replyFound = true;
          // Stop inner loop when input value matches prompts
          break;
        }
      }
      if (replyFound) {
        // Stop outer loop when reply is found instead of interating through the entire array
        break;
      }
    }
    return reply;
  }
  
  function addChat(input, product) {
    const messagesContainer = document.getElementById("messages");
  
    let userDiv = document.createElement("div");
    userDiv.id = "user";
    userDiv.className = "user response";
    userDiv.innerHTML = `<img src="user.png" class="avatar"><span>${input}</span>`;
    messagesContainer.appendChild(userDiv);
  
    let botDiv = document.createElement("div");
    let botImg = document.createElement("img");
    let botText = document.createElement("span");
    botDiv.id = "bot";
    botImg.src = "bot-mini.png";
    botImg.className = "avatar";
    botDiv.className = "bot response";
    botText.innerText = "Thinking...";
    botDiv.appendChild(botText);
    botDiv.appendChild(botImg);
    messagesContainer.appendChild(botDiv);
    // Keep messages at most recent
    messagesContainer.scrollTop = messagesContainer.scrollHeight - messagesContainer.clientHeight;
  
    // Fake delay to seem "real"
    setTimeout(() => {
      botText.innerText = `${product}`;
    }, 2000
    )
  
  }

The above code is the main logic of the ChatBot Application :-

The below code will trigger an event listener for the DOMContentLoaded event, which will fire when the HTML document has been fully loaded. In this event listener, it will listen for the keydown event on the input field with the ID “input.” If you press the key “Enter,” it will get the input value, clear the input field, and call the output function with the user’s input.

document.addEventListener("DOMContentLoaded", () => {
    const inputField = document.getElementById("input");
    inputField.addEventListener("keydown", (e) => {
        if (e.code === "Enter") {
            let input = inputField.value;
            inputField.value = "";
            output(input);
        }
    });
});

The Output function(Below is code snippet) processes the user’s input and determines the appropriate response. It uses regular expressions(Resource available at end of the article) and string manipulations to preprocess the input.

The Compare function will be called to check if there’s an exact match in the predefined prompts array that we’ve defined in the previously created file. If there is a matched phrase in prompts, it selects a response from the corresponding replies array.

After finding the response, the addChat function is called to update the DOM with user’s input and the chatbot’s response.

function output(input) {
    let product;
  
    // Regex remove non word/space chars
    // Trim trailing whitespce
    // Remove digits - not sure if this is best
    // But solves problem of entering something like 'hi1'
  
    let text = input.toLowerCase().replace(/[^\w\s]/gi, "").replace(/[\d]/gi, "").trim();
    text = text
      .replace(/ a /g, " ")   // 'tell me a story' -> 'tell me story'
      .replace(/i feel /g, "")
      .replace(/whats/g, "what is")
      .replace(/please /g, "")
      .replace(/ please/g, "")
      .replace(/r u/g, "are you");
  
    if (compare(prompts, replies, text)) { 
      // Search for exact match in `prompts`
      product = compare(prompts, replies, text);
    } else if (text.match(/thank/gi)) {
      product = "You're welcome!"
    } else if (text.match(/(corona|covid|virus)/gi)) {
      // If no match, check if message contains `coronavirus`
      product = coronavirus[Math.floor(Math.random() * coronavirus.length)];
    } else {
      // If all else fails: random alternative
      product = alternative[Math.floor(Math.random() * alternative.length)];
    }
  
    // Update DOM
    addChat(input, product);
  }

The compare function will iterates through the promptsArray(from Constants.js file)to find an exact match for the processed user input. If a match is found, it selects a random response from the corresponding repliesArray as bor response and returns it.

Conclusion

In Conclusion, the development of Chatbot using JavaScript is worth it and I hope you have learnt something new. And just below there are highly Valued resources that will be helpful for your upcoming project-building journey. Also, we’ve already a tutorial for you on How to Create a Chatbot using HTML, CSS, and JavaScript you can also go through this article.

We have seen the combination of JavaScript’s flexibility, regular expressions, and event-driven nature And DOM concepts that make it a suitable choice for developing intelligent and interactive chatbot solutions.

Resources

Arrays, Rejex

Source Code Credit: Sylvia Pap