pedroslopez / whatsapp-web.js

A WhatsApp client library for NodeJS that connects through the WhatsApp Web browser app
https://wwebjs.dev
Apache License 2.0
15.62k stars 3.72k forks source link

๐Ÿ›๐Ÿ› session does not persist using LocalAuth id ๐Ÿ›๐Ÿ› #2164

Open andresmv94 opened 1 year ago

andresmv94 commented 1 year ago

Is there an existing issue for this?

Describe the bug

I have been using "whatsapp-web.js" in my application for about 6 months, and yesterday the session persistence stopped working, I am using authStrategy: new LocalAuth({ clientId: user._id }), and with this When I want to use the WhatsApp channel again, I can use it without having to scan the QR again, but every time that I want to use the channel and send messages, it is making me to scan the QR and this was not happening until yesterday

Expected behavior

for first time scan the QR once, and be able to continue using whatsapp without having to scan each time I use it

Steps to Reproduce the Bug or Issue

  1. configure the server in linux to work
  2. configure whatsapp web js with authStrategy: new LocalAuth({ clientId: "some-client-id" })
  3. scan the QR and send a message
  4. reuse sending messages with the same "some-client-id"

Relevant Code

function authWhatsapp (user) => {
    console.log("init authentication");
    const client = await new Client({
      authStrategy: new LocalAuth({ clientId: user._id }), // user = {_id: "1234abc", name: "juan"}
      qrMaxRetries: 3,
      authTimeoutMs: 60000,
      puppeteer: {
        executablePath: process.env.CHROME_EXECUTABLE_PATH, // CHROME_EXECUTABLE_PATH=/usr/bin/google-chrome-stable
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
      },
    }); 

    client.on("qr", async (qr) => {
        console.log("scan qr");
        console.log(qr);        

    });

     client.on("ready", async () => {
        console.log("Wapp web connected");
     });

}

function sendWhatsapp (user) => {
    console.log("try send messages");
    client = await new Client({
      authStrategy: new LocalAuth({ clientId: user._id }), // user = {_id: "1234abc", name: "juan"}
      authTimeoutMs: 60000,
      puppeteer: {
        executablePath: process.env.CHROME_EXECUTABLE_PATH,  // CHROME_EXECUTABLE_PATH=/usr/bin/google-chrome-stable
        args: ["--no-sandbox", "--disable-setuid-sandbox"],
      },
    });

     client.on("ready", async () => { // this is never executed ๐Ÿซค
        console.log("perfect, your are authenticated, Wapp web connected");
        /*
            code to send messages...
        */
     });

     client.on("qr", async (qr) => {

        console.log("The whatsapp is asking for QR you are not authenticated"); 
        console.log(qr);    

    });

}

for authWhatsapp function:

> init authentication
> scan qr
> 2@Zy5JBs9MeMX0GBeDlNd1....RUI9lbeATZGDNBtx52+29CIw=
> Wapp web connected

for sendWhatsapp function: 

> try send messages
> The whatsapp is asking for QR you are not authenticated
> 2@TYQbrQCmYVbCB0KG...dEy8edXIPh32AiME0=

Browser Type

Google Chrome

WhatsApp Account Type

Standard

Does your WhatsApp account have multidevice enabled?

Yes, I am using Multi Device

Environment

OS: Ubuntu 20
Phone OS:  Android, iOS
whatsapp-web.js version [1.19.5]
WhatsApp Web version [2.2317.10]:
Node.js Version [v19.8.1]

Additional context

remember: this was not happening until yesterday, I already tried setting all the permissions to the .wwebjs_auth folder, and to all its content, but it's still the same, I also notice that in windows (no server -> my personal computer) with exactly the same configuration but using CHROME_EXECUTABLE_PATH=C:/Program Files/Google/Chrome /Application/chrome.exe, it is working correctly, any idea why?

maybe the session files are not being saved correctly in the ".wwebjs_auth" folder, but I don't really know how to look at that part

Update: in other computer with Windows is happenig the same issue so is not the OS.

benjachiban commented 1 year ago

I am experiencing the same problem. I have been using it for a few weeks without a problem and since yesterday it has been disconnecting me often and it does not notify me why it happens. Anyone else with this error?

