Skip to content

For Whatsapp Web Version 2.3000.1032157364 getChats() throws error and chats are not scrapped #5733

Description

@BavithiranOneMindIndia

Is there an existing issue for this?

  • I have searched the existing issues.

Is this a problem caused by your code, or is it specifically because of the library?

  • I have double-checked my code carefully.

Describe the bug.

Error
❌ Error in /session/:id/run-groups: t: t
at #evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\ExecutionContext.js:391:56)
at async ExecutionContext.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\ExecutionContext.js:277:16)
at async IsolatedWorld.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\IsolatedWorld.js:100:16)
at async CdpFrame.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\api\Frame.js:362:20)
at async CdpPage.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\api\Page.js:826:20)
at async Client.getChats (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\whatsapp-web.js\src\Client.js:1155:23)
at async D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\index.js:1057:19

Note : this happen for specific WhatsApp Account

whatsapp-web.js
Version tested with
1.34.4
1.34.5-alpha.3

Expected Behavior

As a user it needs to scrap groups list with id
const chats = await s.client.getChats(); this itseld throw error

t: t
at #evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\ExecutionContext.js:391:56)
at async ExecutionContext.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\ExecutionContext.js:277:16)
at async IsolatedWorld.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\IsolatedWorld.js:100:16)
at async CdpFrame.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\api\Frame.js:362:20)
at async CdpPage.evaluate (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\puppeteer-core\lib\cjs\puppeteer\api\Page.js:826:20)
at async Client.getChats (D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\node_modules\whatsapp-web.js\src\Client.js:1155:23)
at async D:\ProjectAutomationFolder\MindConnect\whatsapp-membercount-scraper\index.js:1057:19

Steps to Reproduce the Bug or Issue

Scan the whatsapp Account and it will be Loaded and run run-groups for to scrap group

Code:
`// Export groups (unchanged except minor helpers)
app.post("/session/:id/run-groups", async (req, res) => {
const { id } = req.params;
const s = sessions[id];
if (!s) return res.status(404).json({ error: "Session not loaded" });
if (s.error) return res.status(500).json({ error: s.error });
if (!s.isReady) return res.status(401).json({ error: "Session not authenticated" });

const hitApiRaw = req.body?.hitApi ?? req.query?.hitApi;
const hitApi = hitApiRaw === undefined ? true : (String(hitApiRaw).toLowerCase() !== 'false' && hitApiRaw !== '0');

const API_BASE_URL = (process.env.API_BASE_URL && process.env.API_BASE_URL.replace(//$/, ""))
|| (process.env.KEYCLOAK_BASEURL && process.env.KEYCLOAK_BASEURL.replace(//$/, ""))
|| http://127.0.0.1:${PORT};

function extractRawParticipantId(part) {
if (!part) return null;
if (typeof part === 'string' && part.trim()) return part.trim();
if (part.id && typeof part.id === 'object' && typeof part.id._serialized === 'string') return part.id._serialized;
if (part.id && typeof part.id === 'string') return part.id;
if (part.user && typeof part.user === 'string') return part.user;
if (part.jid && typeof part.jid === 'string') return part.jid;
if (typeof part._serialized === 'string') return part._serialized;
return null;
}
function sanitizeParticipantId(rawId) {
if (!rawId) return null;
let p = String(rawId);
p = p.replace(/@c\.us$/i, "")
.replace(/@s\.whatsapp\.net$/i, "")
.replace(/@lid$/i, "")
.replace(/\s+/g, "");
const digits = p.replace(/\D/g, "");
return digits || null;
}

function csvEscape(field) {
if (field === null || field === undefined) return '';
const s = String(field);
if (/[",\r\n]/.test(s)) return "${s.replace(/"/g, '""')}";
return s;
}

// small helpers used earlier
function safeJsonifyValueLocal(v) {
if (typeof v === 'bigint') {
const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
return (v <= maxSafe && v >= -maxSafe) ? Number(v) : v.toString();
}
return v;
}
function safeJsonifyRowLocal(row) {
return Object.fromEntries(Object.entries(row).map(([k, v]) => [k, safeJsonifyValueLocal(v)]));
}

const API_DELAY_MS = 1000;
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

try {
if (hitApi) {
try {
await ensureValidKeycloakToken();
} catch (e) {
return res.status(401).json({ error: "Keycloak token missing or refresh failed. Please authenticate using /auth/login.", details: e.message });
}
}

const chats = await s.client.getChats();
const groups = chats.filter(c => c.isGroup);

const excelRows = [];
const groupData = {};
const apiResults = [];

const runDateTime = new Date().toISOString();
const authHeader = keycloakToken?.access_token ? `Bearer ${keycloakToken.access_token}` : null;

for (const g of groups) {
  try {
    const full = await s.client.getChatById(g.id._serialized);
    const groupId = g.id?._serialized || String(g.id || '');
    const groupName = (full && full.name) || g.name || groupId;

    const rawParticipants = Array.isArray(full?.participants) ? full.participants : (Array.isArray(full?.members) ? full.members : []);
    const rawList = rawParticipants.length ? rawParticipants : (g.participants || []);

    const participantsNormalized = rawList
      .map(p => extractRawParticipantId(p))
      .filter(Boolean)
      .map(r => sanitizeParticipantId(r))
      .filter(Boolean);

    groupData[groupName] = participantsNormalized;

    if (participantsNormalized.length > 0) {
      participantsNormalized.forEach(participant => {
        excelRows.push({ "Group ID": groupId, "Group Name": groupName, "Participants": participant });
      });
    } else {
      excelRows.push({ "Group ID": groupId, "Group Name": groupName, "Participants": "" });
    }

    const payload = {
      adminNumber: id,
      groupName,
      groupUsersPhoneNumber: participantsNormalized,
      runDateTime
    };

    console.log("➡️ Payload for group:", groupName, JSON.stringify(payload));

    if (hitApi) {
      try {
        const resp = await fetch(`${API_BASE_URL}/GroupAdmin/addOrUpdateGroupAdminUsers`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": authHeader
          },
          body: JSON.stringify(payload)
        });

        const text = await resp.text().catch(() => null);
        let body;
        try { body = text ? JSON.parse(text) : null; } catch { body = text; }

        apiResults.push({ groupName, status: resp.status, ok: resp.ok, response: body });

        console.log(`⬅️ API response for "${groupName}":`, resp.status, body);
        if (!resp.ok) console.warn(`⚠️ API returned ${resp.status} for group "${groupName}":`, body);
      } catch (apiErr) {
        console.error(`❌ API call failed for group "${groupName}":`, apiErr?.message || apiErr);
        apiResults.push({ groupName, status: "network_error", ok: false, error: apiErr?.message || String(apiErr) });
      }

      await sleep(API_DELAY_MS);
    } else {
      apiResults.push({ groupName, status: "SKIPPED", ok: true, response: "API call skipped per hitApi=false" });
    }

  } catch (innerErr) {
    console.warn("Failed to process group", g.id?._serialized || g.id, innerErr?.message || innerErr);
  }
}

// Write Excel
const ws = XLSX.utils.json_to_sheet(excelRows);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Groups");

const outDir = path.join(SESSIONS_DIR, id);
if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true });
const outFile = path.join(outDir, "groups_participants.xlsx");
XLSX.writeFile(wb, outFile);

const publicUrl = `http://127.0.0.1:${PORT}/sessions/${encodeURIComponent(id)}/groups_participants.xlsx`;

