javascript 如何在whatsap-web.js中发送whatsapp消息

cs7cruho  于 2023-03-06  发布在  Java
关注(0)|答案(5)|浏览(375)

我正在使用whatsapp-web.js发送和回复消息。https://github.com/pedroslopez/whatsapp-web.js
我可以使用以下代码连接并回复消息:

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();

如何在WhatsApp中向移动的号码发送新消息??

lg40wkob

lg40wkob1#

因此,您希望使用whatsap-web.js直接向移动的号码发送消息

幸运的是whatsap-web.js允许我们这么做,你可以简单地按照说明操作。

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

你想怎么用就怎么用。

vh0rcniy

vh0rcniy2#

下面是我在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");
}


更新(对于仅在异步错误内部有效的await):

  • 如果在任何情况下使用此方法,则应将其放在异步函数中 *
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");
    }
});
pzfprimi

pzfprimi3#

首先确认该号码是在WhatsApp注册的,如果是真的,则只使用sendMessage方法发送消息。
以下是工作代码-

client.isRegisteredUser("911234567890@c.us").then(function(isRegistered) {
    if(isRegistered) {
        client.sendMessage("911234567890@c.us", "hello");
    }
})
nimxete2

nimxete24#

我的代码

//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);
});
gkl3eglg

gkl3eglg5#

如果您有联系人名称,您可以通过获取所有联系人并通过namepushname找到正确的联系人,从而避免手动创建chatId并从联系人对象中获取它。

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')

相关问题