Whatsapp_Web_Node_Server/main.js

50 lines
1.3 KiB
JavaScript

const { Client } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const express = require('express');
const app = express();
app.use(express.json());
const wwebVersion = '2.2407.3';
// Create a new client instance
const client = new Client(
{webVersionCache: {
type: 'remote',
remotePath: `https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/${wwebVersion}.html`
}
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.on('qr', qr => {
qrcode.generate(qr, {small: true});
});
// Listening to all incoming messages
client.on('message_create', message => {
console.log(message.body);
});
function sendMessage(number, message) {
client.sendMessage(number, message);
}
app.post('/send-message', (req, res) => {
/*
This function only accepts numbers formatted as: [CountryCode][Number]@c.us // Example: 39333555887@c.us
*/
const { number, message } = req.body;
if (!number || !message) {
return res.status(400).send('Number and message are required');
}
sendMessage(number, message);
res.send('Message sent');
});
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on port ${port}`));
client.initialize();