luna-bot
v1.0.1
Published
A very easy way to create a bot for whatsapp
Downloads
15
Readme
Luna Bot
Luna Bot is a lightweight, easy-to-use WhatsApp bot framework designed to create interactive conversational experiences with support for menus, choices, and multi-step forms. Build your own WhatsApp bots quickly with page-based navigation and state management per user.
Features
- Page navigation driven by JSON configuration files
- Interactive choice menus (CHOICES type pages)
- Multi-step forms with question iteration and answer collection (FORM type pages)
- User state management to handle conversations smoothly
- Built on top of whatsapp-web.js
Installation
npm install luna-botQuick Start
import { Bot } from "luna-bot";
const bot = new Bot("my-bot-name");
await bot.start();It is folder based
It means that the navigation works in an automatic way, hierarchically through the folder directory. Every index.json is the main page, and every sibling (including other folders) are inferred as choice pages for navigation.
CHOICES page model
To make a navigation page, the structure is:
{
"id": "start",
"type": "CHOICES",
"description": "This model provides a starting point for user interaction, offering choices to navigate the application.",
"header": {
"title": "Welcome!",
"text": "What would you like to do?"
},
"choices": [
{
"text": "🎮 Play",
"jumpTo": "games"
},
{
"text": "🛒 Groceries",
"jumpTo": "store"
}
]
}The choices field is OPTIONAL, if you don't specify the routes it will infer automatically by the sibling pages.
FORM page model
{
"id": "userInfo",
"type": "FORM",
"previousStep": "previousStep",
"description": "This model collects basic user information such as age and email.",
"header": {
"title": "User Information",
"text": "Let's start with some basic questions."
},
"form": {
"questions": [
{
"id": "favFood",
"label": "What's your favourite food?",
"type": "number",
"options": {
"choices": [
"orange",
"avocado",
"lasagne",
"pizza",
"chocolate pudding"
]
}
},
{
"id": "age",
"label": "Type your age:",
"type": "number"
},
{
"id": "email",
"label": "Type your email:",
"type": "text"
}
],
"onComplete": {
"jumpTo": "index",
"message": "Thanks!"
}
}
}Usage
Making pages with this bot is quite easy; how you deal with the data you get from forms or choices is up to you. Here is the core Bot code (simplified):
import { Navigation } from "./Navigation";
import { PageManager } from "./PageManager";
import { Client, LocalAuth } from "whatsapp-web.js";
import qrcodeTerminal from "qrcode-terminal";
// User state interface
interface BotState {
mode: "CHOICES" | "FORM" | null;
pageId: string;
questionIndex?: number;
answers?: Map<string, string>;
}
export class Bot {
private name: string;
private navigation = new Navigation();
private pageManager = PageManager.getInstance();
private client: Client | null = null;
private isClientReady = false;
private states: Map<string, BotState> = new Map();
constructor(name: string) {
this.name = name;
}
async initializeClient() {
if (this.isClientReady) return;
this.client = new Client({
authStrategy: new LocalAuth({ clientId: this.name }),
puppeteer: {
headless: true,
executablePath: "/usr/bin/chromium",
args: ["--no-sandbox", "--disable-setuid-sandbox"],
},
});
this.client.once("qr", (qr) => {
console.log("QR Code generated for scanning");
qrcodeTerminal.generate(qr, { small: true });
});
this.client.once("ready", () => {
this.isClientReady = true;
console.log("Bot is ready!");
});
await this.client.initialize();
}
async start() {
await this.initializeClient();
this.client?.removeAllListeners("message");
this.client?.on("message", async (message) => {
if (message.id.fromMe) return;
const userId = message.from;
const text = message.body?.toLowerCase() ?? "";
await this.handleMessage(userId, text);
});
}
async handleMessage(userId: string, text: string) {
const page = this.pageManager.getPageById(
this.navigation.getCurrentPageId(userId)
);
if (!page) return;
let state = this.states.get(userId);
if (page.type === "FORM") {
await this.handleForm(userId, text, page, state);
return;
}
if (page.type === "CHOICES") {
if (!state || state.pageId !== page.id) {
this.states.set(userId, { mode: "CHOICES", pageId: page.id });
await this.sendChoicesPage(userId, page);
return;
}
const index = Number(text);
if (!isNaN(index) && page.choices && page.choices[index - 1]) {
const nextPageId = page.choices[index - 1].jumpTo;
this.navigation.navigateTo(userId, nextPageId);
this.states.delete(userId);
await this.handleMessage(userId, "");
} else {
await this.sendMessage(userId, "❌ Invalid option. Try again.");
}
}
}
async handleForm(userId: string, text: string, page: any, state?: BotState) {
const questions = page.form?.questions ?? [];
if (!state || state.pageId !== page.id) {
this.states.set(userId, {
mode: "FORM",
pageId: page.id,
questionIndex: 0,
answers: new Map(),
});
await this.sendQuestion(userId, questions[0]);
return;
}
const currentIndex = state.questionIndex ?? 0;
const currentQuestion = questions[currentIndex];
const options = currentQuestion.options?.choices ?? [];
// Simple type validation function
function isValidType(value: string, type: string): boolean {
switch (type) {
case "number":
return !isNaN(Number(value));
case "text":
return value.trim().length > 0;
default:
return true;
}
}
if (!isValidType(text, currentQuestion.type)) {
await this.sendMessage(
userId,
`❌ Invalid response type. Please answer with a ${currentQuestion.type}.`
);
await this.sendQuestion(userId, currentQuestion);
return;
}
if (options.length > 0) {
const choiceIndex = Number(text) - 1;
if (
isNaN(choiceIndex) ||
choiceIndex < 0 ||
choiceIndex >= options.length
) {
await this.sendMessage(userId, "❌ Invalid choice. Try again.");
await this.sendQuestion(userId, currentQuestion);
return;
}
state.answers?.set(currentQuestion.id, options[choiceIndex]);
} else {
state.answers?.set(currentQuestion.id, text);
}
if (currentIndex + 1 < questions.length) {
state.questionIndex = currentIndex + 1;
await this.sendQuestion(userId, questions[state.questionIndex]);
} else {
let msg = "*📝 Recorded answers:*\n";
for (const [key, value] of state.answers!) {
msg += `• ${key}: ${value}\n`;
}
await this.sendMessage(userId, msg);
this.states.delete(userId);
if (page.form.onComplete?.jumpTo) {
this.navigation.navigateTo(userId, page.form.onComplete.jumpTo);
const nextPage = this.pageManager.getPageById(
this.navigation.getCurrentPageId(userId)
);
if (nextPage) {
await this.sendChoicesPage(userId, nextPage);
}
}
}
}
async sendChoicesPage(userId: string, page: any) {
let text = `*${page.label ?? page.header?.title ?? "(no title)"}*\n${
page.header?.text ?? ""
}\n\n`;
page.choices?.forEach((choice: any, i: number) => {
text += `${i + 1} - ${choice.label ?? choice.text}\n`;
});
await this.sendMessage(userId, text);
}
async sendQuestion(userId: string, question: any) {
let text = `*${question.label}*`;
const options = question.options?.choices ?? [];
if (options.length > 0) {
for (let i = 0; i < options.length; i++) {
text += `\n${i + 1} - ${options[i]}`;
}
}
await this.sendMessage(userId, text);
}
async sendMessage(to: string, text: string) {
if (!this.client || !this.isClientReady) return;
await this.client.sendMessage(to, text);
}
async destroyClient() {
if (this.client) {
await this.client.destroy();
this.client = null;
this.isClientReady = false;
}
}
}License
MIT License © 2025 Zaqueu Nilton
