0

I'm using whatsapp-web.js to create a bot. I want to use the client in different files so I'm trying to export it but I cant get the updated client value on the files where I import it. I tried making a global variable as an object so then its value can be updated ones it goes through the function.

const { Client, RemoteAuth } = require('whatsapp-web.js');

var client = {}
// Require database
mongoose.connect(DATABASE_URL).then(async () => {
    const store = new MongoStore({ mongoose: mongoose });

    client = new Client({
        authStrategy: new RemoteAuth({
            store: store,
            backupSyncIntervalMs: 300000
        }),
        headless: false,
        puppeteer: {
            args: [
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-dev-shm-usage',
                '--disable-accelerated-2d-canvas',
                '--no-first-run',
                '--no-zygote',
                '--disable-gpu'
            ],
        },
    });

    client.on('authenticated', async () => {
        console.log('Client is authenticated!');
    });
    client.on('qr', async qr => {
        qrcode.generate(qr, { small: true });
    });
    client.on('ready', async () => {
        console.log('Client is ready!');
    });

    client.on('remote_session_saved', () => {
        console.log('Client is saved!');
    });
    client.initialize();
});

exports.client = client

The files where I'm importing it gives me 'client = {}' I thought that by declaring it as an object I get a reference space which allows to change the variable value later. This was working for me before I use RemoteAuth() and have to update the variable inside a function.

This is how I import it:

var client = require('../app').client;

//Funcion para que se envie correo de minimo de productos
async function correoAgotados(agotados) {
    console.log('inicia proceso de envio de correo')
    var mensaje = "Saludos desde " + agotados[0].planta + ", <br>";
    for (var i = 0; i < agotados.length; i++)
        mensaje = mensaje + "<p>El producto: " + agotados[i].producto + " ha llegado a su minimo.</p>" + "<p>Cantidad en Existencia: " + agotados[i].cantidad + " " + agotados[i].unidadCosteo + "</p><p>Minimo Registrado: " + agotados[i].min + " " + agotados[i].unidadCosteo + "</p> <br>"

    var mailOptions = {
        from: '--',
        to: '--',
        subject: 'Falta de Materiales',
        html: mensaje
    };
    try {
        var contacts = ['--']
        if (agotados[0].planta == 'Hadrok')
            contacts.push('--')
        mensaje = mensaje
        for (var i = 0; i < contacts.length; i++) {
            await client.sendMessage('521' + contacts[i] + '@c.us', mensaje.replace(/<br>|<p>/g, '\n').replace(/<\/p>/g, ''))
        }
    } catch {
        console.log('error de bot')
        console.log(client)
    }
}
  • You're reassigning `client` in an async function. But you're exporting the value from before the async function runs. – Barmar Jun 05 '23 at 21:36
  • I know am exporting it before the update, but its an object. Correct me if am wrong, but an object creates a reference to a memory space that allows it to be change later. As I said this was working correctly until I had to update the variable inside a function, but it was the same it was getting updated later and it imported correctly – Adrian Gonzalez Jun 05 '23 at 21:42
  • I check the "duplicate" post and it doesnt help me at all. Why is this marked as duplicated? – Adrian Gonzalez Jun 05 '23 at 21:57
  • Why don't you think it's the same? You're assigning a variable asynchronously. When you use the variable before the assignment in `exports.client = client;`, you get its old value, which is the empty object. – Barmar Jun 06 '23 at 14:55
  • Note that you're NOT modifying the object in place, you're reassigning the variable with a NEW object that's created later. – Barmar Jun 06 '23 at 14:56
  • I don't think its a duplicate because I'm looking for a solution on how to make it work as I intended and that post just explains why it doesn't work and not offer a workaround on how to make it work. And now I have another question which I cant ask because apparently I dont do good questions – Adrian Gonzalez Jun 29 '23 at 21:27
  • [This answer](https://stackoverflow.com/a/28057246/1491895) has "The two main ways to solve it are using callbacks and promises:" – Barmar Jun 29 '23 at 21:29
  • Also see https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Barmar Jun 29 '23 at 21:30
  • The basic point is that you have to learn to think differently when processing asynchronous data. You can't just use the same style of coding. – Barmar Jun 29 '23 at 21:31
  • I cant figure out how to to export the client variable and use it in other modules, I tried with a promise but it creates a different client on each module – Adrian Gonzalez Jun 29 '23 at 21:34
  • Now im trying to have just the variable at app.js and use sockets to use it in there, but now I cant figure out how to emit from other module, I export my io and try io.sockets.emit('sendmessage', data) but it doesnt go thorugh the io.on(connection, socket -> { socket.on('sendmessage), function (msg) { ... } } can you help with that? – Adrian Gonzalez Jun 29 '23 at 21:39
  • See [can I export the result of an async function?](https://stackoverflow.com/questions/49991740/can-i-export-the-result-of-an-asynchronous-function-with-module-export).) tldr is "no" – Barmar Jun 29 '23 at 22:51

0 Answers0