Giter Club home page Giter Club logo

Comments (15)

bobdevfull avatar bobdevfull commented on June 2, 2024

You must use this code to reconnect automatically, if you already use one similar, replace it with this code

sock.ev.on('connection.update', async (update) => {
	const { connection, lastDisconnect } = update

	if (connection === 'close'){
		if (lastDisconnect?.error?.output?.statusCode !== 401) {
			connectToWhatsApp()
		} else {
			console.log('Logout :(')
		}
	} else if (connection === 'open') {
		console.log('Connected :)')
	}
})

from baileys.

RedTNT-Official avatar RedTNT-Official commented on June 2, 2024

You must use this code to reconnect automatically, if you already use one similar, replace it with this code

sock.ev.on('connection.update', async (update) => {
	const { connection, lastDisconnect } = update

	if (connection === 'close'){
		if (lastDisconnect?.error?.output?.statusCode !== 401) {
			connectToWhatsApp()
		} else {
			console.log('Logout :(')
		}
	} else if (connection === 'open') {
		console.log('Connected :)')
	}
})

I have the same issue and every time it happens, the session is clossed and it asks for the QR again

from baileys.

dhirennjaypal avatar dhirennjaypal commented on June 2, 2024

You must use this code to reconnect automatically, if you already use one similar, replace it with this code

sock.ev.on('connection.update', async (update) => {
	const { connection, lastDisconnect } = update

	if (connection === 'close'){
		if (lastDisconnect?.error?.output?.statusCode !== 401) {
			connectToWhatsApp()
		} else {
			console.log('Logout :(')
		}
	} else if (connection === 'open') {
		console.log('Connected :)')
	}
})

Thank You, And sorry for late reply. I will try this.

from baileys.

dhirennjaypal avatar dhirennjaypal commented on June 2, 2024

You must use this code to reconnect automatically, if you already use one similar, replace it with this code

sock.ev.on('connection.update', async (update) => {
	const { connection, lastDisconnect } = update

	if (connection === 'close'){
		if (lastDisconnect?.error?.output?.statusCode !== 401) {
			connectToWhatsApp()
		} else {
			console.log('Logout :(')
		}
	} else if (connection === 'open') {
		console.log('Connected :)')
	}
})

I tried this, but it didn't work.

from baileys.

Cristopher8049 avatar Cristopher8049 commented on June 2, 2024

I have the same problem, has anyone found a solution?

from baileys.

hosamalzagh avatar hosamalzagh commented on June 2, 2024

{"level":50,"time":1686566884467,"pid":11228,"hostname":"hosamalzagh-hpprobook450g6","err":{"type":"TypeError","message":"Cannot read properties of undefined (reading 'includes')","stack":"TypeError: Cannot read properties of undefined (reading 'includes')\n at getCodeFromWSError (/home/predo/www/whatgo/whatsapp-api-nodejs/node_modules/@whiskeysockets/baileys/lib/Utils/generics.js:339:23)\n at WebSocket. (/home/predo/www/whatgo/whatsapp-api-nodejs/node_modules/@whiskeysockets/baileys/lib/Socket/socket.js:518:116)\n at WebSocket.emit (node:events:523:35)\n at WebSocket.emitClose (/home/predo/www/whatgo/whatsapp-api-nodejs/node_modules/ws/lib/websocket.js:258:10)\n at Receiver.receiverOnFinish (/home/predo/www/whatgo/whatsapp-api-nodejs/node_modules/ws/lib/websocket.js:1158:20)\n at Receiver.emit (node:events:511:28)\n at finish (node:internal/streams/writable:757:10)\n at node:internal/streams/writable:735:13\n at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"},"msg":"Cannot read properties of undefined (reading 'includes')"}
{"level":30,"time":1686566884468,"pid":11228,"hostname":"hosamalzagh-hpprobook450g6","msg":"Server closed"}

from baileys.

titiloxx avatar titiloxx commented on June 2, 2024

2. Waited Some Time and error appeared

Are you trying to send a message, or is an error simply waiting to happen?

from baileys.

journeyANDloneliness avatar journeyANDloneliness commented on June 2, 2024

this happened if u didn't save the contact who send messages. any solution?

from baileys.

Jasermon avatar Jasermon commented on June 2, 2024

this happened for me too. here is my code

