WhiskeySockets / Baileys

Lightweight full-featured typescript/javascript WhatsApp Web API
https://baileys.whiskeysockets.io/
MIT License
3.17k stars 1.1k forks source link

[BUG] "stream errored out" while reading QR or just suddenly! #107

Closed iosahil closed 1 year ago

iosahil commented 1 year ago

When trying to create a session using:

const {state, saveCred} = await useHarperDB(botName)

const sock = makeWASocket.default({
    logger,
    printQRInTerminal: true,
    auth: {
        creds: state.creds,
        keys: makeCacheableSignalKeyStore(state.keys, logger)
    },
    msgRetryCounterCache,
    generateHighQualityLinkPreview: true
})

It gives the QR but when scanned, it raises an error:

[17:03:09.689] INFO (16624): pairing configured successfully, expect to restart the connection...
    me: {
      "id": "447700XXXXXX:24@s.whatsapp.net"
    }
    platform: "android"
[17:03:10.043] ERROR (16624): stream errored out
    node: {
      "tag": "stream:error",
      "attrs": {
        "code": "515"
      }
    }
[17:03:10.044] INFO (16624): connection errored
    trace: "Error: Stream Errored (restart required)\n    at WebSocket.<anonymous> (C:\Users\hey\IdeaProjects\benbecula\node_modules\@whiskeys
ockets\baileys\lib\Socket\socket.js:435:13)\n    at WebSocket.emit (node:events:513:28)\n    at C:\Users\hey\IdeaProjects\benbecula\node_modul
es\@whiskeysockets\baileys\lib\Socket\socket.js:233:35\n    at Object.decodeFrame (C:\Users\hey\IdeaProjects\benbecula\node_modules\@whiskeyso
ckets\baileys\lib\Utils\noise-handler.js:131:17)\n    at WebSocket.onMessageRecieved (C:\Users\hey\IdeaProjects\benbecula\node_modules\@whiske
ysockets\baileys\lib\Socket\socket.js:209:15)\n    at WebSocket.emit (node:events:513:28)\n    at Receiver.receiverOnMessage (C:\Users\hey\Ide
aProjects\benbecula\node_modules\ws\lib\websocket.js:1184:20)\n    at Receiver.emit (node:events:513:28)\n    at Receiver.dataMessage (C:\Users\
hey\IdeaProjects\benbecula\node_modules\ws\lib\receiver.js:526:14)\n    at Receiver.getData (C:\Users\hey\IdeaProjects\benbecula\node_module
s\ws\lib\receiver.js:459:17)\n    at Receiver.startLoop (C:\Users\hey\IdeaProjects\benbecula\node_modules\ws\lib\receiver.js:158:22)\n    at R
eceiver._write (C:\Users\hey\IdeaProjects\benbecula\node_modules\ws\lib\receiver.js:84:10)\n    at writeOrBuffer (node:internal/streams/writab
le:392:12)\n    at _write (node:internal/streams/writable:333:10)\n    at Writable.write (node:internal/streams/writable:337:10)\n    at TLSSock
et.socketOnData (C:\Users\hey\IdeaProjects\benbecula\node_modules\ws\lib\websocket.js:1278:35)\n    at TLSSocket.emit (node:events:513:28)\n  
  at addChunk (node:internal/streams/readable:324:12)\n    at readableAddChunk (node:internal/streams/readable:297:9)\n    at Readable.push (nod
e:internal/streams/readable:234:10)\n    at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)\n    at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17)"
[17:03:10.046] INFO (16624): Connection Status:
[17:03:10.047] INFO (16624): Restart Required, Restarting...

