I'm trying to initialize the script in multiple sessions, does anyone have any tips?
const {Client} = require(`./1.0.1/index`);
const fs = require(`fs`);
const session = function (number) {
console.log('number', number);
const client = new Client({
puppeteer: {
headless: false,
userDataDir: __dirname + `/${number}`,
args: ['--no-sandbox']
},
session: function () {
if (fs.existsSync(`./${number}.json`))
return require(`./${number}.json`);
else return false;
}
});
client.initialize();
client.on(`qr`, (qr) => {
console.log('qr', qr);
});
client.on(`authenticated`, (session) => {
if (!fs.existsSync(`./${number}.json`)) {
fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(`Session stored`);
});
}
});
client.on(`auth_failure`, (msg) => {
console.log(`auth_failure`, msg);
});
client.on(`ready`, () => {
console.log(`ready`);
});
client.on(`message`, async msg => {
console.log('message', msg)
});
client.on(`disconnected`, (reason) => {
console.log(`disconnected`, reason);
});
};
new session('phone-number');
There shouldn't be an issue with handling multiple sessions. You'll just want to instantiate multiple clients.
const client = new Client();
const client2 = new Client();
client.initialize();
client2.initialize();
client.on('qr', qr => {
console.log('QR Received (1)', qr);
});
client2.on('qr', qr => {
console.log('QR Received (2)', qr);
});
If you want to use the same handlers, you can define a function separately and register the handler like so:
const onMessage = (msg) => {
console.log(msg.body);
}
client.on('message', onMessage);
client2.on('message', onMessage);
Is this what you're referring to?
@pedroslopez Thanks for the contribution, did you see my example? Was there a possibility to create something this way?
Yeah I don't see why that wouldn't work. You can also return the client from that function so you can access it later.
Is something wrong with the solution you posted?
Also, just as a note, every WhatsApp structure has the client reference so if at any point you have, for example, a Message object, you can get the client it refers to by using message.client.
@pedroslopez I'm running tests and I had some session problems, so I'm separating the puppeteer's cache in the variable.
Great, I found my error in the session and the puppeteer started 2 separate browsers with cache.
I applied only one fix to get the file with the keys.