res.json({
  status: "success",
  runDateTime,
  hitApi,
  file: publicUrl,
  groups: Object.keys(groupData).length,
  totalParticipants: excelRows.length,
  apiSummary: { apiBaseUrl: API_BASE_URL, results: apiResults }
});

} catch (err) {
console.error("❌ Error in /session/:id/run-groups:", err);
res.status(500).json({ error: Failed to export groups: ${err.message} });
}
});`

this code throw error

but code Load the account and authenticate actually works

// Initialize session (load existing) app.post("/session/:id/init", (req, res) => { const { id } = req.params; if (sessions[id]) return res.json({ status: "already_loaded", id, isReady: sessions[id].isReady, error: sessions[id].error }); const session = createSession(id); res.json({ status: "loaded", id, error: session.error }); });

`function createSession(sessionId) {
if (sessions[sessionId]) return sessions[sessionId];

const sessionExportDir = path.join(SESSIONS_DIR, sessionId);
const sessionAuthDir = path.join(AUTH_DIR, session-${sessionId});
[sessionExportDir, sessionAuthDir].forEach(dir => { if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true, mode: 0o755 }); });

const WEB_CACHE_MODE = process.env.WEB_CACHE_MODE || "none"; // "local", "none", or "remote"

try {
const client = new Client({
puppeteer: puppeteerOptions(),
authStrategy: new LocalAuth({ clientId: sessionId, dataPath: AUTH_DIR }),
webVersionCache:
WEB_CACHE_MODE === "none"
? { type: "none" }
: WEB_CACHE_MODE === "remote"
? { type: "remote", remotePath: "https://raw.githubusercontent.com/wppconnect-team/wa-version/main/html/2.3000.1032157364.html" }
: { type: "local", path: CACHE_FILE }
});

sessions[sessionId] = { client, isReady: false, lastQr: null, error: null };

client.on("qr", (qr) => {
  console.log(`📲 QR generated for ${sessionId}`);
  sessions[sessionId].lastQr = qr;
  sessions[sessionId].error = null;
});

client.on("ready", () => {
  console.log(`✅ ${sessionId} authenticated & ready`);
  sessions[sessionId].isReady = true;
  sessions[sessionId].error = null;
});

client.on("auth_failure", msg => {
  console.error(`❌ Auth failure for ${sessionId}:`, msg);
  sessions[sessionId].isReady = false;
  sessions[sessionId].error = `Authentication failed: ${msg}`;
});

client.on("disconnected", reason => {
  console.warn(`⚠️ ${sessionId} disconnected:`, reason);
  sessions[sessionId].isReady = false;
  sessions[sessionId].error = `Disconnected: ${reason}`;
});

client.on("error", error => {
  console.error(`❌ Client error for ${sessionId}:`, error);
  sessions[sessionId].error = error?.message || String(error);
});

client.initialize().catch(error => {
  console.error(`❌ Failed to initialize ${sessionId}:`, error);
  sessions[sessionId].error = error?.message || String(error);
});

return sessions[sessionId];

} catch (error) {
console.error(❌ Error creating session ${sessionId}:, error);
sessions[sessionId] = { client: null, isReady: false, lastQr: null, error: error.message };
return sessions[sessionId];
}
}`

WhatsApp Account Type

Standard

Browser Type

Chrome

Operation System Type

Windows

Phone OS Type

Android

WhatsApp-Web.js Version

"whatsapp-web.js": "^1.34.4",

WhatsApp Web Version

Version 2.3000.1032157364

Node.js Version

v22.18.0

Authentication Strategy

LocalAuth

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething is broken

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions