How to create whatsapp bot using javascript ?

viralvaghela

Viral Vaghela

Posted on December 1, 2021

How to create whatsapp bot using javascript ?

To build a whatsapp bot we will be using whatsapp-web.js

Step 1) Create a project
Run following commands

$ npm i whatsapp-web.js
Enter fullscreen mode Exit fullscreen mode

You will also require to install qrcode-terminal for generating QR Code. Install it using

$ npm i qrcode-terminal
Enter fullscreen mode Exit fullscreen mode

Step 2) Create index.js

Add following code

const qrcode = require('qrcode-terminal');

const { Client } = require('whatsapp-web.js');
const client = new Client();

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

First it will Display QR code,
you can scan in your whats app -> Linked devices and add new device

After Sucessfully Scan you should get message
"Client is ready!"

Step 3) Listen to Messages

client.on('message', message => {
    console.log(message.body);
});
Enter fullscreen mode Exit fullscreen mode

Inside on message call back you will get message object and listen to specific message like this

client.on('message', message => {
    if(message.body === '!ping') {
        message.reply('pong');
    }
});
Enter fullscreen mode Exit fullscreen mode

Step 4) Saving session
One proble you will face is ,you have to scan QR Code every time.

So for that you can store your session in .json file and when it will start app ,first it will check that is already authenticated or not, and if its authenticated
then continue using previous session.

So first we have to import 'fs' for creating a .json file

const fs = require('fs');
const { Client } = require('whatsapp-web.js');

// Path where the session data will be stored
const SESSION_FILE_PATH = './session.json';

// Load the session data if it has been previously saved
let sessionData;
if(fs.existsSync(SESSION_FILE_PATH)) {
    sessionData = require(SESSION_FILE_PATH);
}

// Use the saved values
const client = new Client({
    session: sessionData
});

// Save session values to the file upon successful auth
client.on('authenticated', (session) => {
    sessionData = session;
    fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), (err) => {
        if (err) {
            console.error(err);
        }
    });
});
Enter fullscreen mode Exit fullscreen mode

Step 6) Downloading Media

client.on('message', async msg => {
    if(msg.hasMedia) {
        const media = await msg.downloadMedia();
        // do something with the media data here
    }
});
Enter fullscreen mode Exit fullscreen mode

Step 7) Sending Media

const { MessageMedia } = require('whatsapp-web.js');

const media = new MessageMedia('image/png', base64Image);
chat.sendMessage(media);
Enter fullscreen mode Exit fullscreen mode

I have created my own bot using this package
Click here to see my bot

💖 💪 🙅 🚩
viralvaghela
Viral Vaghela

Posted on December 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related