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
Top comments (1)
When I copy and paste the script, I receive an error message, even though I have installed all the dependencies correctly.
ERROR MESSAGE
npm run start
npm ERR! Missing script: "start"
npm ERR!
npm ERR! Did you mean one of these?
npm ERR! npm star # Mark your favorite packages
npm ERR! npm stars # View packages marked as favorites
npm ERR!
npm ERR! To see a list of scripts, run:
npm ERR! npm run
npm ERR! A complete log of this run can be found in:
npm ERR! /home/runner/.npm/_logs/2023-07-31T13_47_50_155Z-debug-0.log
exit status 1
îș§