WhatsApp is one of the most widely used messaging platforms globally. While WhatsApp Web allows users to access their chats from a web browser, using Node.js and the whatsapp-web.js library provides a powerful way to automate sending messages programmatically. In this article, we’ll explore how to send messages on WhatsApp using Node.js and whatsapp-web.js.
Prerequisites:
Before we begin, ensure you have the following installed:
- Node.js: Download and install Node.js from https://nodejs.org/
- npm: npm is the package manager for Node.js and comes bundled with the Node.js installation.
Whatsapp-web.js
Whatsapp-web.js is a Node.js library designed for automating interactions with WhatsApp Web. It provides a programmatic interface for sending and receiving messages, handling events, and supporting various media formats. Leveraging the library’s capabilities, developers can build applications, bots, or workflows that interact with WhatsApp, though it’s crucial to use such automation responsibly, adhering to WhatsApp’s terms of service and legal standards. The library utilizes QR code authentication for session initiation and is actively maintained by the open-source community.
Setting Up Your Project:
Create a new directory for your project:
mkdir whatsapp-automation
cd whatsapp-automation
Initialize a new Node.js project:
npm init -y
Install the required packages:
npm install whatsapp-web.js
Using whatsapp-web.js:
Now, let’s create a simple script to send a message using whatsapp-web.js.
Create a new file, e.g., sendWhatsappMessage.js
, and open it in your preferred code editor.
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
// Initialize the WhatsApp client
const client = new Client();
// Event: QR Code generated
client.on('qr', (qrCode) => {
qrcode.generate(qrCode, { small: true });
});
// Event: Authentication successful
client.on('authenticated', (session) => {
console.log('Authenticated');
// Save the session data for later use
// You can store the session in a database or file
});
// Event: Ready to use
client.on('ready', () => {
console.log('WhatsApp Client is ready!');
sendMessage();
});
// Event: Message received
client.on('message', (message) => {
// Handle incoming messages if needed
});
// Event: Disconnected
client.on('disconnected', (reason) => {
console.log('Disconnected:', reason);
});
// Start the WhatsApp client
client.initialize();
// Function to send a message
async function sendMessage() {
const chatId = '[email protected]'; // Replace with the recipient's phone number
const message = 'Hello, this is a test message!';
// Get the chat
const chat = await client.getChatById(chatId);
// Send the message
chat.sendMessage(message).then((msg) => {
console.log('Message sent successfully:', msg.body);
client.destroy(); // Disconnect the client after sending the message
});
}
Replace '[email protected]'
with the actual phone number of the recipient, including the country code. Note that @c.us
is a required suffix for individual chats.
Running the Script:
Execute the script using the following command:
node sendWhatsappMessage.js
This will initiate the WhatsApp client, and a QR code will be generated. Scan the QR code using the WhatsApp app on your phone to authenticate the script.
Once authenticated, the script will send the specified message to the provided phone number.
Conclusion:
Automating WhatsApp messaging using Node.js and whatsapp-web.js opens up possibilities for various applications, such as notifications, reminders, and more. Keep in mind that automating messaging services should be done responsibly and within the bounds of their terms of service to avoid any issues.
Sample code to send Video, Pdf, Audio or Images to Whatsapp Members using NodeJs
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
const fs = require('fs');
// Initialize the WhatsApp client
const client = new Client();
// Event: QR Code generated
client.on('qr', (qrCode) => {
qrcode.generate(qrCode, { small: true });
});
// Event: Authentication successful
client.on('authenticated', (session) => {
console.log('Authenticated');
// Save the session data for later use
// You can store the session in a database or file
});
// Event: Ready to use
client.on('ready', () => {
console.log('WhatsApp Client is ready!');
sendMedia();
});
// Event: Message received
client.on('message', (message) => {
// Handle incoming messages if needed
});
// Event: Disconnected
client.on('disconnected', (reason) => {
console.log('Disconnected:', reason);
});
// Start the WhatsApp client
client.initialize();
// Function to send media
async function sendMedia() {
const chatId = '[email protected]'; // Replace with the recipient's phone number
const message = 'Hello, this is a media test message!';
// Get the chat
const chat = await client.getChatById(chatId);
// Send an image
const imagePath = 'path/to/your/image.jpg';
const imageBase64 = fs.readFileSync(imagePath, { encoding: 'base64' });
chat.sendImage(`data:image/jpeg;base64,${imageBase64}`, 'image.jpg', { caption: message });
// Send an audio file
const audioPath = 'path/to/your/audio.mp3';
const audioBase64 = fs.readFileSync(audioPath, { encoding: 'base64' });
chat.sendAudio(`data:audio/mp3;base64,${audioBase64}`, { caption: message });
// Send a video
const videoPath = 'path/to/your/video.mp4';
const videoBase64 = fs.readFileSync(videoPath, { encoding: 'base64' });
chat.sendVideo(`data:video/mp4;base64,${videoBase64}`, { caption: message });
// Send a PDF file
const pdfPath = 'path/to/your/document.pdf';
const pdfBase64 = fs.readFileSync(pdfPath, { encoding: 'base64' });
chat.sendDocument(`data:application/pdf;base64,${pdfBase64}`, { filename: 'document.pdf', caption: message });
console.log('Media sent successfully!');
client.destroy(); // Disconnect the client after sending the media
}
Disclaimer: The provided code and information are intended for educational purposes and personal experimentation only. Automated messaging on WhatsApp or any other platform may violate the terms of service, and users are advised to use such scripts responsibly, in compliance with applicable laws and regulations. The creator of this script assumes no responsibility for misuse, potential legal consequences, or any damages resulting from its use. Users are encouraged to review and adhere to the terms of service of the messaging platform and exercise caution to ensure responsible and ethical use of automation scripts.
Hi Mian, is it possible send PDF by URL and not by path local?
Yes, you can send a PDF file from any publicly accessible source.
Here is the method for sending media message from whatsapp for free!
app.post(‘/sendmessage’, async (req, res, next) => {
try {
// Log the incoming request body for debugging purposes
console.log(req.body);
// Destructure the incoming request body to get the number, message, and media URL
const { number, message, media } = req.body;
// Format the number with the country code for WhatsApp
const formattedNumber = `${number}@c.us`;
// Retrieve the WhatsApp ID for the provided number
const numberId = await client.getNumberId(formattedNumber);
if (numberId) {
console.log(‘The number exists on WhatsApp:’, numberId._serialized);
// Check if media URL is provided
if (media && media !== ”) {
// Fetch the media from the URL
const mediaContent = await MessageMedia.fromUrl(media);
// Send the message with media attachment
await client.sendMessage(formattedNumber, mediaContent, { caption: message });
} else {
// Send a text message if no media is provided
await client.sendMessage(formattedNumber, message);
}
// Respond to the client indicating the message was sent successfully
res.send(‘sent’);
} else {
// Respond indicating the number is not registered on WhatsApp
res.send(‘not-registered’);
console.log(‘The number does NOT exist on WhatsApp.’);
}
} catch (error) {
// Pass any errors to the next middleware for handling
next(error);
}
});