Baileys: [BUG] "stream errored out" while reading QR or just suddenly!

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.

About this issue

  • Original URL
  • State: closed
  • Created a year ago
  • Comments: 30 (1 by maintainers)

Most upvoted comments

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

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

Credits: @afeno

version: [2,2323,4],

Run here! tks so much!

@w3nder tks u 2

Use version: [2,2323,4]

@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.

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.

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