DEV Community

Cover image for How to Create a WhatsApp Bot in Node.js
Yaasiin Ayeva
Yaasiin Ayeva

Posted on

How to Create a WhatsApp Bot in Node.js

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
Enter fullscreen mode Exit fullscreen mode

Initialize a new Node.js project:

npm init -y
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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');
Enter fullscreen mode Exit fullscreen mode

Next, let's initialize the WhatsApp client:

const client = new Client();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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');
    }
});
Enter fullscreen mode Exit fullscreen mode

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.');
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.');
    }
});
Enter fullscreen mode Exit fullscreen mode

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);
    }
});
Enter fullscreen mode Exit fullscreen mode

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' });
    }
});
Enter fullscreen mode Exit fullscreen mode

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.');
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

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.');
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
dchuquilla profile image
Dario Chuquilla

Nice tutorial buddy, but please let us know how you patched the security bleach about the puppeteer-core library.

Collapse
 
yaasiin-ayeva profile image
Yaasiin Ayeva

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:

  • configure Puppeteer with secure options (--no-sandbox, headless: true).
  • Run the project in an isolated environment, such as Docker, to minimize the impact of vulnerabilities.
  • Always keep Puppeteer-core and whatsapp-web.js updated to benefit from the latest security patches.
  • As a bonus you can use tools like Snyk to identify and fix vulnerabilities in dependencies.

Glad you liked the tutorial bro ! ๐Ÿ˜Š