Hi there ! In this tutorial, we'll learn how to create a WhatsApp bot using Node.js
. This bot will allow you to automate tasks on WhatsApp, such as responding to messages, sending media, and managing groups.
1. Introduction
A full example of an open-source project using the method outlined in this tutorial is publicly available on GitHub. Feel free to contribute!
Before we begin, let's see what we'll need for this project.
Prerequisites
Make sure you have:
- Node.js (version 18 or higher) installed on your machine
- npm (usually installed with Node.js)
- An active WhatsApp account
- Basic knowledge of JavaScript and Node.js
2. Installation and Configuration
If you don't have Node.js and npm yet, Go to the official Node.js website. Download the recommended version and follow the installation instructions.
Creating the project
Create a new folder for your project and navigate into it
mkdir whatsapp-bot
cd whatsapp-bot
Initialize a new Node.js project:
npm init -y
This command will create a package.json
file with default configurations.
Installing Whatsapp-web.js and its Dependencies
Now, let's install Whatsapp-web.js and its dependencies:
npm install whatsapp-web.js qrcode-terminal
-
whatsapp-web.js
is the main library we'll use to interact with WhatsApp. -
qrcode-terminal
will help us display the QR code for authentication in the terminal.
Your development environment is now ready to start coding your WhatsApp bot!
3. Setting Up the Bot
Now that our environment is configured, let's create our WhatsApp bot.
Let's start by importing required modules. Create a file named bot.js
in the root of your project and start by importing the necessary modules:
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
Next, let's initialize the WhatsApp client:
const client = new Client();
Once the Client is created, we need to expose the QR code and allow your client to authenticate and connect to whatsapp web.
To do so, we need to add a couple lines of code
client.on('qr', (qr) => {
qrcode.generate(qr, {small: true});
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.initialize();
This code generates a QR code in the terminal that you'll need to scan with the WhatsApp app on your phone to authenticate the bot.
4. Basic Bot Functionalities
Now that our bot is connected, let's add some basic functionalities.
Listening for Incoming Messages
To listen for incoming messages, use the message
event:
client.on('message', message => {
console.log(message.body);
});
Responding to Simple Messages
Let's add a simple response to a specific message
client.on('message', message => {
if(message.body === '!ping') {
message.reply('pong');
}
});
Handling Basic Commands
Let's create a function to handle different commands:
client.on('message', async (message) => {
if (message.body.startsWith('!')) {
const command = message.body.slice(1).split(' ')[0];
const args = message.body.slice(1).split(' ').slice(1);
switch(command) {
case 'ping':
await message.reply('pong');
break;
case 'hello':
await message.reply('Hello! How can I help you?');
break;
case 'info':
await message.reply(`Your number is: ${message.from}\nYou sent: ${args.join(' ')}`);
break;
default:
await message.reply('Unrecognized command. Try !ping, !hello, or !info.');
}
}
});
This function allows handling multiple commands like !ping
, !hello
, and !info
.
To run your bot, use the following command in your terminal:
node bot.js
Scan the QR code that appears with the WhatsApp app on your phone, and your bot will be operational!ππ
5. Advanced Features
In this section, we'll explore more advanced features of our WhatsApp bot, such as sending messages to specific contacts, sending media, and managing groups.
Sending Messages to Specific Contacts
To send a message to a specific contact, you can use the sendMessage
method. Add this function to your bot.js
:
async function sendMessageToContact(number, message) {
const chatId = number.includes('@c.us') ? number : `${number}@c.us`;
await client.sendMessage(chatId, message);
}
// Example usage
client.on('message', async (message) => {
if (message.body === '!send') {
await sendMessageToContact('1234567890@c.us', 'Hello from the bot!');
message.reply('Message sent to the specified contact.');
}
});
Sending Media (Images, Videos, Documents)
Whatsapp-web.js also allows sending different types of media. Here's how to send an image:
const fs = require('fs');
const { MessageMedia } = require('whatsapp-web.js');
client.on('message', async (message) => {
if (message.body === '!image') {
const media = MessageMedia.fromFilePath('./image.jpg');
await message.reply(media);
}
});
To send a document:
client.on('message', async (message) => {
if (message.body === '!document') {
const media = MessageMedia.fromFilePath('./document.pdf');
await message.reply(media, undefined, { caption: 'Here is the requested document' });
}
});
Creating Groups and Managing Members
Here's how to create a group and add participants:
async function createGroup(name, participants) {
const group = await client.createGroup(name, participants);
return group;
}
client.on('message', async (message) => {
if (message.body.startsWith('!creategroup')) {
const groupName = message.body.split(' ').slice(1).join(' ');
const participants = ['1234567890@c.us', '0987654321@c.us'];
try {
const group = await createGroup(groupName, participants);
message.reply(`Group "${groupName}" created successfully!`);
} catch (error) {
console.error('Error creating group:', error);
message.reply('Sorry, I couldn\'t create the group.');
}
}
});
To add or remove participants from an existing group:
client.on('message', async (message) => {
if (message.body.startsWith('!addtogroup')) {
const chatId = message.body.split(' ')[1];
const participantNumber = message.body.split(' ')[2];
try {
const chat = await message.getChat();
if (chat.isGroup) {
await chat.addParticipants([`${participantNumber}@c.us`]);
message.reply('Participant added successfully!');
}
} catch (error) {
console.error('Error adding participant:', error);
message.reply('Sorry, I couldn\'t add the participant.');
}
}
});
These advanced features allow you to create a more sophisticated WhatsApp bot capable of more complex interactions with users and groups.
Usefull links & Ressources
- WhatsBot : open-source project for a practical implementation. Built with Node.js and TypeScript, running on Docker. It includes several cool features like AI integration for voice and text responses, video downloading, memes, and much more. Feel free to contribute!
- Guides & Docs for wweb.js
- Discord Community for wweb.js
Conclusion
In this tutorial, we've covered all the essential aspects of creating a WhatsApp bot using Whatsapp-web.js and Node.js
Iβm Yaasiin Ayeva, a Software Developer and DevOps Engineer with a solid background in backend technologies and automation. You can reach me here: yaasiin-dev.vercel.app.
Top comments (2)
Nice tutorial buddy, but please let us know how you patched the security bleach about the puppeteer-core library.
Thank you for your feedback, @dchuquilla ! Thatβs an interresting question. To address potential security issues with Puppeteer-core, hereβs what we can do:
Glad you liked the tutorial bro ! π