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.
Your comment is awaiting moderation.
Hello
I wanted to offer my help in improving your site’s online visibility.
If you feel there are areas of your site that could benefit from optimization.
I provide tailored SEO services designed to drive more traffic and enhance performance.
Would you be interested in an SEO audit or any other improvements for your site?
Let me know if you’d like to chat more!
Thanks,
Jamila Frith
Italy, MO, Monteortore, 41059, Piazza Bovio 114
To stop any further communication through your website form, Please reply with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
I wanted to offer my help in improving your site’s online visibility.
If you feel there are areas of your site that could benefit from optimization.
I provide tailored SEO services designed to drive more traffic and enhance performance.
Would you be interested in an SEO audit or any other improvements for your site?
Let me know if you’d like to chat more!
Thanks,
Kit Neff
Australia, QLD, Southtown, 4350, 54 Hunter Street
To stop any further communication through your website form, Please reply with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
At Your SEO & Digital Marketing Partner, we offer complete SEO and promotion solutions designed to enhance your visibility, traffic, and sales:
– Google Maps Ranking – Rank higher in local search results.
– YouTube Ranking – Increase your video visibility and audience.
– SEO Backlinks – Gain authority and climb up in Google rankings.
– Website Traffic – Real, targeted, and relevant traffic.
– Content Creation – Optimized articles to drive more organic traffic.
– Social Media Manager – Manage and grow your social media networks for a stronger brand presence.
We provide personalized strategies and ongoing support to help you achieve visible, long-term, and measurable results!
If you are interested in these services, please reply to this email and we will discuss how we can help you achieve your online goals.
Best regards,
Your SEO & Digital Marketing Expert
France, CENTRE, Hazebrouck, 59190, 82 Avenue Des Tuileries
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
Are you looking to rank higher, get more traffic, and turn visitors into paying customers?
We help businesses like yours grow through powerful and results-driven digital marketing services, including:
– Google Ranking Optimization
– Google Maps Ranking
– YouTube Video Ranking
– SEO Backlinks & Link Diversity
– Website Traffic Campaigns
– High-Quality Content Creation
– Professional Video Production
– Social Media Manager (all major platforms)
– Lead Generation (Get Customers)
– White-Label SEO for Agencies
Whether you’re just starting out or looking to scale, we offer custom SEO plans and hands-on support all focused on helping you achieve visible, lasting results.
Simply reply to this email and we’ll recommend the best package for your goals.
Best regards,
Your SEO & Digital Marketing Expert
Italy, BL, Belluno, 32100, Corso Alcide De Gasperi 80
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
Are you looking to rank higher, get more traffic, and turn visitors into paying customers?
We help businesses like yours grow through powerful and results-driven digital marketing services, including:
– Google Ranking Optimization
– Google Maps Ranking
– YouTube Video Ranking
– SEO Backlinks & Link Diversity
– Website Traffic Campaigns
– High-Quality Content Creation
– Professional Video Production
– Social Media Manager (all major platforms)
– Lead Generation (Get Customers)
– White-Label SEO for Agencies
Whether you’re just starting out or looking to scale, we offer custom SEO plans and hands-on support all focused on helping you achieve visible, lasting results.
Simply reply to this email and we’ll recommend the best package for your goals.
Best regards,
Your SEO & Digital Marketing Expert
Brazil, SP, Americana, 13470-420, Rua Serra Do Parima 1730
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
Would you like to rank higher, increase website visitors, and turn visitors into paying customers?
Our team helps businesses like yours expand through powerful digital marketing services, including:
– Google Ranking Optimization
– Google Maps Ranking
– YouTube Video Ranking
– Authority Link Building
– Website Traffic Campaigns
– High-Quality Content Creation
– Engaging Video Content
– Social Media Manager (all major platforms)
– Targeted Lead Acquisition
– White-Label SEO for Agencies
Whether you’re just starting out or looking to scale, we offer tailored SEO plans and hands-on support — all focused on helping you achieve long-term success.
Reply today and we’ll recommend the best package for your goals.
Best regards,
Your SEO & Digital Marketing Expert
Germany, SH, Aumuhle, 21517, Chausseestr. 71
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
Would you like to rank higher, get more traffic, and turn visitors into paying customers?
Our team helps businesses like yours expand through results-driven digital marketing services, including:
– Search Engine Ranking Boost
– Google Maps Ranking
– YouTube Video Ranking
– Authority Link Building
– Website Traffic Campaigns
– SEO-Optimized Articles
– Engaging Video Content
– Social Media Manager (all major platforms)
– Targeted Lead Acquisition
– White-Label SEO for Agencies
For businesses just beginning or wanting to expand, we offer tailored SEO plans and dedicated guidance — all focused on delivering visible, lasting results.
Reply today and we’ll guide you toward the right package.
Best regards,
Your SEO & Digital Marketing Expert
Netherlands, ZH, Dordrecht, 3319 Hg, Jasmijnstraat 195
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com
Your comment is awaiting moderation.
Hello
This message is intended for the owner of codingshiksha.com. If you are not the person responsible for running the site, please forward this email to the right contact.
Our agency that provides professional SEO services. We can help your website improve its rankings and increase your leads. Here are some of the services we offer:
– Search Engine Ranking Boost
– Google Maps Ranking
– YouTube SEO
– SEO Backlinks & Link Diversity
– Website Traffic Campaigns
– High-Quality Content Creation
– Engaging Video Content
– Social Media Manager (all major platforms)
– Targeted Lead Acquisition
– SEO Outsourcing Solutions
If you are the decision maker, we would be pleased to provide more details and discuss how we can assist your business in achieving greater digital growth and customer growth.
Just get back to us and we’ll suggest the ideal SEO plan for your needs.
Best regards,
Your SEO & Digital Marketing Expert
Norway, NA, Mandal, 4513, Monestoppen 130
To stop any further communication from us, please reply to this email with subject: Unsubscribe !codingshiksha.com