
To build a whatsapp bot we will be usingwhatsapp-web.js
Step 1) Create a project
Run following commands
$npmiwhatsapp-web.js
You will also require to installqrcode-terminal for generating QR Code. Install it using
$npmiqrcode-terminal
Step 2) Create index.js
Add following code
constqrcode=require('qrcode-terminal');const{Client}=require('whatsapp-web.js');constclient=newClient();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
constfs=require('fs');const{Client}=require('whatsapp-web.js');// Path where the session data will be storedconstSESSION_FILE_PATH='./session.json';// Load the session data if it has been previously savedletsessionData;if(fs.existsSync(SESSION_FILE_PATH)){sessionData=require(SESSION_FILE_PATH);}// Use the saved valuesconstclient=newClient({session:sessionData});// Save session values to the file upon successful authclient.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',asyncmsg=>{if(msg.hasMedia){constmedia=awaitmsg.downloadMedia();// do something with the media data here}});
Step 7) Sending Media
const{MessageMedia}=require('whatsapp-web.js');constmedia=newMessageMedia('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
For further actions, you may consider blocking this person and/orreporting abuse