modules\ws\lib\receiver.js:84:10)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at TLSSocket.socketOnData (C:\Users\hey\IdeaProjects\benbecula\node_modules\ws\lib\websocket.js:1278:35)
    at TLSSocket.emit (node:event s:513:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readale:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at TLSWrap.onStreamRead (node:internal/stram_base_commons:190:23)
    at TLSWrap.callbackTrampoline (node:internal/async_hooks:130:17)"

PS: The same code was working perfectly fine previous week. On Restarting, it goes in the loop of sending QR.

iosahil commented 1 year ago

See Below So far the workaround for starting session:

  1. Temporarily install Baileys v5.0.0 using yarn add @adiwajshing/baileys
  2. Change @WhiskeySockets/Baileys -> @adiwajshing/baileys
  3. Login & save auth credentials anywhere, using useMultiFileAuthState or any other AuthStore. (Make sure to restart the connection if it disconnects)
  4. Now, most probably your session will be created successfully.
  5. Switch back to @WhiskeySockets/Baileys everywhere and dont forget to yarn remove @adiwajshing/baileys to prevent any conflict.
  6. Your connection would've started & working just fine. 🥳

NOTE: For some reasons, there is a chance, one might still not be able to listen to message, group, etc. updates (except connection). I have 3 bots, 2 are able to listen to message updates, 1 still only gets connection updates. Idk why. 🤷‍♂️

Till then, I will wait for the devs fix.

iosahil commented 1 year ago

Ok nvm it returned, this time in between while it was idle.

[18:24:21.407] INFO (540): Bot added to group 120363160696XXXXX@g.us
[19:21:05.288] ERROR (540): stream errored out
             node: {
                "tag": "stream:error",
                "attrs": {
                    "code": "503"
                    }
                }

[19:21:05.288] INFO (540): connection errored

trace: "Error: Stream Errored (unknown)\n at WebSocket.<anonymous> (/app/node_modules/@whiskeysockets/baileys/lib/Socket/socket.js:435:13)\n at WebSocket.emit (node:events:513:28)\n at /app/node_modules/@whiskeysockets/baileys/lib/Socket/socket.js:233:35\n at Object.decodeFrame (/app/node_modules/@whiskeysockets/baileys/lib/Utils/noise-handler.js:131:17)\n at WebSocket.onMessageRecieved (/app/node_modules/@whiskeysockets/baileys/lib/Socket/socket.js:209:15)\n at WebSocket.emit (node:events:513:28)\n at Receiver.receiverOnMessage (/app/node_modules/ws/lib/websocket.js:1184:20)\n at Receiver.emit (node:events:513:28)\n at Receiver.dataMessage (/app/node_modules/ws/lib/receiver.js:526:14)\n at Receiver.getData (/app/node_modules/ws/lib/receiver.js:459:17)\n at Receiver.startLoop (/app/node_modules/ws/lib/receiver.js:158:22)\n at Receiver._write (/app/node_modules/ws/lib/receiver.js:84:10)\n at writeOrBuffer (node:internal/streams/writable:392:12)\n at _write (node:internal/streams/writable:333:10)\n at Writable.write (node:internal/streams/writable:337:10)\n at TLSSocket.socketOnData (/app/node_modules/ws/lib/websocket.js:1278:35)\n at TLSSocket.emit (node:events:513:28)\n at addChunk (node:internal/streams/readable:324:12)\n at readableAddChunk (node:internal/streams/readable:297:9)\n at Readable.push (node:internal/streams/readable:234:10)\n at TLSWrap.onStreamRead (node:internal/stream_base_commons:190:23)"

[19:21:05.289] INFO (540): Connection Status:

[19:21:05.289] INFO (540): Connection TimedOut, Reconnecting... 

And there it stuck again :') I started the bot again manually and its working fine.

Though I know this error will return. Any possible work-through or solution will be highly appreciated!

afeno commented 1 year ago

Same here. I Can't scan the QR. Getting this error:

|   statusCode: 515,
|   payload: {
|     statusCode: 515,
|     error: 'Unknown',
|     message: 'Stream Errored (restart required)'
|   },
|   headers: {}
| }

And then, When I restart the socket, I get this error:

|   statusCode: 405,
|   payload: {
|     statusCode: 405,
|     error: 'Method Not Allowed',
|     message: 'Connection Failure'
|   },
|   headers: {}
| }
satriowicaksn commented 1 year ago

