whatssap-web.js: Problem when the client session id is usend for second time

Viewed 15

I'm usign this https://wwebjs.dev/guide/#installation to send messajes via whatsapp but:

(Any idea to solve the problem with what the whatsapp-web.js module give us ?)

In my application the login with "authStrategy: new LocalAuth({ clientId: clientId })," where I successfully generate the connection, but once it is "authenticated" and "ready" I must execute "client.destroy( )", to be able to create a new client later with that same session, that is, with the same "clientId". now if I want to send a picture message the first time it works perfectly but the second time it doesn't work anymore, the application freezes, specifically in the "122 -> needAuthentication promise", if I added the authTimeoutMs variable: 120000 (2 minutes) or whatever time it is , at the end of this time the error will be executed: "TimeoutError: waiting for selector [data-testid="intro-md-beta-logo-dark"], [data-testid="intro-md-beta-logo-light"], [data-asset-intro-image-light="true"], [data-asset-intro-image-dark="true"] failed: timeout 180000ms exceeded".

I tried to solve the error by adding the "client.destroy" after sending the message to be able to use the client without problems, but it seems that this "destroy" cancels the sending of the message and it never reaches its destination.

Expected behavior:

that messages with media are sent in different calls to the api from the same clientId

Steps to Reproduce the Bug or Issue:

  1. make a post request to connect.js code with whatever body.clientId ex:12345 , to generate the QR and authenticate with your whatsapp account.

(for the following steps change the variable of line 5 called "number" for a number to perform the test)

  1. make a post request to sendMessage.js code with the same body.clientId in the step 1, to send the message (from postman or something like that)
  2. make a post request to sendMessage.js code with the same body.clientId in the step 1 again, to send the message again (in this time the app freezes or throw an error if you configure the authTimeoutMs option).

usign client.destroy(); on finish each req.

  1. to check the client.destroy problem (that cancels the sending messsages) only uncomment the line 21 // client.destroy() in sendMessages.js file

Relevant Code:

connect.js:

    // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
    const { Client, LocalAuth } = require('whatsapp-web.js');
    const qrcode = require('qrcode-terminal');
    export default function handler(req, res) {
      const { body: { clientId } } = req;
    
      const client = new Client({
        authStrategy: new LocalAuth({ clientId }),    
      });
    
      client.on('qr', (qr) => {
        console.log('QR RECEIVED', qr);
        qrcode.generate(qr, { small: true });
      });
    
      client.on('ready', () => {
        console.log('Client is ready!');
        client.destroy();
      });
    
      client.initialize();
    
      res.status(200).send({ response: "melo", clientId });
    }

sendMessage.js:

// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');

export default async function handler(req, res) {
    const number = "PUT A VALID WHATSAPP NUMBER TO THE TEST HERE";
    const { body: { clientId } } = req;
    try {
        let client = new Client({
            authStrategy: new LocalAuth({ clientId }),
        });

        client.on("ready", async () => {
            console.log("READY-------------------->");
            const media = await MessageMedia.fromUrl('https://via.placeholder.com/350x150.png');

            const response = await client.sendMessage(`${number}@c.us`, media, {
                caption: "image test andresmv94"
            });
            console.log(response.id.remote);
            // client.destroy();
            
        });

        await client.initialize().then((r) => r).catch((er) => console.log(er));

    } catch (error) {
        console.log(error);
    }

    res.status(200).send({ response: "done", clientId });
}

Additional context:

I also tried putting it inside .then() but it doesn't work either:

    const response = await client.sendMessage(`${number}@c.us`, media, {
        caption: "image test andresmv94"
    }).then((res) => {      
          client.destroy();
    });

The only method I found to avoid the problem in step 3 and 4 was to add the destroy inside a setTimeout, but it is not very reliable if the message takes longer than that to send.

const response = await client.sendMessage(`${number}@c.us`, media, {
                caption: "image test andresmv94"
            }).then((res) => {              
                setTimeout(() => {
                  client.destroy();
                }, 60000);
            });

Any idea to solve the problem with what the whatsapp-web.js module give us ?

0 Answers
Related