whatsflow
v0.0.5
Published
Simple WhatsApp automation SDK
Downloads
524
Maintainers
Readme
<README_CONTENT>
Whatsflow 🚀
Whatsflow is a powerful, lightweight, and incredibly easy-to-use WhatsApp automation SDK built on top of Baileys. Designed for developers who want to build smart WhatsApp bots effortlessly, Whatsflow abstracts the complexities of connection management, session handling, message routing, conversational flows, and AI integration into a clean, modern API.
Whether you're building a simple auto-responder, a complex customer support bot with stateful flows, or an AI-powered assistant, Whatsflow provides the tools you need—with zero boilerplate.
🌟 Features
- Blazing Fast Setup: Automatically handles WhatsApp Web QR generation and multi-file session authentication.
- Smart Routing: easily listen to exact text matches, RegEx patterns, wildcards, or commands.
- Stateful Flows: Build multi-step conversational flows (e.g., surveys, lead generation) with just an array of functions.
- Built-in AI Power: Native support for Gemini, OpenAI, Anthropic, and Ollama. Connect your API key and respond intelligently.
- Type-safe: Designed with TypeScript for an excellent developer experience.
📦 Installation
npm install whatsflow @whiskeysockets/baileys
# or
yarn add whatsflow @whiskeysockets/baileysNote: Ensure you are running Node.js 18+ to support native fetch used by the AI integrations.
🚀 Quick Start
Here's how easily you can get your bot running in under 20 lines of code:
import { createBot } from "whatsflow";
const bot = createBot();
// Triggered when WhatsApp is successfully connected
bot.onReady(() => {
console.log("Bot is ready and connected to WhatsApp!");
});
// Simple keyword matching
bot.onText("hi", (msg, bot) => {
bot.reply(msg, "Hello there! 👋");
});
// Start the bot
bot.start();When you run this script, it will generate a QR code in your terminal. Scan it with your WhatsApp app via "Linked Devices".
📖 Core Concepts & Examples
1. Connecting and Listening to Messages
Whatsflow provides intuitive methods to listen to different types of incoming messages:
const bot = createBot();
// 1. Exact Match
bot.onText("ping", (msg, bot) => {
bot.reply(msg, "pong!");
});
// 2. Wildcard Match (listens if text contains the word)
bot.onText("*price*", (msg, bot) => {
bot.reply(msg, "Our starting price is $99! 💰");
});
// 3. RegEx Match
bot.onText(/hello|hey/, (msg, bot) => {
bot.reply(msg, "Regex match successful! 🔥");
});
// 4. Command Listeners (matches exact word after a slash '/')
// E.g., user sends: /start
bot.onCommand("start", (msg, bot) => {
bot.reply(msg, "Welcome to the bot! 🚀");
});
// 5. Catch-All / Fallback
bot.onMessage((msg, bot) => {
console.log(`Received unknown message: ${msg.text}`);
});2. Conversational Flows (Stateful Interactions)
Building surveys or collecting data step-by-step is effortless using the .flow API. Define an array of steps, and Whatsflow will handle the state for each specific user automatically.
import { Bot, Msg } from "whatsflow/types"; // Adjust import depending on your setup
// Define the flow
bot.flow("onboarding_flow", [
async (msg: Msg, bot: Bot) => {
bot.reply(msg, "Welcome! What is your name?");
},
async (msg: Msg, bot: Bot) => {
// Process the name from the previous step
bot.reply(msg, `Nice to meet you, ${msg.text}! What is your email?`);
},
async (msg: Msg, bot: Bot) => {
// Process the email from the previous step
bot.reply(msg, "Thanks! We've saved your details. We will contact you soon.");
}
]);
// Trigger the flow when the user sends an exact text
bot.onText("register", (msg, bot) => {
bot.startFlow(msg.chatId, "onboarding_flow");
});To manually end a flow before completion, you can call bot.endFlow(msg.chatId).
3. Native AI Integrations
You can transform your WhatsApp bot into an AI agent in minutes. Whatsflow supports Gemini, OpenAI, Anthropic, and Ollama natively.
// 1. Configure the AI Provider
bot.useAI({
provider: "gemini", // or "openai", "anthropic", "ollama"
apiKey: "YOUR_API_KEY_HERE"
});
// 2. Use it in your message handler
bot.onMessage(async (msg, bot) => {
// You can wrap this in a loading state if needed
const reply = await bot.ai(`You are a helpful assistant. User said: ${msg.text}`);
bot.reply(msg, reply);
});Supported Providers Options:
- Gemini:
provider: "gemini", apiKey: "..."(Defaults togemini-2.5-flash) - OpenAI:
provider: "openai", apiKey: "..."(Defaults togpt-4o-mini) - Anthropic:
provider: "anthropic", apiKey: "..."(Defaults toclaude-3-haiku-20240307) - Ollama:
provider: "ollama", baseUrl: "http://localhost:11434", model: "llama3"
4. Sending Messages Programmatically
You can send messages outside of conversational replies via bot.sendMsg(jid, text):
bot.onReady(() => {
// Pass the phone number with country code. The bot will automatically append @s.whatsapp.net
bot.sendMsg("1234567890", "System is online! 🟢");
});🛠️ API Reference
createBot(options?: { silent?: boolean })
Initializes a new bot instance.
silent: If true, prevents Baileys' internal connection logs from spamming your terminal. Default istrue.
Bot Methods
start(): Starts the bot, handles authentication, and outputs the QR code if required.onReady(handler): Called when the connection is fully open.onMessage(handler): A global listener for every valid text message.onText(pattern, handler): Listens to an exact string, a wildcard*word*, or aRegExp.onCommand(command, handler): Listens to commands prefixed with/(e.g./help).flow(name, steps[]): Registers a new stateful conversational flow.useAI(config): Initializes the preferred AI provider.
Handler Context (msg, bot)
Every handler method receives a msg object and the bot instance.
msg.text: The text content of the message.msg.from: The sender's phone number without the WhatsApp suffix.msg.chatId: The WhatsApp JID of the sender or group.msg.raw: The raw Baileys message object.bot.reply(msg, "text"): Reply to the current conversation.bot.sendMsg(jid, "text"): Send a message to a specific JID or phone number.bot.startFlow(chatId, "flow_name"): Initiates a flow for the specific chat.bot.endFlow(chatId): Terminate any active flow for the chat.bot.ai("prompt"): Prompts the integrated AI.
🤝 Contributing
Contributions, issues, and feature requests are welcome!
- Fork the project.
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request.
📝 License
Distributed under the MIT License. See LICENSE for more information.