app.get("/send-message", async (req, res) => {
  const tempMessage = req.query.message;
  const msgTo = req.query.to;

  try {
    if (!msgTo) {
      res.status(500).json({
        status: false,
        response: "The number does not exist",
      });
    } else {
      if (isConnected()) {
        sock
          .sendMessage(msgTo, {
            text: tempMessage,
          })
          .then(() => {
            res.status(200).json({
              status: "success",
              response: "ok",
            });
          })
          .catch((err) => {
            res.status(500).json({
              status: false,
              response: err,
            });
          });
      } else {
        res.status(500).json({
          status: false,
          response: "You are not connected yet",
        });
      }
    }
  } catch (err) {
    res.status(500).send(err);
  }
});

from baileys.

krugerrgabriel avatar krugerrgabriel commented on June 2, 2024

It's happens to me too.

from baileys.

JoshlsNT avatar JoshlsNT commented on June 2, 2024

I am also facing this problem. In my case it occurs when I have to create a connection to "mobile"

{"level":30,"time":"2023-10-08T03:56:35.040Z","pid":24732,"hostname":"joshua","class":"baileys","browser":["Baileys","Chrome","4.0.0"],"helloMsg":{"clientHello":{"ephemeral":"LSzz7YwTnrw9vh9NjNg1UO3Tcfp6RmJAzGLLj3uYpVw="}},"msg":"connected to WA"}
{"level":30,"time":"2023-10-08T03:56:35.376Z","pid":24732,"hostname":"joshua","class":"baileys","trace":"Error: Connection Terminated\n    at MobileSocketClient.<anonymous> (C:\\Users\\joshu\\Documents\\Projetos\\ntautomations\\whatsapp\\node_modules\\@whiskeysockets\\baileys\\lib\\Socket\\socket.js:437:30)\n    at MobileSocketClient.emit (node:events:513:28)\n    at Socket.<anonymous> (C:\\Users\\joshu\\Documents\\Projetos\\ntautomations\\whatsapp\\node_modules\\@whiskeysockets\\baileys\\lib\\Socket\\Client\\mobile-socket-client.js:44:100)\n    at Socket.emit (node:events:513:28)\n    at TCP.<anonymous> (node:net:322:12)\n    at TCP.callbackTrampoline (node:internal/async_hooks:130:17)","msg":"connection errored"}
connection closed due to  Error: Connection Terminated
    at MobileSocketClient.<anonymous> (C:\Users\joshu\Documents\Projetos\ntautomations\whatsapp\node_modules\@whiskeysockets\baileys\lib\Socket\socket.js:437:30)
    at MobileSocketClient.emit (node:events:513:28)
    at Socket.<anonymous> (C:\Users\joshu\Documents\Projetos\ntautomations\whatsapp\node_modules\@whiskeysockets\baileys\lib\Socket\Client\mobile-socket-client.js:44:100)
    at Socket.emit (node:events:513:28)
    at TCP.<anonymous> (node:net:322:12)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  data: null,
  isBoom: true,
  isServer: false,
  output: {
    statusCode: 428,
    payload: {
      statusCode: 428,
      error: 'Precondition Required',
      message: 'Connection Terminated'
    },
    headers: {}
  }
} , reconnecting  true

My code:

const { state, saveCreds } = await useMultiFileAuthState(fullPath);
const { version, isLatest } = await fetchLatestBaileysVersion();

const WASocketConfig: UserFacingSocketConfig = {
  version,
  printQRInTerminal: true,
  auth: state,
  mobile: true,
};

const sock = makeWASocket(WASocketConfig);

from baileys.

Jasermon avatar Jasermon commented on June 2, 2024

Guys this comment fixed my problem.

from baileys.

weershft avatar weershft commented on June 2, 2024

Any personal solutions?

from baileys.

weershft avatar weershft commented on June 2, 2024

@dhirennjaypal Any solutions?

from baileys.

dhirennjaypal avatar dhirennjaypal commented on June 2, 2024

I don't remember what was it about when I did post this, but this code is working file:

import makeWASocket, { DisconnectReason, BufferJSON, useMultiFileAuthState } from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'

async function connectToWhatsApp () {
    const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')

    const sock = makeWASocket({
		auth: state,
        printQRInTerminal: true,
    });

    sock.ev.on ('creds.update', saveCreds)

    sock.ev.on('connection.update', (update) => {
        const { connection, lastDisconnect } = update
        if(connection === 'close') {
            const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut
            console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', shouldReconnect)
            if(shouldReconnect) {
                connectToWhatsApp()
            }
        } else if(connection === 'open') {
            console.log('opened connection')
        }
    });

    sock.ev.on('messages.upsert', m => {
	console.log("Message Received: "+m.messages[0].key.remoteJid);
    });
}

connectToWhatsApp();

from baileys.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.