// Send message to group
// You can use chatID or group name, yea!
app.post('/send-group-message', [
body('id').custom((value, { req }) => {
if (!value && !req.body.name) {
throw new Error('Invalid value, you can use id or name');
}
return true;
}),
body('message').notEmpty(),
], async (req, res) => {
const errors = validationResult(req).formatWith(({
msg
}) => {
return msg;
});
if (!errors.isEmpty()) {
return res.status(422).json({
status: false,
message: errors.mapped()
});
}
let chatId = req.body.id;
const groupName = req.body.name;
const message = req.body.message;
// Find the group by name
if (!chatId) {
const group = await findGroupByName(groupName);
if (!group) {
return res.status(422).json({
status: false,
message: 'No group found with name: ' + groupName
});
}
chatId = group.id._serialized;
}
client.sendMessage(chatId, message).then(response => {
res.status(200).json({
status: true,
response: response
});
}).catch(err => {
res.status(500).json({
status: false,
response: err
});
});
});
// my custome functions
function getResourceWithRetry(url, maxRetries = 6, retryDelay = 1000) {
function attemptRequest(attempt) {
return axios.get(url, {
rejectUnauthorized: false,
responseType: 'arraybuffer'
})
.then(response => {
// Check if the response indicates success (status code 2xx)
if (response.status >= 200 && response.status < 300) {
return response;
}
// If not successful, throw an error to trigger the catch block
throw new Error(`Unsuccessful response: ${response.status}`);
})
.catch(error => {
// Check if the error is a 404 and there are remaining attempts
if (error.response && error.response.status === 404 && attempt < maxRetries) {
console.log(`Resource not found (attempt ${attempt + 1}/${maxRetries}). Retrying in ${retryDelay / 1000} seconds...`);
// Retry after a delay
return new Promise(resolve => setTimeout(() => resolve(attemptRequest(attempt + 1)), retryDelay));
}
// If not a 404 or no more attempts, reject the Promise with the error
console.log(">>>>>>>>>>>", error.message);
});
}
// Start the initial attempt
return attemptRequest(0);
}
server.listen(port, function () {
console.log('App running on : ' + port);
});
Browser Type
Google Chrome
WhatsApp Account Type
Standard
Does your WhatsApp account have multidevice enabled?
Is there an existing issue for this?
Describe the bug
Two chrome instance or process appeared in top command process list
Expected behavior
it should only creates one chrome process
Steps to Reproduce the Bug or Issue
just run nodejs code in pm2
Relevant Code
const { Client, MessageMedia, LocalAuth, NoAuth } = require('whatsapp-web.js'); const express = require('express'); const { body, validationResult } = require('express-validator'); const socketIO = require('socket.io'); const qrcode = require('qrcode'); const http = require('http'); const fs = require('fs'); // const { phoneNumberFormatter } = require('./helpers/formatter'); const fileUpload = require('express-fileupload'); const axios = require('axios');
//change const my_app_name = "nrtest" const app = express(); const server = http.createServer(app); const io = socketIO(server, { path: "/" + my_app_name + "/socket.io" });
const redis = require('redis'); const redis_client = redis.createClient();
const connect_redis = async () => {
}
connect_redis()
// Test the connection
const setRedisKeyValue = async (key, value) => { console.log(await redis_client.set(key, value)); }
const getRedisKeyValue = async (key) => { return await redis_client.get(key); }
// create cdn folder
fs.mkdir(
cdn/${my_app_name}
, (err) => { if (err) { console.log(err); } else { console.log('Folder created successfully!'); } });//const port = process.env.PORT || 7017; //change const port = 7000; const webhook_url = "localhost"; const cb_port = 4002
// NewEraLiFe
app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(fileUpload({ // debug: true }));
app.use(express.static('cdn/' + my_app_name));
var PROCESS_MEDIA_MESSAGE = function (data, filename) { // var SANITIZEd = SANITIZE_MSG(port,data) //const http = require("http") // console.log("filename:", filename); const new_data = JSON.stringify({ "data": data, "filename": filename, "app_name": my_app_name }) // const new_data = SANITIZEd
};
var SANITIZE_ACK = function (data) { return JSON.stringify({ ack: [{ id: data.id._serialized, from: data.id.remote, mdata: data, status: (data.ack == 1 ? 'sent' : (data.ack == 2 ? 'delivered' : 'viewed')) }], instanceId: port }); };
var PROCESS_MESSAGE = function (data) { // var SANITIZEd = SANITIZE_MSG(port,data) //const http = require("http") const new_data = JSON.stringify({ "data": data, "app_name": my_app_name }) // const new_data = SANITIZEd // console.log("sending", new_data) const options = { hostname: webhook_url, //"en6gta6u8epkt.x.pipedream.net", port: cb_port, //443, path: "/bot/wapi", method: "POST", bodu: new_data, headers: { "Content-Type": "application/json", // "Content-Length": new_data.length, "Content-Length": Buffer.byteLength(new_data, 'utf8'), }, } const req = http.request(options, res => { console.log(
statusCode text: ${res.statusCode}
)};
//Here will receive our our message var PROCESS_ACK = function (data) { //const http = require("http") // var SANITIZED = SANITIZE_ACK(data); console.log("data.hasMedia:", data.hasMedia); console.log("data.hasMedia:", data.isStatus);
};
var PROCESS_STATE = function (data) { // console.log("[STATE CHANGED] -", data); };
// const SESSION_FILE_PATH = ('/home/ketan/Desktop/l/whatsapp-api/Whats3API/Whats3API5/WhatsSessions/'+ port + '.json'); // let sessionCfg; // if (fs.existsSync(SESSION_FILE_PATH)) { // sessionCfg = require(SESSION_FILE_PATH); // }
app.get('/' + my_app_name + '', (req, res) => { res.sendFile('index.html', { root: __dirname }); });
let client; const setupClient = async () => {
} console.log(process.pid)
setupClient()
const downloadStoreMedia = async (msg) => {
}
// Socket IO io.on('connection', async function (socket) { console.log("got connnnn");
});
const deleteSessionFile = function () { const mysessionpath =
.wwebjs_auth/session-${my_app_name}
; fs.rmdir(mysessionpath, { recursive: true }, function (err) { if (err) return console.log(">>>>>>>>ERRRRRR<<<<<<< while deleting session file"); console.log('Session deleted!'); }); }const checkRegisteredNumber = async function (number) { const isRegistered = await client.isRegisteredUser(number); return isRegistered; }
// Send message app.post('/sendMessage', [ body('phone').notEmpty(), body('body').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) => { return msg; }); // console.log(req.body); if (!errors.isEmpty()) { return res.status(422).json({ status: false, message: errors.mapped() }); }
});
// Send media app.post('/sendFile', async (req, res) => { // const number = phoneNumberFormatter(req.body.phone); const number = req.body.phone.replace("+", "") console.log(number, "number");
});
// app.post('/sendLocalFiles', async (req, res))=>{ // const { MessageMedia } = require('whatsapp-web.js'); // const media = MessageMedia.fromFilePath('/home/ketan/Desktop/lifeel/whatsapp-api/Whats3API/Whats3API5/public/cdn/7015/sample.pdf'); // chat.sendMessage(media); // }
const findGroupByName = async function (name) { const group = await client.getChats().then(chats => { return chats.find(chat => chat.isGroup && chat.name.toLowerCase() == name.toLowerCase() ); }); return group; }
// Send message to group // You can use chatID or group name, yea! app.post('/send-group-message', [ body('id').custom((value, { req }) => { if (!value && !req.body.name) { throw new Error('Invalid value, you can use
id
orname
'); } return true; }), body('message').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ msg }) => { return msg; });});
// my custome functions
function getResourceWithRetry(url, maxRetries = 6, retryDelay = 1000) { function attemptRequest(attempt) { return axios.get(url, { rejectUnauthorized: false, responseType: 'arraybuffer' }) .then(response => { // Check if the response indicates success (status code 2xx) if (response.status >= 200 && response.status < 300) { return response; }
}
server.listen(port, function () { console.log('App running on : ' + port); });
Browser Type
Google Chrome
WhatsApp Account Type
Standard
Does your WhatsApp account have multidevice enabled?
Yes, I am using Multi Device
Environment
Distributor ID: Ubuntu Description: Ubuntu 22.04.3 LTS Release: 22.04 Codename: jammy
latest whatsapp-web.js version
WhatsApp Web version is in the code itself
nodejs version : v16.14.0
Additional context
No response