andresmv94 commented 1 year ago

The whatsapp version that whatsapp-web.js mark like "working with" is = WhatsApp_Web 2.2306.7, and Now the current WhatsApp Web version is 2.2317.10. maybe something with session was changed

I am experiencing the same problem. I have been using it for a few weeks without a problem and since yesterday it has been disconnecting me often and it does not notify me why it happens. Anyone else with this error?

benjachiban commented 1 year ago

The whatsapp version that whatsapp-web.js mark like "working with" is = WhatsApp_Web 2.2306.7, and Now the current WhatsApp Web version is 2.2317.10. maybe something with session was changed

I am experiencing the same problem. I have been using it for a few weeks without a problem and since yesterday it has been disconnecting me often and it does not notify me why it happens. Anyone else with this error?

Pudiste encontar solucion??

benjachiban commented 1 year ago

At first I found a solution, for now it's working. In the package.json inside node_modules/whatsapp-web... change the version of puppeteer to 18.1.0

andresmv94 commented 1 year ago

At first I found a solution, for now it's working. In the package.json inside node_modules/whatsapp-web... change the version of puppeteer to 18.1.0

Is weird because that works some times

RC047 commented 1 year ago

same here

samuelfaj commented 1 year ago

Same here

mahmouds12 commented 1 year ago

benjachiban

I tried it, didn't work

ch9ch9n commented 1 year ago

Same problem change the version of puppeteer to 18.1.0 dont work

andresmv94 commented 1 year ago

@pedroslopez , some idea about this?

Neotastisch commented 1 year ago

same here

akimabs commented 1 year ago

same here :(

lanstat commented 1 year ago

At first I found a solution, for now it's working. In the package.json inside node_modules/whatsapp-web... change the version of puppeteer to 18.1.0

It worked for me, update puppeteer to 20.3.0

XxQuickSilverZz commented 1 year ago

At first I found a solution, for now it's working. In the package.json inside node_modules/whatsapp-web... change the version of puppeteer to 18.1.0

It worked for me, update puppeteer to 20.3.0

Please fulls steps. I need a npm install then?

iAndreas commented 1 year ago

My puppeteer is on version 20.3.0 but the error persists.

XxQuickSilverZz commented 1 year ago

@pedroslopez Maybe your help?

Santosl2 commented 1 year ago

up

Davixe7 commented 1 year ago

UP, session persistence is super unconsistent.

longgtruong commented 1 year ago

same problem

daniloavilez commented 1 year ago

I had the same problem with session in another library, it seems this problem is related to some thing that Whatsapp changed. Maybe it's a false impression I've tested different libraries.

leandrosantoss commented 1 year ago

Hi, I resolved it with permission chmod on both .wwebjs_auth and .wwebjs_cache directories

regards

bryanfok commented 1 year ago

Hi, I resolved it with permission chmod on both .wwebjs_auth and .wwebjs_cache directories

regards chmod 777 .wwebjs_cache

still ask to scan qr code

Santosl2 commented 1 year ago

up again

mahmouds12 commented 1 year ago

still happening

amoyano commented 11 months ago

every restart localauth not working , and send new QR, any solution to this?

myanpetra99 commented 11 months ago

every restart localauth not working , and send new QR, any solution to this?

Have you tried the solutions mentioned above? Try updating Puppeteer to version 20.3.0 in Node_modules/whatsapp-web.js/package.json and then run 'npm update'. This worked for me.

bryanfok commented 10 months ago

This is how i fix this issue:

1/ make sure .wwebjs_auth is created after login, otherwise likely your code problem 2/ puppeteer is update 3/ make sure .wwebjs_auth is chmod 777

justoverclockl commented 10 months ago

why this is closed if actually not work?

alechkos commented 10 months ago

the solution is to wait a couple minutes after the first qr code scan to let the session be "populated" properly also as mentioned here the session is being saved in .wwebjs_auth, so make sure that folder is created properly

justoverclockl commented 10 months ago

I scan the qrcode, I get the qrcode, authentications is fineโ€ฆif after 2 hour I restart the server I need to rescan qrcode, so itโ€™s not a problem related to โ€œwait some minutesโ€

alechkos commented 10 months ago

@justoverclockl

3/ make sure .wwebjs_auth is chmod 777

Good luck

justoverclockl commented 10 months ago

i've managed this and seems to work but i get

ProtocolError: Waiting for selector `[data-icon='search']` failed: Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.
1|app       |     at <instance_members_initializer> (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:86:14)
1|app       |     at new Callback (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:90:16)
1|app       |     at CallbackRegistry.create (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:22:26)
1|app       |     at Connection._rawSend (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:80:26)
1|app       |     at CdpCDPSession.send (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:66:33)
1|app       |     at #evaluate (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:201:50)
1|app       |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1|app       |     at async ExecutionContext.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:168:16)
1|app       |     at async IsolatedWorld.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:115:16)
1|app       |     at async CdpJSHandle.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:150:20)
1|app       |     at async WaitTask.rerun (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:103:28)
amoyano commented 10 months ago