The corrected version follows with multiple sessions.
const {Client} = require(`./1.0.1/index`);
const fs = require(`fs`);
const session = function (number) {
console.log('number', number);
let session_file;
if (fs.existsSync(`./${number}.json`)) {
session_file = require(`./${number}.json`);
console.log('session_file', session_file);
}
const client = new Client({
puppeteer: {
headless: false,
userDataDir: __dirname + `/${number}`,
args: ['--no-sandbox']
},
session: session_file
});
client.initialize();
client.on(`qr`, (qr) => {
console.log('qr', qr);
});
client.on(`authenticated`, (session) => {
if (!fs.existsSync(`./${number}.json`)) {
fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(`Session stored`);
});
}
});
client.on(`auth_failure`, (msg) => {
console.log(`auth_failure`, msg);
});
client.on(`ready`, () => {
console.log(`ready`);
});
client.on(`message`, async msg => {
console.log('message', msg)
});
client.on(`disconnected`, (reason) => {
console.log(`disconnected`, reason);
});
};
new session('phone-number-1');
new session('phone-number-2');
new session('phone-number-3');
It would be interesting to implement this script in the examples.
Yeah, definitely!
I'm in the process right now of creating a nice and clear guide that explains how everything works (https://waguide.pedroslopez.me/). I just started it a few hours ago so it's still in progress, but eventually I want to move away from pointing people to example.js and have everything in that guide. I'm thinking of having a useful examples section in there where something like this can go.
Thanks!
The corrected version follows with multiple sessions.
const {Client} = require(`./1.0.1/index`); const fs = require(`fs`); const session = function (number) { console.log('number', number); let session_file; if (fs.existsSync(`./${number}.json`)) { session_file = require(`./${number}.json`); console.log('session_file', session_file); } const client = new Client({ puppeteer: { headless: false, userDataDir: __dirname + `/${number}`, args: ['--no-sandbox'] }, session: session_file }); client.initialize(); client.on(`qr`, (qr) => { console.log('qr', qr); }); client.on(`authenticated`, (session) => { if (!fs.existsSync(`./${number}.json`)) { fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) { if (err) console.log(err); else console.log(`Session stored`); }); } }); client.on(`auth_failure`, (msg) => { console.log(`auth_failure`, msg); }); client.on(`ready`, () => { console.log(`ready`); }); client.on(`message`, async msg => { console.log('message', msg) }); client.on(`disconnected`, (reason) => { console.log(`disconnected`, reason); }); }; new session('phone-number-1'); new session('phone-number-2'); new session('phone-number-3');It would be interesting to implement this script in the examples.
how do you send messages with a particular session?
Thus interesting I also have the same idea as yours. I will try your code
and see if I can do some up grades
On Mon, Apr 6, 2020, 06:03 ʀᴀᴅᴇɴᴠᴏᴅᴋᴀ (ᴇᴋᴀ ꜱ) notifications@github.com
wrote:
The corrected version follows with multiple sessions.
const {Client} = require(
./1.0.1/index);const fs = require(fs);
const session = function (number) {console.log('number', number);
let session_file;
if (fs.existsSync(./${number}.json)) {
session_file = require(./${number}.json);
console.log('session_file', session_file);
}const client = new Client({
puppeteer: {
headless: false,
userDataDir: __dirname +/${number},
args: ['--no-sandbox']
},
session: session_file
});client.initialize();
client.on(
qr, (qr) => {
console.log('qr', qr);
});client.on(
authenticated, (session) => {
if (!fs.existsSync(./${number}.json)) {
fs.writeFile(./${number}.json, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(Session stored);
});
}
});client.on(
auth_failure, (msg) => {
console.log(auth_failure, msg);
});client.on(
ready, () => {
console.log(ready);
});client.on(
message, async msg => {
console.log('message', msg)
});client.on(
disconnected, (reason) => {
console.log(disconnected, reason);
});};
new session('phone-number-1');new session('phone-number-2');new session('phone-number-3');It would be interesting to implement this script in the examples.
how do you send messages with a particular session?
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/pedroslopez/whatsapp-web.js/issues/45#issuecomment-609553345,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ANMBORL5P2HW42ZTP3HISSLRLFICRANCNFSM4KSYHMAA
.
How i do send message with different route using thats multi session code ?
The corrected version follows with multiple sessions.
const {Client} = require(`./1.0.1/index`); const fs = require(`fs`); const session = function (number) { console.log('number', number); let session_file; if (fs.existsSync(`./${number}.json`)) { session_file = require(`./${number}.json`); console.log('session_file', session_file); } const client = new Client({ puppeteer: { headless: false, userDataDir: __dirname + `/${number}`, args: ['--no-sandbox'] }, session: session_file }); client.initialize(); client.on(`qr`, (qr) => { console.log('qr', qr); }); client.on(`authenticated`, (session) => { if (!fs.existsSync(`./${number}.json`)) { fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) { if (err) console.log(err); else console.log(`Session stored`); }); } }); client.on(`auth_failure`, (msg) => { console.log(`auth_failure`, msg); }); client.on(`ready`, () => { console.log(`ready`); }); client.on(`message`, async msg => { console.log('message', msg) }); client.on(`disconnected`, (reason) => { console.log(`disconnected`, reason); }); }; new session('phone-number-1'); new session('phone-number-2'); new session('phone-number-3');It would be interesting to implement this script in the examples.
how do you send messages with a particular session?
How i do send message with different route using thats multi session code ?
How i do send message with different route using thats multi session code ?
You will need to store the client in some way, maybe in an object. Using that example, I would return client in that session function, and then save them like this:
const sessions = {
'1234567890': session('1234567890'),
'1111123456': session('1111123456')
}
you could then later refer to these like so:
sessions['1234567890'].sendMessage()
How i do send message with different route using thats multi session code ?
You will need to store the client in some way, maybe in an object. Using that example, I would return
clientin thatsessionfunction, and then save them like this:const sessions = { '1234567890': session('1234567890'), '1111123456': session('1111123456') }you could then later refer to these like so:
sessions['1234567890'].sendMessage()
i am tryng tu use this method. but i still get the problem and having error.
this my session.
`var express = require('express')
var app = express()
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const {Client} = require(whatsapp-web.js);
const fs = require(fs);
const session = function (number) {
console.log('number', number);
let session_file;
if (fs.existsSync(`./${number}.json`)) {
session_file = require(`./${number}.json`);
console.log('session_file', session_file);
}
const client = new Client({
puppeteer: {
headless: false,
userDataDir: __dirname + `/${number}`,
args: ['--no-sandbox']
},
session: session_file
});
client.initialize();
client.on(`qr`, (qr) => {
console.log('qr', qr);
});
client.on(`authenticated`, (session) => {
if (!fs.existsSync(`./${number}.json`)) {
fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(`Session stored`);
});
}
});
client.on(`auth_failure`, (msg) => {
console.log(`auth_failure`, msg);
});
client.on(`ready`, () => {
console.log(`ready`);
});
client.on(`message`, async msg => {
console.log('message', msg)
});
client.on(`disconnected`, (reason) => {
console.log(`disconnected`, reason);
});
};
new session('082113150495');
app.get('/send', function (req, res, next) {
const sessions = {
'082113150495': session('082113150495')
}
sessions['082113150495'].sendMessage("[email protected]", `test`).then((r) => {
console.log("sendMessage",r)
});
next();
})
app.listen(port, hostname, () => {
console.log(Server running at http://${hostname}:${port}/);
});`
how do i can send the message inside the router. like this
`app.get('/send', function (req, res, next) {
const sessions = {
'082113150495': session('082113150495')
}
sessions['082113150495'].sendMessage("[email protected]", `test`).then((r) => {
console.log("sendMessage",r)
});
next();
})
when i execute the route, error like this.
TypeError: Cannot read property 'sendMessage' of undefined`
whats is my problem, thanks
@Marzuki5 you need to return the client when creating the session:
const session = function (number) {
// ...
return client;
};
@pedroslopez
i got new error when execute the /send route.
this my code
`var express = require('express')
var app = express()
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const wa = require('waweb-phi');
const fs = require(fs);
app.get('/scan/:id', function (req, res, next) {
var number = req.params.id ;
const session = function (number) {
console.log('number', number);
let session_file;
if (fs.existsSync(`./${number}.json`)) {
session_file = require(`./${number}.json`);
console.log('session_file', session_file);
}
const client = new wa({
puppeteer: {
headless: false,
userDataDir: __dirname + `/${number}`,
args: ['--no-sandbox']
},
session: session_file
});
client.initialize();
client.on(`qr`, (qr) => {
console.log('qr', qr);
});
client.on(`authenticated`, (session) => {
if (!fs.existsSync(`./${number}.json`)) {
fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(`Session stored`);
});
}
});
client.on(`auth_failure`, (msg) => {
console.log(`auth_failure`, msg);
});
client.on(`ready`, () => {
console.log(`ready`);
});
client.on(`message`, async msg => {
console.log('message', msg)
});
client.on(`disconnected`, (reason) => {
console.log(`disconnected`, reason);
});
return client;
};
new session('082113150495');
next();
});
app.get('/send', function (req, res, next) {
new session('082113150495');
client.sendMessage("[email protected]", test).then((r) => {
console.log("sendMessage",r)
})
});
app.listen(port, hostname, () => {
console.log(Server running at http://${hostname}:${port}/);
});`
@Marzuki5 I got the same error
let sessions = {};
const session = function (number) {
const SESSION_FILE_PATH = __dirname + `/../sessions/session_${number}.json`;
if (fs.existsSync(SESSION_FILE_PATH)) {
sessionData = require(SESSION_FILE_PATH);
}
const puppeteerOptions = {
session: sessionData,
puppeteer: {
//headless: false,
userDataDir: __dirname + `/../sessions/${number}`,
args: ['--no-sandbox', '--disable-setuid-sandbox']
}
};
// Use the saved values
sessions[number] = new Client(puppeteerOptions);
sessions[number].initialize();
// Save session values to the file upon successful auth
sessions[number].on('authenticated', (session) => {
sessionData = session;
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
if (err) console.log(err);
else console.log(`Session stored`);
});
});
// ...
return sessions[number];
};
session('1234567890');
md5-7ba4a4a7f04cecef6b07c4058500cf05
let from = '1234567890'
let to = '1212341234'
sessions[from].sendMessage(`55${to}@c.us`, content)
https://github.com/pedroslopez/whatsapp-web.js/issues/45#issuecomment-673041886
How to destroy / close session?
i got some error like this
(node:9104) UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Target closed.
at F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:208:63
at new Promise (<anonymous>)
at CDPSession.send (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:207:16)
at ExecutionContext._evaluateInternal (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:200:50)
at ExecutionContext.evaluateHandle (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:151:21)
at WaitTask.rerun (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\DOMWorld.js:528:37)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:9104) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
#45 (comment)
How to destroy / close session?
i got some error like this(node:9104) UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Target closed. at F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:208:63 at new Promise (<anonymous>) at CDPSession.send (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:207:16) at ExecutionContext._evaluateInternal (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:200:50) at ExecutionContext.evaluateHandle (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:151:21) at WaitTask.rerun (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\DOMWorld.js:528:37) at processTicksAndRejections (internal/process/task_queues.js:93:5) (node:9104) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:9104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
sessions[number].destroy();
delete sessions[number];
#45 (comment)
How to destroy / close session?
i got some error like this(node:9104) UnhandledPromiseRejectionWarning: Error: Protocol error (Runtime.callFunctionOn): Target closed. at F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:208:63 at new Promise (<anonymous>) at CDPSession.send (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\Connection.js:207:16) at ExecutionContext._evaluateInternal (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:200:50) at ExecutionContext.evaluateHandle (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\ExecutionContext.js:151:21) at WaitTask.rerun (F:\whatsapp-web.js\node_modules\puppeteer\lib\cjs\puppeteer\common\DOMWorld.js:528:37) at processTicksAndRejections (internal/process/task_queues.js:93:5) (node:9104) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:9104) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.sessions[number].destroy(); delete sessions[number];
I got the same error
let sessions = {}; const session = function (number) { const SESSION_FILE_PATH = __dirname + `/../sessions/session_${number}.json`; if (fs.existsSync(SESSION_FILE_PATH)) { sessionData = require(SESSION_FILE_PATH); } const puppeteerOptions = { session: sessionData, puppeteer: { //headless: false, userDataDir: __dirname + `/../sessions/${number}`, args: ['--no-sandbox', '--disable-setuid-sandbox'] } }; // Use the saved values sessions[number] = new Client(puppeteerOptions); sessions[number].initialize(); // Save session values to the file upon successful auth sessions[number].on('authenticated', (session) => { sessionData = session; fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) { if (err) console.log(err); else console.log(`Session stored`); }); }); // ... return sessions[number]; };session('1234567890');let from = '1234567890' let to = '1212341234' sessions[from].sendMessage(`55${to}@c.us`, content)
thnks for the answer, its work for me, but i have another problem, when i send messange with that function, my whatsapp messanger going force close. is that a bug ?
Most helpful comment