Got same error, Anyone know how to solve this issue ??

afeno commented 1 year ago

Use version: [2,2323,4]

iosahil commented 1 year ago

Current workaround is to specify the version [2,2323,4] like:

const sock = makeWASocket({
        version: [2,2323,4],
        ...
});

Credits: @afeno

igortrust commented 1 year ago
version: [2,2323,4],

Run here! tks so much!

@w3nder tks u 2

edgardmessias commented 1 year ago

Fixed at https://github.com/WhiskeySockets/Baileys/releases/tag/v6.2.1

wombat86 commented 1 year ago

Doesn't seem to work for me with v6.2.1. Same symptoms as in the initial comment

blackhiden commented 1 year ago

@iosahil it works fine on me

elmasse commented 1 year ago

Same here, using 6.2.1 and/or the setting the version to the mentioned values are not working for me. Same 515 error.

iosahil commented 1 year ago

Fixed at https://github.com/WhiskeySockets/Baileys/releases/tag/v6.2.1

Using v2.2323.4 or version: [2,2323,4] isn't fixing the issue. For now, getting stream errored out while scanning the QR & when it's idle (if session already exists).

NOTE: Baileys v5.0.0 has no such errors while creating session usually but there is a sudden stream errored out error when it's idle and restarting the connection doesn't work. One can revert back from v6.0.0+ to v5.0.0 using yarn add @adiwajshing/baileys and yarn remove @whiskeysockets/baileys for creating session and scanning QR successfully. Though v5.0.0 lack some features one might not want to miss.

ahsan-riaz commented 1 year ago

@iosahil I am getting this message on: "@adiwajshing/baileys": "^4.2.0", {"level":50,"time":1686584733824,"pid":22196,"hostname":"E41664T","node":{"tag":"stream:error","attrs":{"code":"515"}},"msg":"stream errored out"}

ahsan-riaz commented 1 year ago

any work around or quick fix?

wombat86 commented 1 year ago

My workaround is to restart the service after login

ahsan-riaz commented 1 year ago

My workaround is to restart the service after login

unable to create session actually

iosahil commented 1 year ago

@iosahil I am getting this message on: "@adiwajshing/baileys": "^4.2.0", {"level":50,"time":1686584733824,"pid":22196,"hostname":"E41664T","node":{"tag":"stream:error","attrs":{"code":"515"}},"msg":"stream errored out"}

Yeah, @adiwajshing/baileys isn't robust on this as well. What I did was:

  1. Create session using @adiwajshing/baileys
  2. Make sure to restart the connection if it disconnects when scanning the QR. An example code to do so would look like:
import makeWASocket, { DisconnectReason, useMultiFileAuthState } from '@adiwajshing/baileys';
import {Boom} from '@hapi/boom';

async function startWA() {
  .... 
  ....

  sock.ev.on('connection.update', async update => {
        // Sends QR code to Telegram Chat using a function sendQR()
        if (update.qr) await sendQR(update.qr);

        // Gets connection status
        const {lastDisconnect, connection} = update;
        if (connection) logger.info("Connection Status: ", connection)
        let reason = new Boom(lastDisconnect?.error)?.output?.statusCode
        // Handle reconnection
        if (connection === 'close') {
            if (reason === DisconnectReason.badSession) {
                logger.error(`Bad Session, Please Delete /auth and Scan Again`)
                process.exit()
            } else if (reason === DisconnectReason.connectionClosed) {
                logger.warn("Connection closed, reconnecting....");
                await startWA()
            } else if (reason === DisconnectReason.connectionLost) {
                logger.warn("Connection Lost from Server, reconnecting...");
                await startWA()
            } else if (reason === DisconnectReason.connectionReplaced) {
                logger.error("Connection Replaced, Another New Session Opened, Please Close Current Session First");
                process.exit()
            } else if (reason === DisconnectReason.loggedOut) {
                logger.error(`Device Logged Out, Please Delete /auth and Scan Again.`)
                process.exit()
            } else if (reason === DisconnectReason.restartRequired) {
                logger.info("Restart Required, Restarting...");
                await startWA()
            } else if (reason === DisconnectReason.timedOut) {
                logger.warn("Connection TimedOut, Reconnecting...");
                await startWA()
            } else {
                logger.warn(`Unknown DisconnectReason: ${reason}: ${connection}`);
                await startWA()
            }
        } else if (connection === 'open') {
            logger.info('Opened connection');
        }
  });
}
  1. Switch back to @whiskeysockets/baileys
  2. Use the created session with @whiskeysockets/baileys.

