How to Build a WhatsApp Web Chatbot Using Node.js to Automate Messages
Automating WhatsApp messages can be useful for tasks like reminders, notifications, or even simple customer support. In this tutorial, we will guide you step-by-step to create a WhatsApp Web chatbot using Node.js and the whatsapp-web.js
library.
Step 1: Set Up Your Node.js Environment
Before starting, ensure Node.js is installed on your system. You can download it from Node.js official website.
Next, initialize a new Node.js project:
1 2 3 |
mkdir whatsapp-chatbot cd whatsapp-chatbot npm init -y |
Step 2: Install Required Dependencies
We will use the whatsapp-web.js
library for interacting with WhatsApp Web. Install it along with qrcode-terminal
for displaying the QR code in the terminal:
1 |
npm install whatsapp-web.js qrcode-terminal |
Step 3: Write the Chatbot Code
Create a file named index.js
in your project directory and paste the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
const { Client, LocalAuth } = require('whatsapp-web.js'); const qrcode = require('qrcode-terminal'); // Initialize the client with session persistence const client = new Client({ authStrategy: new LocalAuth(), }); // Generate and display QR code client.on('qr', (qr) => { console.log('Scan this QR code with WhatsApp:'); qrcode.generate(qr, { small: true }); }); // Log successful authentication client.on('ready', () => { console.log('WhatsApp Web Client is ready!'); }); // Listen for incoming messages (optional) client.on('message', (message) => { console.log(`Message received from ${message.from}: ${message.body}`); // Example auto-reply if (message.body.toLowerCase() === 'hello') { message.reply('Hi there! How can I help you?'); } }); // Function to send messages async function sendMessage(to, text) { try { await client.sendMessage(to, text); console.log(`Message sent to ${to}: ${text}`); } catch (error) { console.error(`Failed to send message to ${to}:`, error); } } // Start the client client.initialize(); // Example: Sending a message after the client is ready client.on('ready', async () => { const phoneNumber = '911234567890'; // Replace with recipient's phone number const message = 'Hello! This is an automated message.'; // WhatsApp requires the phone number with country code and no special characters const chatId = `${phoneNumber}@c.us`; await sendMessage(chatId, message); }); |
Step 4: Run the Chatbot
To run your chatbot, use the following command:
node index.js
Scan the QR code displayed in the terminal with your WhatsApp app. Once authenticated, the bot will be ready to send and receive messages.
Step 5: Automate Messages from a File (Optional)
To send messages in bulk from a file, create a file named contacts.json
in the project directory with the following structure:
1 2 3 4 5 6 7 8 9 10 |
[ { "phone": "911234567890", "message": "Hello, this is a test message!" }, { "phone": "919876543210", "message": "Good morning! Have a great day." } ] |
Modify the script to read from this file and send messages:
1 2 3 4 5 6 7 8 9 10 11 |
const fs = require('fs'); client.on('ready', async () => { const contacts = JSON.parse(fs.readFileSync('contacts.json')); for (const contact of contacts) { const chatId = `${contact.phone}@c.us`; await sendMessage(chatId, contact.message); await new Promise((resolve) => setTimeout(resolve, 2000)); // Delay to avoid spam } }); |
Step 6: Best Practices
- Avoid Spamming: Add delays between messages to prevent being flagged by WhatsApp.
- Session Persistence: Use
LocalAuth
to persist your session across restarts without needing to scan the QR code repeatedly. - Error Handling: Implement robust error handling for scenarios like unreachable contacts or network issues.
- Respect Privacy: Use this bot responsibly and ensure recipients have opted in to receive messages.
Conclusion
You’ve successfully created a WhatsApp Web chatbot using Node.js! This bot can send messages automatically and even handle incoming messages. For more advanced use cases, explore the whatsapp-web.js
library’s documentation.
By following these steps, you can easily automate repetitive tasks and improve productivity.