Prerequisites:
- Node.Js installed in your machine.
- A WhatsApp account with WhatsApp Web related.
Step 1: Set Up a New Node.Js Project
Create a new project and initialize it as a Node.Js:
mkdir whatsapp-bot
cd whatsapp-bot
npm init -y
Step 2: Install Required Libraries
You'll need the following libraries:
- qrcode-terminal: To display the QR code for WhatsApp Web authentication.
- Whatsapp-web.Js: A library for interacting with WhatsApp Web.
- express: To create a simple net server for receiving incoming messages.
Install those libraries using npm:
npm install qrcode-terminal whatsapp-web.Js express
Step 3: Create Your WhatsApp Bot
Create a JavaScript report, e.g., whatsapp-bot.Js, and upload the following code to set up your WhatsApp bot:
const qrcode = require('qrcode-terminal');
const { Client } = require('whatsapp-web.js');
const express = require('express');
const app = express();
const port = 8080;
app.use(express.json());
const client = new Client();
client.on('qr', (qr) => {
qrcode.generate(qr, { small: true });
console.log('Scan the QR code above to log in.');
});
client.on('ready', () => {
console.log('WhatsApp bot is ready!');
});
client.on('message', (message) => {
// Implement your message handling logic here
if (message.body === 'Hello') {
message.reply('Hello, I am your WhatsApp bot!');
}
});
client.initialize();
app.post('/send-message', (req, res) => {
const { number, message } = req.body;
client.sendMessage(number, message).then(() => {
res.status(200).json({ message: 'Message sent successfully' });
}).catch((err) => {
res.status(500).json({ error: err.message });
});
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 4: Run Your WhatsApp Bot
Run your bot the use of the following command:
node whatsapp-bot.Js
This will start your Express.Js server on port 8080. The bot will display a QR code inside the terminal. Scan the QR code the usage of your WhatsApp cellular app to log in.
Step 5: Interact with Your Bot
You can ship a POST request in your Express.Js server to ship messages out of your bot:
curl -X POST http://localhost:8080/send-message -H "Content-Type: application/json" -d '{"number": "RECIPIENT_PHONE_NUMBER", "message": "Hello from my WhatsApp bot!"}'
Replace RECIPIENT_PHONE_NUMBER with the recipient's smartphone number.
Your bot will automatically reply with "Hello, I am your WhatsApp bot!" when it gets a "Hello" message.
This is a primary example of putting in place a WhatsApp Web bot with JavaScript and Express.Js. You can expand it to handle greater complicated common sense and commands as needed.