This is a very vague & temporary work-around that worked for me.

rayenking commented 1 year ago

I got this problem before I used v6.2.1

and I got fix it when using v.6.2.1 but when I tried to install another library with yarn or npm the version replaced

so I downloaded the releases and extract it to my root folder, its solved my problem.

ahsan-riaz commented 1 year ago

I got this problem before I used v6.2.1

and I got fix it when using v.6.2.1 but when I tried to install another library with yarn or npm the version replaced

so I downloaded the releases and extract it to my root folder, its solved my problem.

can you please mention your node version

jhernancanom commented 1 year ago

Use version: [2,2323,4]

How should I proceed? ----------------->>> solved !!! see next ........ image image

jhernancanom commented 1 year ago

Solved for me. I saw the solution somewhere, I aply it, and now it runs fine, but it says that the adjustment must be done in whatsapp.js. image

Marouane-AQUIL commented 1 year ago

i use https://github.com/ookamiiixd/baileys-api.git

i have this problem : image

this is my package.json { "name": "baileys-api", "description": "Simple RESTful WhatsApp API", "version": "1.0.0-beta.0", "private": true, "main": "dist/index.js", "repository": "github:ookamiiixd/baileys-api", "author": "Royhan (https://github.com/ookamiiixd)", "bugs": { "url": "https://github.com/ookamiiixd/baileys-api/issues" }, "homepage": "https://github.com/ookamiiixd/baileys-api#readme", "license": "MIT", "scripts": { "start": "node .", "build": "tsc", "lint": "eslint .", "format": "prettier . --write" }, "dependencies": { "@adiwajshing/baileys": "^5.0.0", "@hapi/boom": "^10.0.0", "@ookamiiixd/baileys-store": "^1.0.0-beta.0", "@prisma/client": "^4.7.1", "cors": "^2.8.5", "dotenv": "^16.0.3", "express": "^4.18.2", "express-validator": "^6.14.2", "link-preview-js": "^3.0.0", "pino": "^8.7.0", "qrcode": "^1.5.1", "qrcode-terminal": "^0.12.0", "sharp": "^0.30.5" }, "devDependencies": { "@types/cors": "^2.8.13", "@types/express": "^4.17.14", "@types/node": "^18.11.10", "@types/qrcode": "^1.5.0", "@types/ws": "^8.5.3", "@typescript-eslint/eslint-plugin": "^5.45.0", "@typescript-eslint/parser": "^5.45.0", "eslint": "^8.29.0", "eslint-config-prettier": "^8.5.0", "prettier": "^2.8.0", "prettier-plugin-organize-imports": "^3.2.1", "prisma": "^4.7.1", "ts-node": "^10.9.1", "typescript": "^4.9.3" }, "engines": { "node": ">=14.5.0" }, "files": [ "dist/", "prisma/schema.prisma", ".env.example" ] }

what i can change for resolve that? i need help!

trisnoardi commented 1 year ago

In my code, this issue is closely related to the re-calling of startSock when the connection is closed. And it's possible that the connection always closes after scanning the QR code, and if reconnection is not performed, the aforementioned issue will occur.

