Chatbots Tutorial menu

Build a Rule-Based Bot in JavaScript

In this lesson you will build a complete rule-based chatbot in JavaScript that you can run with Node.js.

Step 1: Define Intents

Each intent has a name, keywords that point to it and a reply:

Example

javascript
const intents = [
  { name: "greeting", keywords: ["hello", "hi", "salam", "assalam"],
    reply: "Walaikum Assalam! Ask me about courses, timings or fees." },
  { name: "timings", keywords: ["timing", "time", "open", "close"],
    reply: "We are open Monday to Saturday, 10 am to 8 pm." },
  { name: "courses", keywords: ["course", "courses", "learn", "class"],
    reply: "We teach Web Development, Python, AI, Graphic Design and more." },
  { name: "location", keywords: ["where", "address", "location"],
    reply: "We are in Orangi Town, Karachi." },
];
console.log(intents.length, "intents loaded");
Output
4 intents loaded

Step 2: Clean the Text

Users type in many ways: capital letters, punctuation, extra spaces. Cleaning makes matching reliable:

Example

javascript
function clean(text) {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9\s]/g, " ")
    .split(/\s+/)
    .filter(Boolean);
}
console.log(clean("Salam!!  What's your TIMING?"));
Output
[ 'salam', 'what', 's', 'your', 'timing' ]

Step 3: Score Each Intent

Instead of taking the first match, count how many keywords match each intent and choose the best score. This works better when a message touches two topics.

Here is the full bot, including the parts above:

Example

javascript
const intents = [
  { name: "greeting", keywords: ["hello", "hi", "salam", "assalam"],
    reply: "Walaikum Assalam! Ask me about courses, timings or fees." },
  { name: "timings", keywords: ["timing", "time", "open", "close"],
    reply: "We are open Monday to Saturday, 10 am to 8 pm." },
  { name: "courses", keywords: ["course", "courses", "learn", "class"],
    reply: "We teach Web Development, Python, AI, Graphic Design and more." },
  { name: "location", keywords: ["where", "address", "location"],
    reply: "We are in Orangi Town, Karachi." },
];

function clean(text) {
  return text.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter(Boolean);
}

function getReply(message) {
  const words = clean(message);
  let best = null;
  let bestScore = 0;
  for (const intent of intents) {
    const score = intent.keywords.filter((k) => words.includes(k)).length;
    if (score > bestScore) {
      best = intent;
      bestScore = score;
    }
  }
  return best ? best.reply : "Sorry, I didn't understand. Try asking about courses or timings.";
}

const tests = ["Hi there!", "Which courses can I learn?", "What is the address?", "Tell me a joke"];
for (const t of tests) console.log(`You: ${t}\nBot: ${getReply(t)}`);
Output
You: Hi there!
Bot: Walaikum Assalam! Ask me about courses, timings or fees.
You: Which courses can I learn?
Bot: We teach Web Development, Python, AI, Graphic Design and more.
You: What is the address?
Bot: We are in Orangi Town, Karachi.
You: Tell me a joke
Bot: Sorry, I didn't understand. Try asking about courses or timings.

"Which courses can I learn?" matched two course keywords ("courses" and "learn"), so the courses intent won.

Step 4: Chat in the Terminal

Node.js has a built-in readline module for typing messages. Save this as bot.js, put getReply and intents from above at the top, and run node bot.js:

Example

javascript
const readline = require("readline");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

function ask() {
  rl.question("You: ", (message) => {
    if (message.trim().toLowerCase() === "bye") {
      console.log("Bot: Allah Hafiz!");
      return rl.close();
    }
    console.log("Bot: " + getReply(message));
    ask();
  });
}
ask();

Type bye to end the chat.

Limits of Rule-Based Bots

ProblemExample
Spelling mistakes"timng" does not match "timing"
New wording"When do you shut?" has no keyword
Context"And on Sunday?" does not know you meant timings
Many languagesEvery Urdu and Roman Urdu word needs a rule

These limits are exactly why AI chatbots exist. In the next lesson you will connect an AI model, while keeping this rule-based code as a fast, free first step for common questions if you like.

Exercise

Exercise

Why does the bot clean the text before matching keywords?

Learn Chatbots with a teacher

Join the AI & Prompt Engineering course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp