A robot is a programable computer. It is capable of carrying out a complex series of actions automatically. A robot can be controlled by an external device or a device fixed in it. Robots were invented by George C. Devol in the early 1950s. These were built for universal automation but failed.
A bot is a software program that is trained to do certain tasks. These are automated and work on the basis of given instructions. These are programmed to do work as humans without manually getting started up. Bots work over a network and work more efficiently than humans, but they perform repetitive tasks. bots get the content interacting through websites, or webpages.
Bots can be:
- Chatbots: Bots that simulate human conversation by responding to certain phrases with programmed responses
- Web crawlers (Googlebots): Bots that scan content on webpages all over the Internet
- Social bots: Bots that operate on social media platforms
- Malicious bots: Bots that scrape content, spread spam content, or carry out credential stuffing attacks.
CREATING A CHATBOT USING JAVASCRIPT-
In this article, we can learn to create a chatbot using javascript and build a web application for a basic chatbot.
Step1– Creating an Html file, named bot.html containing code –
<div id="container" class="container">
<img src="https://cdn.pixabay.com/photo/2020/02/13/02/34/robot-4844306__340.png" height="300vh" alt="Chatbot clipart">
<div id="chat" class="chat">
<div id="messages" class="messages"></div>
<input id="input" type="text" placeholder="Type a message..." autocomplete="off" autofocus="true" />
</div>
</div>
here, In this code, I have created a div with id main which will have an input of text through which the bot can chat.
Step2-Create a CSS file style.css which will contain the stylesheet 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: silver;
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: 0;
padding: 15px;
margin-left: auto;
border-radius: 10px;
}
.messages {
display: flex;
flex-direction: column;
overflow: scroll;
height: 90%;
width: 100%;
background-color: white;
padding: 15px;
margin: 15px;
border-radius: 10px;
}
#bot {
margin-right: auto;
}
#user {
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;
}
}
Step3- Now create a bot.js file that will contain javascript functions to be implemented for creating a bot.
const inputField = document.getElementById("input")
inputField.addEventListener("keydown", function(e) {
if (e.code === "Enter") {
let input = inputField.value;
inputField.value = "";
output(input);
}
});
In the above code, the inputField function is called when a user press Enter key. The addEventListener() is a javascript inbuilt function that took place when the second argument is called off. The document.getElementById(“input”) is called when HTML DOM is called having id with specific value. After getting the input message in the inputfield.value. The inputfield.value is given a blank string as it should have the next message. The next function is the output function which will help the bot to get its accurate answer.
Step 4- Creation of output function.
This is the output function for better results by the bot.
function output()
{
let text = input.toLowerCase().replace(/[^\w\s\d]/gi, "");
…
text = text
.replace(/ a /g, " ")
.replace(/whats/g, "what is")
.replace(/please /g, "")
.replace(/ please/g, "");
}
This output function removes everything except words. For example – if someone has given input as what’s your name and what is your name the bot will treat both the same and is easily understood by the bot.
Step 5-In our next step is we will write the possible bot responses on the basis of user input.
const references = [
["how are you", "how is life", "how are things"],
["hi", "hey", "hello", "good morning", "good afternoon"],
["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"
],
["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"],
["what", "why", "how", "where", "when"],
["no", "not sure", "maybe", "no thanks"],
[""],
["haha", "ha", "lol", "hehe", "funny", "joke"]
];
const answers = [
[
"Fine... how are you?",
"Pretty well, how are you?",
"Fantastic, how are you?"
],
[
"Hello!", "Hi!", "Hey!", "Hi there!", "Howdy"
],
[
"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"],
["Have you ever felt bad?", "Glad to hear it"],
["Why?", "Why? You shouldn't!"],
["What about?", "Once upon a time..."],
["Tell me a story", "Tell me a joke", "Tell me about yourself"],
["Bye", "Goodbye", "See you later"],
["Pasta", "Burger"],
["Great question"],
["That's ok", "What do you want to talk about?"],
["Please say something :("],
["Haha!", "Good one!"]
];
const alternatives = [
"Go on...",
"Try again",
];
here the above code shows the same indexes of class answers and class responses. which means if the user input matches at any index of reference class then the bot will answer with the same index of the answer class . but if users’ input is not matched then class alternatives is called.
Step 5- How does Chatbot respond?
Now we are familiar with how chatbots respond. now we will go through how these responses are called.
function compare(responseArray, answersArray, string) {
let item;
for (let x = 0; x < responseArray.length; x++) {
for (let y = 0; y < responseArray[x].length; y++) {
if (responseArray[x][y] === string) {
items = answersArray[x];
item = items[Math.floor(Math.random() * items.length)];
}
}
}
return item;
}
Step 6-This compare function is used to match the string from the references class and the output is given with the help of the output function.
function output(input) {
let product;
let text = input.toLowerCase().replace(/[^\w\s\d]/gi, "");
text = text
.replace(/ a /g, " ")
.replace(/whats/g, "what is")
.replace(/please /g, "")
.replace(/ please/g, "");
if (compare(response, answers, text)) {
product = compare(response, answers, text);
}
else {
product = alternatives[Math.floor(Math.random() * alternatives.length)];
}
//update DOM
addChatEntry (input, product);
}
This output function gives the output message by the bot, if the class alternative is called off then the output is given randomly with the use of Math.random() function.
Step 7- After the output dom is updated.
function addChatEntry(input, product) {
const messagesContainer = document.getElementById("messages");
let userDiv = document.createElement("div");
userDiv.id = "user";
userDiv.className = "user response";
userDiv.innerHTML = `${input}`;
messagesContainer.appendChild(userDiv);
let botDiv = document.createElement("div");
let botText = document.createElement("span");
botDiv.id = "bot";
botDiv.className = "bot response";
botText.innerText = "Typing...";
botDiv.appendChild(botText);
messagesContainer.appendChild(botDiv);
…
setTimeout(() => {
botText.innerText = `${product}`;
}, 2000); }
addChatEntry is called for showing the history of chat for a better view of chat.
and At the end setTimeout() function is called for a better experience and looks like a bot answer after thinking.
and here is the final look of our chatbot.
Thanks for reading! 🙂