18

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??

Hello World
  • 2,673
  • 7
  • 28
  • 60

5 Answers5

22

So, you want to send a message to mobile number directly using whatsapp-web.js

Fortunately whatsapp-web.js allow us to do that. Simply you can follow the instruction.

client.on('ready', () => {
 console.log('Client is ready!');

  // Number where you want to send the message.
 const number = "+911234567890";

  // Your message.
 const text = "Hey john";

  // Getting chatId from the number.
  // we have to delete "+" from the beginning and add "@c.us" at the end of the number.
 const chatId = number.substring(1) + "@c.us";

 // Sending message.
 client.sendMessage(chatId, text);
});

use it as you wish.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Subham Panja
  • 221
  • 1
  • 6
13

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");
    }
});

Hello World
  • 2,673
  • 7
  • 28
  • 60
6

First confirm the number is registered with WhatsApp and if true then only use sendMessage method to deliver message.

Following is working code -

client.isRegisteredUser("911234567890@c.us").then(function(isRegistered) {
    if(isRegistered) {
        client.sendMessage("911234567890@c.us", "hello");
    }
})  
Prabhu
  • 178
  • 2
  • 12
5

My code

//Documentacao https://docs.wwebjs.dev/ 
const qrcode = require('qrcode-terminal');
const { Client, LocalAuth } = require('whatsapp-web.js');

//Read QRcode only one time
const client = new Client({
    authStrategy: new LocalAuth(),
    puppeteer: {
      handleSIGINT: false,
      args: [
          '--no-sandbox',
          '--disable-setuid-sandbox'
      ] }
  });
 

client.on('qr', qr => {
    qrcode.generate(qr, {small: true});
});

client.on('ready', () => {
    console.log('Client is ready!');

    // Number and Text.
    var number = "+55.11.9.8888.9999";
    var text = "Hi!";

    //Cleaning to only numbers
    number = number.replace(/\D/g, "");
    //console.log(number);

    //Remove Contry Code (Brazil 55) to make it more simple
    if (Array.from(number)[0] == "5" && Array.from(number)[1] == "5" && number.length >11) {
        number=number.substring(2);
        //console.log(number);
    } else {
        number=number;
        //console.log(number);
    }

    //Removing 0 from beggin (In Brazil old people put that)
    if (Array.from(number)[0] == "0") {
        number=number.substring(1);
        //console.log(number);
    } else {
        number=number;
        //console.log(number);
    }

    //Creating two numbers (In Brazil we change recentily to 11 digits, put one 9 more) 
    var number2="";
    if (number && /^\d{11,}$/.test(number.trim())) {
        //console.log('Tem 11');
        number2=number.slice(0,2)+number.slice(3);
        //console.log(number2);
    } else if (number && /^\d{10,}$/.test(number.trim())) {
        //console.log('Tem 10');
        number2=number.slice(0,2)+"9"+number.slice(2);
        //console.log(number2);
    } else {
        console.log('Não Tem 11 ou 10');
    }

    //Add Brazil code (55) and whatsapp ending
    number="55"+number+"@c.us";
    number2="55"+number2+"@c.us";
    //console.log(number);
    //console.log(number2);
    var number_array = [number,number2]
    number_array.forEach(element => console.log(element));

    // Sending message.
    function senf_numeber (number,text) {
        client.isRegisteredUser(number).then(function(isRegistered) {
            if(isRegistered) {
                console.log(number+' Registrado');
                client.sendMessage(number, (text+" "+number));
            }else{
                console.log(number+' Não Registrado');
            }
        })
    }  
    number_array.forEach(element => senf_numeber (element,text));
});


//teste if script is working. User send !ping e script return pong
client.on('message', msg => {
    if (msg.body == '!ping') {
        msg.reply('pong');
    }
});

client.initialize();

//Closing correcily using CTRL+C 
process.on('SIGINT', async () => {
    console.log('(SIGINT) Shutting down...');
    await client.destroy();
    console.log('client destroyed');
    process.exit(0);
});
3

If you have contact name, you can avoid creating chatId manually and take it from contact object, by fetching all contacts and find right one by name or pushname.


  const contacts = await client.getContacts()
  const contact = contacts.find(({ name }) => name === CONTACT_DISPLAY_NAME)
  const { id: { _serialized: chatId } } = contact

  await client.sendMessage(chatId, 'Message Text')
bFunc
  • 1,370
  • 1
  • 12
  • 22