Building a Simple Chatbot (No AI Required) - Part 2
Time to add the brains! Let's write the JavaScript that makes our chatbot actually respond to users.
Adding the Bot's Brain
In [Part 1](/blog/building-simple-chatbot-no-ai-part-1), we built the HTML and CSS for our chatbot interface. Now let's make it actually do something.
The Response System
The key to a simple chatbot is pattern matching. We define triggers and responses:
const responses = {
greetings: {
triggers: ["hello", "hi", "hey", "howdy", "hola"],
responses: [
"Hey there! How can I help you today?",
"Hi! What's on your mind?",
"Hello! Nice to meet you!"
]
},
farewell: {
triggers: ["bye", "goodbye", "see ya", "later"],
responses: [
"Take care! Come back anytime.",
"Goodbye! Have a great day!",
"See you later! 👋"
]
},
thanks: {
triggers: ["thank", "thanks", "appreciate"],
responses: [
"You're welcome!",
"Happy to help!",
"Anytime! 😊"
]
}
};
Finding Matches
We need a function to check user input against our triggers:
function findResponse(userInput) {
const input = userInput.toLowerCase();
for (const category in responses) {
const { triggers, responses: replies } = responses[category];
for (const trigger of triggers) {
if (input.includes(trigger)) {
// Return a random response from the category
const randomIndex = Math.floor(Math.random() * replies.length);
return replies[randomIndex];
}
}
}
// Default response if no match
return "I'm not sure I understand. Could you rephrase that?";
}
Putting It All Together
const chatMessages = document.getElementById("chatMessages");
const userInput = document.getElementById("userInput");
const sendBtn = document.getElementById("sendBtn");
function addMessage(text, isUser) {
const messageDiv = document.createElement("div");
messageDiv.classList.add("message", isUser ? "user" : "bot");
messageDiv.textContent = text;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
function handleUserInput() {
const text = userInput.value.trim();
if (!text) return;
// Add user message
addMessage(text, true);
userInput.value = "";
// Simulate typing delay
setTimeout(() => {
const response = findResponse(text);
addMessage(response, false);
}, 500);
}
sendBtn.addEventListener("click", handleUserInput);
userInput.addEventListener("keypress", (e) => {
if (e.key === "Enter") handleUserInput();
});
Making It Smarter
You can expand this by:
1. **Adding more categories** - Help topics, product info, etc. 2. **Using regex** - For more flexible matching 3. **Conversation state** - Remember context between messages
Try It Out
The full working code is on GitHub: github.com/adhddev/simple-chatbot
In the next part, we'll look at adding conversation flow and context awareness.