Simple Chat Bot
A lightweight and flexible chatbot library for Node.js and the browser, written in TypeScript.
Features
- 🚀 Simple and intuitive API
- 📦 TypeScript support out of the box
- 🎯 Pattern matching using RegExp or strings
- ⚡ Async response handling
- 🎨 Customizable response delay and default messages
- 📡 Event-based architecture
Installation
npm install simple-chat-bot
Quick Start
import { ChatBot } from 'simple-chat-bot';
const bot = new ChatBot({
name: 'MyBot',
defaultResponse: "I didn't understand that.",
responseDelay: 500
});
bot.addRule({
pattern: /hello|hi|hey/i,
handler: () => 'Hello! How can I help you today?'
});
bot.addRule({
pattern: /bye|goodbye/i,
handler: () => 'Goodbye! Have a great day!'
});
bot.addRule({
pattern: /my name is (.*)/i,
handler: (message, matches) => `Nice to meet you, ${matches?.[1]}!`
});
bot.on('message', (message) => {
console.log('User:', message.content);
});
bot.on('response', (message) => {
console.log('Bot:', message.content);
});
async function chat() {
await bot.processMessage('Hello');
await bot.processMessage('My name is John');
await bot.processMessage('goodbye');
}
chat();
API Reference
ChatBot Class
Constructor Options
interface ChatBotOptions {
name?: string;
defaultResponse?: string;
responseDelay?: number;
}
Methods
addRule(rule: MatchRule): Add a new response rule
processMessage(content: string): Process a user message
setDefaultResponse(response: string): Update default response
setResponseDelay(delay: number): Update response delay
Events
message: Emitted when a user message is received
response: Emitted when the bot responds
Types
interface Message {
content: string;
type: 'user' | 'bot';
timestamp: Date;
metadata?: Record<string, unknown>;
}
interface MatchRule {
pattern: RegExp | string;
handler: (message: Message, matches: RegExpMatchArray | null) => Promise<string> | string;
}
License
MIT