if(connection === 'close') {
  // reconnect if not logged out
  if((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
  startSock()
  } else {
  console.log('Connection closed. You are logged out.')
  }
}
Felipegloriati commented 1 year ago

No meu código, esse problema está intimamente relacionado à chamada de startSock quando a conexão é fechada. E é possível que a conexão sempre feche após a leitura do código QR e, se a reconexão não for realizada, ocorrerá o problema mencionado.

if(connection === 'close') {
  // reconnect if not logged out
  if((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
  startSock()
  } else {
  console.log('Connection closed. You are logged out.')
  }
}

estou tendo esse problema mas não sei como resolver e onde coloco este codigo?

p-ugulino commented 1 year ago

Bumping

imlolman commented 7 months ago

I just encountered with the issue and found a workaround.

I copied the example.ts file and after a few ts error resolutions, ran it to create authentication file/folder. Once done, since now i am already logged in, my normal code works.

rlucredio commented 6 months ago

In my code, this issue is closely related to the re-calling of startSock when the connection is closed. And it's possible that the connection always closes after scanning the QR code, and if reconnection is not performed, the aforementioned issue will occur.

if(connection === 'close') {
  // reconnect if not logged out
  if((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
  startSock()
  } else {
  console.log('Connection closed. You are logged out.')
  }
}

This worked for me. For some reason we need to restart as soon as this error happens, and it's just a matter of connecting again.

The "startSock()" call in this snippet is related to the provided example.ts. In my case I didn't need to rewrite any code, just had a bug that was preventing the startSock() from being executed.

manuelcastrobarinas commented 3 months ago

In my code, this issue is closely related to the re-calling of startSock when the connection is closed. And it's possible that the connection always closes after scanning the QR code, and if reconnection is not performed, the aforementioned issue will occur.

if(connection === 'close') {
  // reconnect if not logged out
  if((lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut) {
  startSock()
  } else {
  console.log('Connection closed. You are logged out.')
  }
}

This worked for me. For some reason we need to restart as soon as this error happens, and it's just a matter of connecting again.

The "startSock()" call in this snippet is related to the provided example.ts. In my case I didn't need to rewrite any code, just had a bug that was preventing the startSock() from being executed.

remember that you should clean the socket connection before to restart and execute, this You can achieve this by calling the socket reference and accessing the ws property with its close() function;

example this.socket.ws.close();

or also this.socket.ws.terminate();

but it is better to use close() because the connection is closed more cleanly while terminate() kills the process instantly

...
 if (connection === 'close') {
  const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
  if (shouldReconnect) {
      this.socket?.ws.close();  //close connection
      await this.startSock();   //Since the connection works through sockets, you should implement async await
      resolve!();
    }
 }
jaderesp commented 3 months ago

Screenshot_62 no meu caso continuo testando porem o erro persiste

TheMacros commented 2 months ago

Still have this issue in version 6.6.0 The code is:

const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info');
const sock = makeWASocket.default({
        printQRInTerminal: true,
        auth: state,
})

An error with statusCode 515 occurs and the phone is stuck on QR code scanning. Tried on Android and iPhone - same problem. Also tried to set version: [2, 2323, 4] and browser - nothing helps. Issue persists. Does anyone know how to solve this?

Riders004 commented 1 month ago

See Below ~So far the workaround for starting session:~

  1. Temporarily install Baileys v5.0.0 using yarn add @adiwajshing/baileys
  2. Change @WhiskeySockets/Baileys -> @adiwajshing/baileys
  3. Login & save auth credentials anywhere, using useMultiFileAuthState or any other AuthStore. (Make sure to restart the connection if it disconnects)
  4. Now, most probably your session will be created successfully.
  5. Switch back to @WhiskeySockets/Baileys everywhere and dont forget to yarn remove @adiwajshing/baileys to prevent any conflict.
  6. Your connection would've started & working just fine. 🥳

NOTE: For some reasons, there is a chance, one might still not be able to listen to message, group, etc. updates (except connection). I have 3 bots, 2 are able to listen to message updates, 1 still only gets connection updates. Idk why. 🤷‍♂️

Till then, I will wait for the devs fix.

Bailey's bug for message or commnds listening