i've managed this and seems to work but i get

ProtocolError: Waiting for selector `[data-icon='search']` failed: Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.
1|app       |     at <instance_members_initializer> (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:86:14)
1|app       |     at new Callback (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:90:16)
1|app       |     at CallbackRegistry.create (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:22:26)
1|app       |     at Connection._rawSend (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:80:26)
1|app       |     at CdpCDPSession.send (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:66:33)
1|app       |     at #evaluate (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:201:50)
1|app       |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1|app       |     at async ExecutionContext.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:168:16)
1|app       |     at async IsolatedWorld.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:115:16)
1|app       |     at async CdpJSHandle.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:150:20)
1|app       |     at async WaitTask.rerun (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:103:28)

Check here https://github.com/pedroslopez/whatsapp-web.js/issues/2477

justoverclockl commented 10 months ago

@amoyano thx, done but not work, the session seems to be restored but after a while i get the above error

this happen also on clientState. after few seconds become null @alechkos


0|app  | ClientState:  CONNECTED
1|app  | ClientState:  null
1|app  | ClientState:  null

this is the complete log

0|app      | Server started on port 3030
0|app      | Connected to db
0|app      | Whatsapp Authenticated
0|app      | Client ready
0|app      | ClientState:  CONNECTED
0|app      | ClientState:  CONNECTED
0|app      | ClientState:  null
0|app      | ClientState:  null
0|app      | ClientState:  CONNECTED

1|app  | ClientState:  null
1|app  | You have triggered an unhandledRejection, you may have forgotten to catch a Promise rejection:
1|app  | ProtocolError: Waiting for selector `div[role='textbox']` failed: Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.
1|app  |     at <instance_members_initializer> (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:86:14)
1|app  |     at new Callback (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:90:16)
1|app  |     at CallbackRegistry.create (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:22:26)
1|app  |     at Connection._rawSend (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:80:26)
1|app  |     at CdpCDPSession.send (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:66:33)
1|app  |     at #evaluate (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:201:50)
1|app  |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
1|app  |     at async ExecutionContext.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:168:16)
1|app  |     at async IsolatedWorld.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:115:16)
1|app  |     at async CdpJSHandle.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:150:20)
1|app  |     at async WaitTask.rerun (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:103:28)
alechkos commented 10 months ago

@justoverclockl

thx, done

Did you just change to const INTRO_IMG_SELECTOR = '[data-icon="search"]' in your code as mentioned here? If so you are not using the latest library version and you should apply this:

npm i github:pedroslopez/whatsapp-web.js#main

Also provide the code where you are handling the client state changes

justoverclockl commented 10 months ago

i have github:pedroslopez/whatsapp-web.js#main @alechkos

const authStrategy = new LocalAuth({
  clientId: "adminSession"
});

const client = new Client({
  authStrategy,
  restartOnAuthFail: true,
  takeoverOnConflict: true,
  puppeteer: {
    headless: true,
    args: ["--no-sandbox"],
  }
});

client.initialize();

client.on("ready", () => {
  console.log("Client pronto");
});

client.on("authenticated", () => {
  console.log("Whatsapp ok");
});

client.on("disconnected", (reason) => {
  console.log("Disconnected:", reason);
});

