WhatsApp bots can automate responses, handle customer inquiries, and perform various tasks. In this guide, we will walk through the process of creating a WhatsApp bot using whatsapp-web.js.
Step 1: Set Up Your Project
Before starting, ensure you have Node.js installed. You can download it from nodejs.org.
Initialize a Node.js Project
Create a new project directory and initialize it:
mkdir whatsapp-bot
cd whatsapp-bot
npm init -y
Install Dependencies
Install whatsapp-web.js, qrcode-terminal, and dotenv
npm install whatsapp-web.js qrcode-terminal dotenv
These packages help interact with WhatsApp Web, display QR codes for authentication, and manage environment variables.
Step 2: Create Your Bot Script
Create an index.js file and add the following code:
const { Client, LocalAuth } = require("whatsapp-web.js");
const qrcode = require("qrcode-terminal");
const client = new Client({
authStrategy: new LocalAuth(), // Stores authentication locally
});
client.on("qr", (qr) => {
console.log("Scan this QR code with WhatsApp to log in:");
qrcode.generate(qr, { small: true });
});
client.on("ready", () => {
console.log("Bot is ready!");
});
client.on("message", async (message) => {
if (message.body.toLowerCase() === "hi") {
await message.reply("Hello! How can I assist you?");
}
});
client.initialize();
Step 3: Run Your Bot
Run the bot with the following command:
node index.js
Scan the QR code displayed in the terminal with your WhatsApp mobile app. Once scanned, your bot will be connected.
Step 4: Enhancing Your Bot
- Automate responses: Add more message handlers to automate replies.
- Connect to a database: Store user data using MongoDB or Firebase.
- Deploy the bot: Run your bot on a server like AWS or Heroku.
Conclusion
With whatsapp-web.js, building a WhatsApp bot is easy and effective. You can expand its functionality to handle complex workflows and integrate it with APIs. Try it out and automate your communications today!