How to create whatsapp bot using javascript ?
Viral Vaghela
Posted on December 1, 2021
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
You will also require to install qrcode-terminal for generating QR Code. Install it using
$ npm i qrcode-terminal
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();
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);
});
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');
}
});
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);
}
});
});
Step 6) Downloading Media
client.on('message', async msg => {
if(msg.hasMedia) {
const media = await msg.downloadMedia();
// do something with the media data here
}
});
Step 7) Sending Media
const { MessageMedia } = require('whatsapp-web.js');
const media = new MessageMedia('image/png', base64Image);
chat.sendMessage(media);
I have created my own bot using this package
Click here to see my bot
Posted on December 1, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.