router.get("/whatsapp/auth", async (req, res) => {
  const clientState = await client?.getState();
  console.log('ClientState: ', clientState)
  try {
    if (clientState === "CONNECTED") {
      return res.status(200).json({
        message: "Login ok."
      });
    } else {
      return res.status(200).json({
        message: "Scan qrcode."
      });
    }
  } catch (err) {
    res.status(404).send({
      error: "oops test error."
    });
  }
});
alechkos commented 10 months ago

@justoverclockl getState is probably broken, check #2125

justoverclockl commented 10 months ago

its not the only broken, i keep getting

ProtocolError: Waiting for selector `[data-icon="search"]` failed: Runtime.callFunctionOn timed out. Increase the 'protocolTimeout' setting in launch/connect calls for a higher timeout if needed.
0|app  |     at <instance_members_initializer> (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:86:14)
0|app  |     at new Callback (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:90:16)
0|app  |     at CallbackRegistry.create (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:22:26)
0|app  |     at Connection._rawSend (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:80:26)
0|app  |     at CdpCDPSession.send (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:66:33)
0|app  |     at #evaluate (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:201:50)
0|app  |     at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
0|app  |     at async ExecutionContext.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:168:16)
0|app  |     at async IsolatedWorld.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:115:16)
0|app  |     at async CdpJSHandle.evaluateHandle (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/api/JSHandle.js:150:20)
0|app  |     at async WaitTask.rerun (/var/www/node_modules/whatsapp-web.js/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WaitTask.js:103:28)

i've tried with [data-icon="search"] , i tried also const INTRO_IMG_SELECTOR = 'div[role=\'textbox\']';...but nothing...please do not close issues this fast....

josuelmm commented 10 months ago

Same error.. Any solution

tuke307 commented 10 months ago

same for me. the library appears to have problems with multiple projects.

I have two projects:

when the client init is in the library project it cant restore the session, even if i directly specify it.

gustavorps commented 10 months ago

+1

yairmelamed commented 10 months ago

WhatsApp-web.js suddenly logs out on restore session with no reason.. How to fix this?

justoverclockl commented 10 months ago

WhatsApp-web.js suddenly logs out on restore session with no reason.. How to fix this?

@yairmelamed we need to wait for a fix...

AgustinParraquini commented 10 months ago

same problem here!

mylmz10 commented 10 months ago

+1

justoverclockl commented 10 months ago

any news on that?

joaopaulopresa commented 9 months ago

same here

joaopaulopresa commented 9 months ago

At first I found a solution, for now it's working. In the package.json inside node_modules/whatsapp-web... change the version of puppeteer to 18.1.0

work for me, but some times fails

Avivbens commented 9 months ago

We really need some solution in here...

I'm willing to assist, just give me the details of the potential issue ๐Ÿ™

Avivbens commented 9 months ago

OK, I've managed to resolve the issue:

TL;DR Set the webVersion to 2.2306.7

NestJS provider

export const WhatsappClientProvider: Provider<Client> = {
    provide: WHATSAPP_CLIENT,
    inject: [ConfigService],
    useFactory: async (configService: ConfigService) => {
        const logger: Logger = new Logger('WHATSAPP_CLIENT')
        const env = configService.get<Envs>(EnvVariables.NODE_ENV, Envs.Production)
        const args = env === Envs.Production ? ['--no-sandbox', '--disable-setuid-sandbox'] : undefined

        const client = new Client({
            authStrategy: new LocalAuth(),
            webVersion: '2.2306.7', // this keeps the Whatsapp Verison with the latest version worked ๐Ÿ‘ 
            puppeteer: {
                args,
            },
        })

        client.once('qr', (qr) => {
            logger.debug('QR code received, scan please')
            return qrcode.generate(qr)
        })

        client.on('authenticated', () => {
            logger.debug('Authenticated successfully!')
        })

        client.on('disconnected', (reason) => {
            logger.error(`Disconnected, reason: ${reason}`)
        })

        const prm = new Promise<void>((resolve) =>
            client.on('ready', async () => {
                logger.debug('WhatsApp Client is ready!')
                resolve()
            }),
        )

        client.initialize()

        await prm
        return client
    },
}

Terminal Screenshot

CleanShot 2024-02-19 at 17 35 08