I am using whatsapp-web.js
to send and reply message. https://github.com/pedroslopez/whatsapp-web.js
I can connect and reply message using following code:
const { Client } = require('whatsapp-web.js');
const client = new Client();
client.on('qr', (qr) => {
// Generate and scan this code with your phone
console.log('QR RECEIVED', qr);
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.on('message', msg => {
if (msg.body == '!ping') {
msg.reply('pong');
}
});
client.initialize();
how can I send new message in whatsapp to mobile number??
Here is how I send messages in whatsapp-web.js
.
const number = "9830121234";
const sanitized_number = number.toString().replace(/[- )(]/g, ""); // remove unnecessary chars from the number
const final_number = `91${sanitized_number.substring(sanitized_number.length - 10)}`; // add 91 before the number here 91 is country code of India
const number_details = await client.getNumberId(final_number); // get mobile number details
if (number_details) {
const sendMessageData = await client.sendMessage(number_details._serialized, sendData.message); // send message
} else {
console.log(final_number, "Mobile number is not registered");
}
.
.
update (for await is valid inside only async error):
if you are using this method in any event you should put it inside an async function
on.any_kind_of_event(async function () {
const number = "9830121234";
const sanitized_number = number.toString().replace(/[- )(]/g, ""); // remove unnecessary chars from the number
const final_number = `91${sanitized_number.substring(sanitized_number.length - 10)}`; // add 91 before the number here 91 is country code of India
const number_details = await client.getNumberId(final_number); // get mobile number details
if (number_details) {
const sendMessageData = await client.sendMessage(number_details._serialized, sendData.message); // send message
} else {
console.log(final_number, "Mobile number is not registered");
}
});