Jump to content

WALIX - WHATSAPP GATEWAY SUPPORT MULTY DEVICE v7.0


Recommended Posts

  • 4 weeks later...
  • 1 month later...

please solve this

 

C:\xampp\htdocs\server.js:108
if (res && !res.headersSent) {
^

ReferenceError: res is not defined
at EventEmitter.<anonymous> (C:\xampp\htdocs\server.js:108:13)
at EventEmitter.emit (node:events:525:35)
at EventEmitter.<anonymous> (C:\xampp\htdocs\node_modules\@adiwajshing\baileys\lib\Utils\event-buffer.js:38:16)
at EventEmitter.emit (node:events:513:28)
at Object.emit (C:\xampp\htdocs\node_modules\@adiwajshing\baileys\lib\Utils\event-buffer.js:56:23)
at genPairQR (C:\xampp\htdocs\node_modules\@adiwajshing\baileys\lib\Socket\socket.js:381:16)
at WebSocket.<anonymous> (C:\xampp\htdocs\node_modules\@adiwajshing\baileys\lib\Socket\socket.js:385:9)

  • Like 1
  • 4 weeks later...
  • 1 month later...
  • 1 month later...
  • 1 month later...
On 4/5/2023 at 9:17 PM, vosonese said:

qr code is not working 😞

Here is the code for server.js, don't forget to update the @adiwajshing/baileys to version 4.4.0 or 5.0.0:

const { Browsers, useMultiFileAuthState , DisconnectReason, fetchLatestBaileysVersion, generateForwardMessageContent, prepareWAMessageMedia, generateWAMessageFromContent, generateMessageID, downloadContentFromMessage, makeInMemoryStore, jidDecode, proto } = require("@adiwajshing/baileys")
const makeWASocket = require('@adiwajshing/baileys').default;
const pino = require('pino')
const { Boom } = require('@hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
require('dotenv/config')
const express = require('express')
const socket = require("socket.io");
const { toDataURL } = require('qrcode')
const mysql = require('mysql');
require('dotenv').config();
const request = require('request');
const { smsg } = require('./app_node/lib/myf')

const app = express()
const host = process.env.HOST ?? '127.0.0.1'
const port = parseInt(process.env.PORT ?? 3000)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const ser = app.listen(port, host, () => {
    console.log(`Server is listening on http://${host}:${port}`)
})
const io = socket(ser);

const db = mysql.createPool({
    host: process.env.DB_HOSTNAME,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE
});

db.getConnection((err) => {
    if (err) throw err;
    console.log('Mysql Connected...');
});

const sessionMap = new Map()

async function startDEVICE(idevice) {
    const store = makeInMemoryStore({ logger: pino().child({ level: 'silent', stream: 'store' }) })
    // const { state, saveState } = useMultiFileAuthState(`./app_node/session/device-${idevice}.json`)
    const { state, saveCreds } = await useMultiFileAuthState(`./app_node/session/device-${idevice}.json`)
    const sock = makeWASocket({
        logger: pino({ level: 'silent' }),
        printQRInTerminal: true,
        browser: Browsers.macOS("Desktop"),
        auth: state
    });
    sock.ev.on('creds.update', saveCreds);
    store.bind(sock.ev)
    sock.decodeJid = (jid) => {
        if (!jid) return jid
        if (/:\d+@/gi.test(jid)) {
            let decode = jidDecode(jid) || {}
            return decode.user && decode.server && decode.user + '@' + decode.server || jid
        } else return jid
    }
    sock.ev.on('connection.update', async (update) => {
        const { connection, lastDisconnect, qr } = update
        if (update.qr) {
            const url = await toDataURL(qr)
            // if (res && !res.headersSent) {
            try {
                const qr = await toDataURL(update.qr)
                io.emit('qr', { id: idevice, src: qr });
                log = {"result": true, "instance": idevice, "qrcode": qr, "message": "Ready scan now!"}
                // res.send(log);
                console.log(log)
                // return
            } catch {
                response(res, 500, false, 'Unable to create QR code.')
            }
            // }      
        }
        if (connection === 'close') {
            // sessionMap.delete(idevice)
            const logoutsessi = () => {
                sock.logout();
                if (fs.existsSync(`./sessions/${idevice}.json`)) {
                    fs.unlinkSync(`./sessions/${idevice}.json`);
                }
            }
            // let reason = new Boom(lastDisconnect?.error)?.output.statusCode
            // let reason = lastDisconnect.error?.output?.statusCode;
            let reason = (lastDisconnect?.error instanceof Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
            console.log('connection closed due to ', lastDisconnect?.error, ', reconnecting ', reason);
            if(reason) {
                // logoutsessi();
                startDEVICE(idevice);
            }           
        } else if(connection === 'open') {
            io.emit('message', {
                id: idevice,
                text: 'Whatsapp is ready!'
            });
            io.emit('authenticated', {
                id: idevice,
                data: sock.user
            })
        }
    })
    sock.ev.on('messages.upsert', async ({ messages, type }) => {
        // autoreply code here
    })
   
   sessionMap.set(idevice, sock);
   // return sock
}

const logoutDEVICE = (idevice) => {
    const chi = sessionMap.get(idevice)
    console.log(chi)
    chi.logout();
    if (fs.existsSync(`./app_node/session/device-${idevice}.json`)) {
        fs.rmSync(`./app_node/session/device-${idevice}.json`, { force: true, recursive: true });
    }
    sessionMap.delete(idevice)
}

io.on('connection', function (socket) {
    socket.on('create-session', function (data) {
        if (sessionMap.has(parseInt(data.id))) {
            console.log('get session: ' + data.id);
            const conn = sessionMap.get(parseInt(data.id));
            io.emit('message', {
                id: data.id,
                text: 'Whatsapp is ready!'
            });
            io.emit('authenticated', {
                id: data.id,
                data: conn.user
            })
        } else {
            console.log('Create session: ' + data.id);
            startDEVICE(data.id);
        }
    });
    socket.on('logout', async function (data) {
        if (fs.existsSync(`./app_node/session/device-${data.id}.json`)) {
            socket.emit('isdelete', {
                id: data.id,
                text: '<h2 class="text-center text-info mt-4">Logout Success, Lets Scan Again<h2>'
            })
            logoutDEVICE(data.id)
        } else {
            socket.emit('isdelete', {
                id: data.id,
                text: '<h2 class="text-center text-danger mt-4">You are have not Login yet!<h2>'
            })
        }
    })
});
require('./app_node/routes/web')(app, sessionMap, startDEVICE)
require('./app_node/lib/cron')(db, sessionMap, fs, startDEVICE)

 

  • Like 1
  • 1 year later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
  • Create New...