Update: a slightly different version of the code is now on GitHub, and you can test Monkeybot here.
I made a simple chatbot called Monkeybot for my website, and I’ll share the code for anyone who wants to do something similar. The Monkeybot simply replies with a string of random letters to any question from the user, simulating a monkey hammering on the keyboard. It was a fun challenge to build, and I’m sharing it as a template that can be used for other chatbot-ideas.
There are comments inside the code that explain the different elements. You can customize the code and make it work for your specific use case.
This is the Javascript for the Monkeybot, monkeyScript.js:
// The chatbot object
const chatbot = {
name: "Monkey",
reply: function (question) {
// Generate a random string of lowercase and uppercase characters
let response = "";
for (let i = 0; i < 20; i++) {
response += Math.random() < 0.5 ?
String.fromCharCode(Math.floor(Math.random() * 26) + 97) :
String.fromCharCode(Math.floor(Math.random() * 26) + 65);
}
return response;
}
};
// Get references to the input and output elements
const inputEl = document.getElementById("input");
const outputEl = document.getElementById("output");
// automatically scroll to the bottom of the chatbot
const chatbotContainer = document.getElementById("chatbot-container");
// Add an event listener to the input element to listen for user input
inputEl.addEventListener("keydown", function (event) {
// If the user presses the Enter key, get the user's input and generate a response
if (event.keyCode === 13) {
sendMessage();
}
});
// Add an event listener to the send button
sendBtn.addEventListener("click", function () {
sendMessage();
});
function sendMessage() {
// Get the user's input
const userInput = inputEl.value;
// If the user's input is empty, return without sending the message
if (!userInput) {
return;
}
// Clear the input element
inputEl.value = "";
// Append the user's input to the output element
outputEl.innerHTML += "<p><strong class='blue-text'>You:</strong> " + userInput + "</p>";
// Append the "Monkey is typing" message
outputEl.innerHTML += "<p><strong>Monkey:</strong> Monkey is typing...</p>";
// Scroll to the bottom of the chatbot container
chatbotContainer.scrollTop = chatbotContainer.scrollHeight;
// Delay for 2 seconds before generating the chatbot's response
setTimeout(() => {
// Generate a response from the chatbot
const chatbotResponse = chatbot.reply(userInput);
// Replace the "Monkey is typing" message with the chatbot's response
outputEl.innerHTML = outputEl.innerHTML.replace("<p><strong>Monkey:</strong> Monkey is typing...</p>", "<p><strong>Monkey:</strong> " + chatbotResponse + "</p>");
// Scroll to the bottom of the chatbot container
chatbotContainer.scrollTop = chatbotContainer.scrollHeight;
}, 1000);
}
// Open pop-up form
function openForm() {
document.getElementById("chatbotForm").style.display = "block";
}
// Close pop-up form
function closeForm() {
document.getElementById("chatbotForm").style.display = "none";
}
// close if Esc is pressed on the keyboard
document.addEventListener("keydown", function (event) {
if (event.keyCode === 27) {
closeForm();
}
});
Note that some of the above code is related to the pop-up form, so you can remove it if you don’t need it.
The CSS is of course just the styling of the chatbot and not nececcary for the functionality (If you don’t want it you should remove or replace references to it from the HTML that comes later in this post).
chatbot.css:
/* Apply border-box sizing to all elements for consistent box model */
* {box-sizing: border-box;}
/* Button used to open the chat form - fixed at the bottom of the page */
.open-button {
background-color: rgb(77, 47, 27);
color: white;
padding: 1vw 1vw;
font-size: 1.5vw;
border: none;
border-radius: 0.5vw;
cursor: pointer;
position: fixed;
bottom: 2vw;
right: 4vw;
transform: scale(1);
}
/* Open button scale for small screens */
@media (max-width: 600px) {
.open-button {
transform: scale(2);
}
}
/* Open button scale for medium screens */
@media (min-width: 601px) and (max-width: 900px) {
.open-button {
transform: scale(1.3);
}
}
/* Blue text for the user "You:" */
.blue-text {
color: rgb(104, 116, 151);
}
/* The popup chat - hidden by default */
.chat-popup {
display: none;
position: fixed;
bottom: 0;
right: 15px;
border: 3px solid #252221;
border-radius: 5px;
z-index: 9;
}
/* Chatbot container that holds the conversation history*/
#chatbot-container {
height: 300px; /* maximum height of the chat box */
overflow-y: scroll; /* scrollbar */
word-wrap: break-word;
}
/* Styling of the form container */
.form-container {
max-width: 300px;
padding: 10px;
background-color: #f3f3f3;
}
/* Form header */
.form-container h1 {
/* background-color: rgb(77, 47, 27); */
/* color: #fff; */
/* padding: 0 !important; */
text-align: center;
}
/* Full-width textarea */
.form-container input {
width: 85%;
padding: 12px 20px;
margin: 8px 0;
border: none;
background: #f1f1f1;
float: left;
}
/* Styling for the close button */
.close-button {
background-color: rgb(165, 45, 24);
color: white;
padding: 16px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
width: 100%;
margin-bottom:10px;
margin-top: 10px;
}
/* Styling for the Send button*/
.send-button {
font-size: 20px;
color: currentColor;
color: rgb(49, 38, 31);
margin-left: 10px;
cursor: pointer;
border: none;
background-color: transparent;
}
/* Float the send button to the right within the form container*/
.form-container .send-button {
float: right;
}
/* Add hover effects to buttons */
.form-container .close-button:hover, .open-button:hover, .send-button:hover {
opacity: 0.8;
}
And finally this is the HTML. Not that there are references to the above chatbot.css stylesheet and also to the W3.CSS stylesheet which I use for my website. You can remove it without changing the functionality of the code. The third reference is to the font-awesome icon library and it is used for the chat bubble and paper plane icons.
HTML:
<head>
<!-- CSS -->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="chatbot.css">
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<!-- Chatbot pop-up -->
<button class="open-button" onclick="openForm()"><span class="fa fa-comments"></span> Monkeybot</button>
<div class="chat-popup" id="chatbotForm">
<div class="form-container">
<h1><span class="fa fa-comments"></span><strong> MONKEYBOT</strong></h1>
<div id="chatbot-container" class="chatbot">
<p id="output"></p>
</div>
<div class="chatbot-input-container">
<p class="chatbot-input-label"></p>
<input id="input" class="input" type="text" placeholder="Ask monkey anything..." />
<button class="send-button" type="button" onclick="sendMessage()">
<i class="fa fa-paper-plane" aria-hidden="true"></i>
</button>
<button class="close-button" type="button" onclick="closeForm()">Close</button>
</div>
</div>
</div>
<!-- Link to monkeybot Javascript -->
<script src="monkeyScript.js"></script>
</body>
Note the link to the monkeyscript.js at the end of the HTML. You can also just put the HTML, CSS and JavaScript into one file if you prefer.