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