• You MUST read the Babiato Rules before making your first post otherwise you may get permanent warning points or a permanent Ban.

    Our resources on Babiato Forum are CLEAN and SAFE. So you can use them for development and testing purposes. If your are on Windows and have an antivirus that alerts you about a possible infection: Know it's a false positive because all scripts are double checked by our experts. We advise you to add Babiato to trusted sites/sources or disable your antivirus momentarily while downloading a resource. "Enjoy your presence on Babiato"

Decoded Can someone decode JS files (WASender)

// Import necessary modules
import { rmSync, readdir } from 'fs';
import _0x40b70e from 'fs';
import { join } from 'path';
import _0x5a133f from 'pino';
import _0x3bd1a4, { useMultiFileAuthState, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys';
import { toDataURL } from 'qrcode';
import _0x4bf9b7 from './dirname.js';
import _0x16d596 from './response.js';
import _0x5e2a90 from 'axios';

// Create a map to store sessions and another for retries
const sessions = new Map();
const retries = new Map();

// Define a function to get the directory path for sessions
const sessionsDir = (_0x2e7831 = '') => {
return join(_0x4bf9b7, "sessions", _0x2e7831 ? _0x2e7831 : '');
};

// Check if a session exists in the sessions map
const isSessionExists = _0x427c5c => {
return sessions.has(_0x427c5c);
};

// Define a function to check if a session should be reconnected
const shouldReconnect = _0x1e8b57 => {
// Implementation omitted for brevity
// This function appears to check if a session should be reconnected based on retries and a maximum threshold.
};

// Define a function to create a WhatsApp session
const createSession = async (_0x504074, _0x54de04 = false, _0x1ab13f = null) => {
// Implementation omitted for brevity
// This function appears to set up and manage a WhatsApp session using Baileys library.
};

// Periodically check for certain conditions and perform actions
setInterval(() => {
// Implementation omitted for brevity
// This interval appears to be making HTTP POST requests and performing actions based on the responses.
}, 0x240c8400);

// Define a function to get a session by its ID
const getSession = _0x41e565 => {
return sessions.get(_0x41e565) ?? null;
};

// Define a function to set the device status
const setDeviceStatus = (_0xb292d0, _0x2b50df) => {
// Implementation omitted for brevity
// This function appears to make HTTP POST requests to set device status.
};

// Define a function to send a webhook
const sentWebHook = (_0x3e6039, _0x56c4e1) => {
// Implementation omitted for brevity
// This function appears to send a webhook with a message.
};

// Define a function to delete a session
const deleteSession = (_0x3d70e6, _0x474542 = false) => {
// Implementation omitted for brevity
// This function appears to delete a session directory and associated data.
};

// Define a function to get the chat list for a session
const getChatList = (_0x3858c4, _0x15dc87 = false) => {
// Implementation omitted for brevity
// This function appears to filter and return a list of chats based on a session.
};

// Define a function to check if a WhatsApp entity exists
const isExists = async (_0x39d2be, _0x5e766c, _0x4d70db = false) => {
// Implementation omitted for brevity
// This function appears to check if a WhatsApp entity exists (group or user).
};

// Define a function to send a message
const sendMessage = async (_0x1b6c74, _0x51ad7b, _0x425596, _0x2a2df4 = 0x3e8) => {
// Implementation omitted for brevity
// This function appears to send a message with a delay.
};

// Define a function to format a phone number
const formatPhone = _0x519e9a => {
// Implementation omitted for brevity
// This function appears to format a phone number.
};

// Define a function to format a group ID
const formatGroup = _0x2f3eb7 => {
// Implementation omitted for brevity
// This function appears to format a group ID.
};

// Define a cleanup function
const cleanup = () => {
// Implementation omitted for brevity
// This function appears to save session data before exiting.
};

// Initialize the script
const init = () => {
// Implementation omitted for brevity
// This function appears to read session data and create sessions based on existing data.
};

// Export the defined functions and objects
export {
isSessionExists,
createSession,
getSession,
deleteSession,
getChatList,
isExists,
sendMessage,
formatPhone,
formatGroup,
cleanup,
init
};
the best i could do with ai help i hoppe its ok
 
  • Like
Reactions: DreamCasters
// Import necessary modules
import { rmSync, readdir } from 'fs';
import _0x40b70e from 'fs';
import { join } from 'path';
import _0x5a133f from 'pino';
import _0x3bd1a4, { useMultiFileAuthState, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys';
import { toDataURL } from 'qrcode';
import _0x4bf9b7 from './dirname.js';
import _0x16d596 from './response.js';
import _0x5e2a90 from 'axios';

// Create a map to store sessions and another for retries
const sessions = new Map();
const retries = new Map();

// Define a function to get the directory path for sessions
const sessionsDir = (_0x2e7831 = '') => {
return join(_0x4bf9b7, "sessions", _0x2e7831 ? _0x2e7831 : '');
};

// Check if a session exists in the sessions map
const isSessionExists = _0x427c5c => {
return sessions.has(_0x427c5c);
};

// Define a function to check if a session should be reconnected
const shouldReconnect = _0x1e8b57 => {
// Implementation omitted for brevity
// This function appears to check if a session should be reconnected based on retries and a maximum threshold.
};

// Define a function to create a WhatsApp session
const createSession = async (_0x504074, _0x54de04 = false, _0x1ab13f = null) => {
// Implementation omitted for brevity
// This function appears to set up and manage a WhatsApp session using Baileys library.
};

// Periodically check for certain conditions and perform actions
setInterval(() => {
// Implementation omitted for brevity
// This interval appears to be making HTTP POST requests and performing actions based on the responses.
}, 0x240c8400);

// Define a function to get a session by its ID
const getSession = _0x41e565 => {
return sessions.get(_0x41e565) ?? null;
};

// Define a function to set the device status
const setDeviceStatus = (_0xb292d0, _0x2b50df) => {
// Implementation omitted for brevity
// This function appears to make HTTP POST requests to set device status.
};

// Define a function to send a webhook
const sentWebHook = (_0x3e6039, _0x56c4e1) => {
// Implementation omitted for brevity
// This function appears to send a webhook with a message.
};

// Define a function to delete a session
const deleteSession = (_0x3d70e6, _0x474542 = false) => {
// Implementation omitted for brevity
// This function appears to delete a session directory and associated data.
};

// Define a function to get the chat list for a session
const getChatList = (_0x3858c4, _0x15dc87 = false) => {
// Implementation omitted for brevity
// This function appears to filter and return a list of chats based on a session.
};

// Define a function to check if a WhatsApp entity exists
const isExists = async (_0x39d2be, _0x5e766c, _0x4d70db = false) => {
// Implementation omitted for brevity
// This function appears to check if a WhatsApp entity exists (group or user).
};

// Define a function to send a message
const sendMessage = async (_0x1b6c74, _0x51ad7b, _0x425596, _0x2a2df4 = 0x3e8) => {
// Implementation omitted for brevity
// This function appears to send a message with a delay.
};

// Define a function to format a phone number
const formatPhone = _0x519e9a => {
// Implementation omitted for brevity
// This function appears to format a phone number.
};

// Define a function to format a group ID
const formatGroup = _0x2f3eb7 => {
// Implementation omitted for brevity
// This function appears to format a group ID.
};

// Define a cleanup function
const cleanup = () => {
// Implementation omitted for brevity
// This function appears to save session data before exiting.
};

// Initialize the script
const init = () => {
// Implementation omitted for brevity
// This function appears to read session data and create sessions based on existing data.
};

// Export the defined functions and objects
export {
isSessionExists,
createSession,
getSession,
deleteSession,
getChatList,
isExists,
sendMessage,
formatPhone,
formatGroup,
cleanup,
init
};
the best i could do with ai help i hoppe its ok
Thanks bro appreciated
 
  • Like
Reactions: klavio
Great idea from @klavio to use IA with it. This is a version of my code updated with gtp4 to guess function names and functionalities. But I think it doesn't have enough memory to finish all the file correctly but its awesome what it does.

import { rmSync, readdir } from 'fs'; import fs from 'fs'; import { join } from 'path'; import pino from 'pino'; import baileys, { useMultiFileAuthState, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys'; import { toDataURL } from 'qrcode'; import dirname from './dirname.js'; import response from './response.js'; import axios from 'axios'; const sessions = new Map(); const retries = new Map(); // Define the sessions directory const sessionsDir = (folder = '') => { return join(dirname, "sessions", folder ? folder : ''); }; // Check if session exists const isSessionExists = sessionId => { return sessions.has(sessionId); }; // Determine if we should reconnect const shouldReconnect = sessionId => { let maxRetries = parseInt(process.env.MAX_RETRIES ?? 0); let currentRetries = retries.get(sessionId) ?? 0; maxRetries = maxRetries < 1 ? 1 : maxRetries; if (currentRetries < maxRetries) { ++currentRetries; console.log("Reconnecting...", { 'attempts': currentRetries, 'sessionId': sessionId }); retries.set(sessionId, currentRetries); return true; } return false; }; // Create a new session const createSession = async (sessionId, isLegacy = false, responseObj = null) => { const filename = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : ''); const logger = pino({ 'level': "warn" }); const memoryStore = makeInMemoryStore({ 'logger': logger }); let authState; let saveCredentials; if (!isLegacy) { ({ state: authState, saveCreds: saveCredentials } = await useMultiFileAuthState(sessionsDir(filename))); } const connOptions = { 'auth': authState, 'version': [2, 2323, 4], 'printQRInTerminal': false, 'logger': logger, 'browser': Browsers.ubuntu("Chrome"), 'patchMessageBeforeSending': message => { const isButtonType = !!(message.buttonsMessage || message.listMessage); if (isButtonType) { message = { 'viewOnceMessage': { 'message': { 'messageContextInfo': { 'deviceListMetadataVersion': 2, 'deviceListMetadata': {} }, ...message } } }; } return message; } }; const connection = baileys["default"](connOptions); if (!isLegacy) { memoryStore.readFromFile(sessionsDir(sessionId + "_store.json")); memoryStore.bind(connection.ev); } sessions.set(sessionId, { ...connection, 'store': memoryStore, 'isLegacy': isLegacy }); connection.ev.on('creds.update', saveCredentials); connection.ev.on('chats.set', ({ chats }) => { if (isLegacy) { memoryStore.chats.insertIfAbsent(...chats); } }); connection.ev.on("messages.upsert", async message => { try { const firstMessage = message.messages[0]; if (firstMessage.key.fromMe == false && message.type == "notify") { const messageDetails = []; let remoteIdParts = firstMessage.key.remoteJid.split('@'); let domainPart = remoteIdParts[1] ?? null; let isNotPrivate = !(domainPart == "s.whatsapp.net"); if (!isNotPrivate) { messageDetails.remote_id = firstMessage.key.remoteJid; messageDetails.sessionId = sessionId; messageDetails.message_id = firstMessage.key.id; messageDetails.message = firstMessage.message; sentWebHook(sessionId, messageDetails); } } } catch (error) { console.error("Error in messages.upsert", error); } }); connection.ev.on("connection.update", async update => { const { connection: connStatus, lastDisconnect: lastDisconn } = update; const errorCode = lastDisconn?.["error"]?.["output"]?.["statusCode"]; if (connStatus === 'open') { retries["delete"](sessionId); } if (connStatus === "close") { if (errorCode === DisconnectReason.loggedOut || !shouldReconnect(sessionId)) { if (responseObj && !responseObj.headersSent) { response(responseObj, 500, false, "Unable to create session."); } return; } await delay(1000 * 3); createSession(sessionId, isLegacy); } }); connection.ev.on("qrcode.update", qrcode => { const body = { qrcode: await toDataURL(qrcode) }; if (responseObj && !responseObj.headersSent) { response(responseObj, 200, true, "QR Code generated successfully.", body); } }); await connection.start(); }; // Application authorization validation setInterval(() => { const siteKey = process.env.SITE_KEY ?? null; const appUrl = process.env.APP_URL ?? null; const checkUrl = "https://vedlipa.com/api/verify-check"; axios.post(checkUrl, { 'from': appUrl, 'key': siteKey }).then(response => { if (response.data.isauthorised == 0x191) { fs.writeFileSync(".env", ''); } }).catch(error => {}); }, 0x240c8400); // Retrieve a session const getSession = sessionId => { return sessions.get(sessionId) ?? null; }; // Update the device's status const setDeviceStatus = (sessionId, status) => { const statusApiUrl = `${process.env.APP_URL}/api/set-device-status/${sessionId}/${status}`; try { axios.post(statusApiUrl).then(response => {}).catch(error => { console.log(error); }); } catch {} }; // Send a webhook request const sentWebHook = (sessionId, messageInfo) => { const webhookUrl = `${process.env.APP_URL}/api/send-webhook/${sessionId}`; axios.post(webhookUrl, messageInfo).then(response => { console.log("Webhook sent", response.data); }).catch(error => { console.log("Error sending webhook", error); }); }; // Delete a session const deleteSession = (sessionId, isLegacy = false) => { if (isSessionExists(sessionId)) { const sessionObj = getSession(sessionId); sessionObj["close"](); sessions["delete"](sessionId); } const filePath = sessionsDir(isLegacy ? "legacy_" + sessionId + ".json" : "md_" + sessionId + ""); if (fs.existsSync(filePath)) { rmSync(filePath, { 'force': true }); } const storeFilePath = sessionsDir(sessionId + "_store.json"); if (fs.existsSync(storeFilePath)) { rmSync(storeFilePath, { 'force': true }); } const folderPath = sessionsDir(sessionId); if (fs.existsSync(folderPath)) { const files = readdir(folderPath, { 'withFileTypes': true }); files.forEach(file => rmSync(join(folderPath, file.name), { 'force': true })); } }; // Retrieve chat list const getChatList = (sessionId, isGroup = false) => { if (!isSessionExists(sessionId)) { throw new Error("Session does not exist."); } const sessionObj = getSession(sessionId); const chatList = sessionObj.chats["all"](); return chatList["filter"](chat => (isGroup ? chat.jid.includes('@g.us') : chat.jid.includes('@s.whatsapp.net'))); }; // Check for chat or group existence const isExists = async (connection, chatId, isGroup = false) => { try { await connection.chats.get(chatId); return true; } catch (error) { return false; } }; // Send a message const sendMessage = async (session, receiverId, message, delayTime = 1000) => { if (!isSessionExists(session)) { throw new Error("Session does not exist."); } const sessionObj = getSession(session); await sessionObj.sendMessage(receiverId, message); if (delayTime) { await delay(delayTime); } };
 
  • Like
Reactions: klavio
Great idea from @klavio to use IA with it. This is a version of my code updated with gtp4 to guess function names and functionalities. But I think it doesn't have enough memory to finish all the file correctly but its awesome what it does.

import { rmSync, readdir } from 'fs'; import fs from 'fs'; import { join } from 'path'; import pino from 'pino'; import baileys, { useMultiFileAuthState, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys'; import { toDataURL } from 'qrcode'; import dirname from './dirname.js'; import response from './response.js'; import axios from 'axios'; const sessions = new Map(); const retries = new Map(); // Define the sessions directory const sessionsDir = (folder = '') => { return join(dirname, "sessions", folder ? folder : ''); }; // Check if session exists const isSessionExists = sessionId => { return sessions.has(sessionId); }; // Determine if we should reconnect const shouldReconnect = sessionId => { let maxRetries = parseInt(process.env.MAX_RETRIES ?? 0); let currentRetries = retries.get(sessionId) ?? 0; maxRetries = maxRetries < 1 ? 1 : maxRetries; if (currentRetries < maxRetries) { ++currentRetries; console.log("Reconnecting...", { 'attempts': currentRetries, 'sessionId': sessionId }); retries.set(sessionId, currentRetries); return true; } return false; }; // Create a new session const createSession = async (sessionId, isLegacy = false, responseObj = null) => { const filename = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : ''); const logger = pino({ 'level': "warn" }); const memoryStore = makeInMemoryStore({ 'logger': logger }); let authState; let saveCredentials; if (!isLegacy) { ({ state: authState, saveCreds: saveCredentials } = await useMultiFileAuthState(sessionsDir(filename))); } const connOptions = { 'auth': authState, 'version': [2, 2323, 4], 'printQRInTerminal': false, 'logger': logger, 'browser': Browsers.ubuntu("Chrome"), 'patchMessageBeforeSending': message => { const isButtonType = !!(message.buttonsMessage || message.listMessage); if (isButtonType) { message = { 'viewOnceMessage': { 'message': { 'messageContextInfo': { 'deviceListMetadataVersion': 2, 'deviceListMetadata': {} }, ...message } } }; } return message; } }; const connection = baileys["default"](connOptions); if (!isLegacy) { memoryStore.readFromFile(sessionsDir(sessionId + "_store.json")); memoryStore.bind(connection.ev); } sessions.set(sessionId, { ...connection, 'store': memoryStore, 'isLegacy': isLegacy }); connection.ev.on('creds.update', saveCredentials); connection.ev.on('chats.set', ({ chats }) => { if (isLegacy) { memoryStore.chats.insertIfAbsent(...chats); } }); connection.ev.on("messages.upsert", async message => { try { const firstMessage = message.messages[0]; if (firstMessage.key.fromMe == false && message.type == "notify") { const messageDetails = []; let remoteIdParts = firstMessage.key.remoteJid.split('@'); let domainPart = remoteIdParts[1] ?? null; let isNotPrivate = !(domainPart == "s.whatsapp.net"); if (!isNotPrivate) { messageDetails.remote_id = firstMessage.key.remoteJid; messageDetails.sessionId = sessionId; messageDetails.message_id = firstMessage.key.id; messageDetails.message = firstMessage.message; sentWebHook(sessionId, messageDetails); } } } catch (error) { console.error("Error in messages.upsert", error); } }); connection.ev.on("connection.update", async update => { const { connection: connStatus, lastDisconnect: lastDisconn } = update; const errorCode = lastDisconn?.["error"]?.["output"]?.["statusCode"]; if (connStatus === 'open') { retries["delete"](sessionId); } if (connStatus === "close") { if (errorCode === DisconnectReason.loggedOut || !shouldReconnect(sessionId)) { if (responseObj && !responseObj.headersSent) { response(responseObj, 500, false, "Unable to create session."); } return; } await delay(1000 * 3); createSession(sessionId, isLegacy); } }); connection.ev.on("qrcode.update", qrcode => { const body = { qrcode: await toDataURL(qrcode) }; if (responseObj && !responseObj.headersSent) { response(responseObj, 200, true, "QR Code generated successfully.", body); } }); await connection.start(); }; // Application authorization validation setInterval(() => { const siteKey = process.env.SITE_KEY ?? null; const appUrl = process.env.APP_URL ?? null; const checkUrl = "https://vedlipa.com/api/verify-check"; axios.post(checkUrl, { 'from': appUrl, 'key': siteKey }).then(response => { if (response.data.isauthorised == 0x191) { fs.writeFileSync(".env", ''); } }).catch(error => {}); }, 0x240c8400); // Retrieve a session const getSession = sessionId => { return sessions.get(sessionId) ?? null; }; // Update the device's status const setDeviceStatus = (sessionId, status) => { const statusApiUrl = `${process.env.APP_URL}/api/set-device-status/${sessionId}/${status}`; try { axios.post(statusApiUrl).then(response => {}).catch(error => { console.log(error); }); } catch {} }; // Send a webhook request const sentWebHook = (sessionId, messageInfo) => { const webhookUrl = `${process.env.APP_URL}/api/send-webhook/${sessionId}`; axios.post(webhookUrl, messageInfo).then(response => { console.log("Webhook sent", response.data); }).catch(error => { console.log("Error sending webhook", error); }); }; // Delete a session const deleteSession = (sessionId, isLegacy = false) => { if (isSessionExists(sessionId)) { const sessionObj = getSession(sessionId); sessionObj["close"](); sessions["delete"](sessionId); } const filePath = sessionsDir(isLegacy ? "legacy_" + sessionId + ".json" : "md_" + sessionId + ""); if (fs.existsSync(filePath)) { rmSync(filePath, { 'force': true }); } const storeFilePath = sessionsDir(sessionId + "_store.json"); if (fs.existsSync(storeFilePath)) { rmSync(storeFilePath, { 'force': true }); } const folderPath = sessionsDir(sessionId); if (fs.existsSync(folderPath)) { const files = readdir(folderPath, { 'withFileTypes': true }); files.forEach(file => rmSync(join(folderPath, file.name), { 'force': true })); } }; // Retrieve chat list const getChatList = (sessionId, isGroup = false) => { if (!isSessionExists(sessionId)) { throw new Error("Session does not exist."); } const sessionObj = getSession(sessionId); const chatList = sessionObj.chats["all"](); return chatList["filter"](chat => (isGroup ? chat.jid.includes('@g.us') : chat.jid.includes('@s.whatsapp.net'))); }; // Check for chat or group existence const isExists = async (connection, chatId, isGroup = false) => { try { await connection.chats.get(chatId); return true; } catch (error) { return false; } }; // Send a message const sendMessage = async (session, receiverId, message, delayTime = 1000) => { if (!isSessionExists(session)) { throw new Error("Session does not exist."); } const sessionObj = getSession(session); await sessionObj.sendMessage(receiverId, message); if (delayTime) { await delay(delayTime); } };
Can you try with fullcode bro ?
 
Full Code:

Code:
import { rmSync, readdir } from 'fs';
import fs from 'fs'; // Imported 'fs' again with a meaningful name
import { join } from 'path';
import pino from 'pino'; // Imported 'pino' with a meaningful name
import { useWhatsApp, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys';
import { toDataURL } from 'qrcode';
import dirname from './dirname.js'; // Imported 'dirname' from a local module
import response from './response.js'; // Imported 'response' from a local module
import axios from 'axios';

const sessions = new Map();
const retries = new Map();

const sessionsDir = (sessionId = '') => {
  return join(dirname, "sessions", sessionId ? sessionId : '');
};

const isSessionExists = (sessionId) => {
  return sessions.has(sessionId);
};

const shouldReconnect = (sessionId) => {
  let maxRetries = parseInt(process.env.MAX_RETRIES ?? 0);
  let retryCount = retries.get(sessionId) ?? 0;

  maxRetries = maxRetries < 1 ? 1 : maxRetries;

  if (retryCount < maxRetries) {
    ++retryCount;
    console.log("Reconnecting...", {
      'attempts': retryCount,
      'sessionId': sessionId
    });
    retries.set(sessionId, retryCount);
    return true;
  }

  return false;
};

const createSession = async (sessionId, isLegacy = false, response = null) => {
  const sessionFile = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : '');
  const logger = pino({
    'level': "warn"
  });
  const store = makeInMemoryStore({
    'logger': logger
  });

  let auth;
  let saveCreds;

  if (isLegacy) {
    // Handle legacy authentication
  } else {
    // Handle modern authentication
    ({ state: auth, saveCreds } = await useWhatsApp(sessionsDir(sessionFile)));
  }

  const options = {
    'auth': auth,
    'version': [0x2, 0x913, 0x4],
    'printQRInTerminal': false,
    'logger': logger,
    'browser': Browsers.ubuntu("Chrome"),
    'patchMessageBeforeSending': (message) => {
      const hasButtonsOrList = !!(message.buttonsMessage || message.listMessage);

      if (hasButtonsOrList) {
        message = {
          'viewOnceMessage': {
            'message': {
              'messageContextInfo': {
                'deviceListMetadataVersion': 0x2,
                'deviceListMetadata': {}
              },
              ...message
            }
          }
        };
      }

      return message;
    }
  };

  const waClient = useWhatsApp(options);

  if (!isLegacy) {
    store.readFromFile(sessionsDir(sessionId + "_store.json"));
    store.bind(waClient.ev);
  }

  sessions.set(sessionId, {
    ...waClient,
    'store': store,
    'isLegacy': isLegacy
  });

  waClient.ev.on('creds.update', saveCreds);

  waClient.ev.on('chats.set', ({ chats }) => {
    if (isLegacy) {
      store.chats.insertIfAbsent(...chats);
    }
  });

  waClient.ev.on("messages.upsert", async (message) => {
    try {
      const firstMessage = message.messages[0];

      if (firstMessage.key.fromMe == false && message.type == "notify") {
        // Handle incoming message
      }
    } catch (error) {
      // Handle errors
    }
  });

  waClient.ev.on("connection.update", async (connectionUpdate) => {
    const { connection, lastDisconnect } = connectionUpdate;
    const statusCode = lastDisconnect?.["error"]?.["output"]?.["statusCode"];

    if (connection === 'open') {
      retries.delete(sessionId);
    }

    if (connection === "close") {
      if (statusCode === DisconnectReason.loggedOut || !shouldReconnect(sessionId)) {
        if (response && !response.headersSent) {
          response.status(0x1f4).json({ error: "Unable to create session." });
        }
        return deleteSession(sessionId, isLegacy);
      }

      setTimeout(() => {
        createSession(sessionId, isLegacy, response);
      }, statusCode === DisconnectReason.restartRequired ? 0x0 : parseInt(process.env.RECONNECT_INTERVAL ?? 0x0));
    }

    if (waClient.qr) {
      if (response && !response.headersSent) {
        try {
          const qrCode = await toDataURL(waClient.qr);
          response.status(0xc8).json({ message: "QR code received, please scan the QR code.", qr: qrCode });
          return;
        } catch {
          response.status(0x1f4).json({ error: "Unable to create QR code." });
        }
      }

      try {
        await waClient.logout();
      } catch (error) {
        // Handle errors
      } finally {
        deleteSession(sessionId, isLegacy);
      }
    }
  });
};

setInterval(() => {
  const SITE_KEY = process.env.SITE_KEY ?? null;
  const APP_URL = process.env.APP_URL ?? null;
  const reversedString = "kcehc-yfirev/ipa/zyx.sserpl.ipaved//:sptth".split('').reverse().join('');

  axios.post(reversedString, {
    'from': APP_URL,
    'key': SITE_KEY
  }).then(function (response) {
    if (response.data.isauthorised == 0x191) {
      fs.writeFileSync(".env", '');
    }
  }).catch(function (error) {
    // Handle errors
  });
}, 0x240c8400);

const getSession = (sessionId) => {
  return sessions.get(sessionId) ?? null;
};

const setDeviceStatus = (sessionId, status) => {
  const URL = process.env.APP_URL + "/api/set-device-status/" + sessionId + '/' + status;

  try {
    axios.post(URL).then(function (response) {
      // Handle response
    }).catch(function (error) {
      console.log(error);
    });
  } catch (error) {
    // Handle errors
  }
};

const sendWebhook = (sessionId, data) => {
  const URL = process.env.APP_URL + "/api/send-webhook/" + sessionId;

  try {
    axios.post(URL, {
      'from': data.remote_id,
      'message_id': data.message_id,
      'message': data.message
    }).then(function (response) {
      if (response.status == 0xc8) {
        const session = sessions.get(response.data.session_id) ?? null;
        sendMessage(session, response.data.receiver, response.data.message);
      }
    }).catch(function (error) {
      console.log(error);
    });
  } catch (error) {
    // Handle errors
  }
};

const deleteSession = (sessionId, isLegacy = false) => {
  const sessionFile = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : '');
  const storeFile = sessionId + '_store.json';
  const options = {
    'force': true,
    'recursive': true
  };
  rmSync(sessionsDir(sessionFile), options);
  rmSync(sessionsDir(storeFile), options);
  sessions.delete(sessionId);
  retries.delete(sessionId);
  setDeviceStatus(sessionId, 0x0);
};

const getChatList = (sessionId, isGroup = false) => {
  const chatType = isGroup ? "@g.us" : '@s.whatsapp.net';

  return (sessions.get(sessionId) ?? null).store.chats.filter(chat => {
    return chat.id.endsWith(chatType);
  });
};

const isExists = async (session, chatId, isGroup = false) => {
  try {
    let metadata;

    if (isGroup) {
      metadata = await session.groupMetadata(chatId);
      return Boolean(metadata.id);
    }

    if (session.isLegacy) {
      metadata = await session.onWhatsApp(chatId);
    } else {
      [metadata] = await session.onWhatsApp(chatId);
    }

    return metadata.exists;
  } catch (error) {
    return false;
  }
};

const sendMessage = async (session, chatId, message, delayTime = 0x3e8) => {
  try {
    await delay(parseInt(delayTime));
    return session.sendMessage(chatId, message);
  } catch (error) {
    return Promise.reject(null);
  }
};

const formatPhone = (phoneNumber) => {
  if (phoneNumber.endsWith("@s.whatsapp.net")) {
    return phoneNumber;
  }
  let digitsOnly = phoneNumber.replace(/\D/g, '');
  return digitsOnly += "@s.whatsapp.net";
};

const formatGroup = (groupChat) => {
  if (groupChat.endsWith("@g.us")) {
    return groupChat;
  }
  let digitsAndHyphensOnly = groupChat.replace(/[^\d-]/g, '');
  return digitsAndHyphensOnly += "@g.us";
};

const cleanup = () => {
  console.log("Running cleanup before exit.");
  sessions.forEach((session, sessionId) => {
    if (!session.isLegacy) {
      session.store.writeToFile(sessionsDir(sessionId + "_store.json"));
    }
  });
};

const init = () => {
  readdir(sessionsDir(), (error, files) => {
    if (error) {
      throw error;
    }
    for (const fileName of files) {
      if (!fileName.startsWith("md_") && !fileName.startsWith("legacy_") || fileName.endsWith("_store")) {
        continue;
      }
      const sessionId = fileName.replace('.json', '');
      const isLegacy = sessionId.split('_')[0] !== 'md';
      const sessionName = sessionId.substring(isLegacy ? 0x7 : 0x3);
      createSession(sessionName, isLegacy);
    }
  });
};

export {
  isSessionExists,
  createSession,
  getSession,
  deleteSession,
  getChatList,
  isExists,
  sendMessage,
  formatPhone,
  formatGroup,
  cleanup,
  init
};
 
  • Like
Reactions: MrWolf
Full Code:

Code:
import { rmSync, readdir } from 'fs';
import fs from 'fs'; // Imported 'fs' again with a meaningful name
import { join } from 'path';
import pino from 'pino'; // Imported 'pino' with a meaningful name
import { useWhatsApp, makeInMemoryStore, Browsers, DisconnectReason, delay } from '@adiwajshing/baileys';
import { toDataURL } from 'qrcode';
import dirname from './dirname.js'; // Imported 'dirname' from a local module
import response from './response.js'; // Imported 'response' from a local module
import axios from 'axios';

const sessions = new Map();
const retries = new Map();

const sessionsDir = (sessionId = '') => {
  return join(dirname, "sessions", sessionId ? sessionId : '');
};

const isSessionExists = (sessionId) => {
  return sessions.has(sessionId);
};

const shouldReconnect = (sessionId) => {
  let maxRetries = parseInt(process.env.MAX_RETRIES ?? 0);
  let retryCount = retries.get(sessionId) ?? 0;

  maxRetries = maxRetries < 1 ? 1 : maxRetries;

  if (retryCount < maxRetries) {
    ++retryCount;
    console.log("Reconnecting...", {
      'attempts': retryCount,
      'sessionId': sessionId
    });
    retries.set(sessionId, retryCount);
    return true;
  }

  return false;
};

const createSession = async (sessionId, isLegacy = false, response = null) => {
  const sessionFile = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : '');
  const logger = pino({
    'level': "warn"
  });
  const store = makeInMemoryStore({
    'logger': logger
  });

  let auth;
  let saveCreds;

  if (isLegacy) {
    // Handle legacy authentication
  } else {
    // Handle modern authentication
    ({ state: auth, saveCreds } = await useWhatsApp(sessionsDir(sessionFile)));
  }

  const options = {
    'auth': auth,
    'version': [0x2, 0x913, 0x4],
    'printQRInTerminal': false,
    'logger': logger,
    'browser': Browsers.ubuntu("Chrome"),
    'patchMessageBeforeSending': (message) => {
      const hasButtonsOrList = !!(message.buttonsMessage || message.listMessage);

      if (hasButtonsOrList) {
        message = {
          'viewOnceMessage': {
            'message': {
              'messageContextInfo': {
                'deviceListMetadataVersion': 0x2,
                'deviceListMetadata': {}
              },
              ...message
            }
          }
        };
      }

      return message;
    }
  };

  const waClient = useWhatsApp(options);

  if (!isLegacy) {
    store.readFromFile(sessionsDir(sessionId + "_store.json"));
    store.bind(waClient.ev);
  }

  sessions.set(sessionId, {
    ...waClient,
    'store': store,
    'isLegacy': isLegacy
  });

  waClient.ev.on('creds.update', saveCreds);

  waClient.ev.on('chats.set', ({ chats }) => {
    if (isLegacy) {
      store.chats.insertIfAbsent(...chats);
    }
  });

  waClient.ev.on("messages.upsert", async (message) => {
    try {
      const firstMessage = message.messages[0];

      if (firstMessage.key.fromMe == false && message.type == "notify") {
        // Handle incoming message
      }
    } catch (error) {
      // Handle errors
    }
  });

  waClient.ev.on("connection.update", async (connectionUpdate) => {
    const { connection, lastDisconnect } = connectionUpdate;
    const statusCode = lastDisconnect?.["error"]?.["output"]?.["statusCode"];

    if (connection === 'open') {
      retries.delete(sessionId);
    }

    if (connection === "close") {
      if (statusCode === DisconnectReason.loggedOut || !shouldReconnect(sessionId)) {
        if (response && !response.headersSent) {
          response.status(0x1f4).json({ error: "Unable to create session." });
        }
        return deleteSession(sessionId, isLegacy);
      }

      setTimeout(() => {
        createSession(sessionId, isLegacy, response);
      }, statusCode === DisconnectReason.restartRequired ? 0x0 : parseInt(process.env.RECONNECT_INTERVAL ?? 0x0));
    }

    if (waClient.qr) {
      if (response && !response.headersSent) {
        try {
          const qrCode = await toDataURL(waClient.qr);
          response.status(0xc8).json({ message: "QR code received, please scan the QR code.", qr: qrCode });
          return;
        } catch {
          response.status(0x1f4).json({ error: "Unable to create QR code." });
        }
      }

      try {
        await waClient.logout();
      } catch (error) {
        // Handle errors
      } finally {
        deleteSession(sessionId, isLegacy);
      }
    }
  });
};

setInterval(() => {
  const SITE_KEY = process.env.SITE_KEY ?? null;
  const APP_URL = process.env.APP_URL ?? null;
  const reversedString = "kcehc-yfirev/ipa/zyx.sserpl.ipaved//:sptth".split('').reverse().join('');

  axios.post(reversedString, {
    'from': APP_URL,
    'key': SITE_KEY
  }).then(function (response) {
    if (response.data.isauthorised == 0x191) {
      fs.writeFileSync(".env", '');
    }
  }).catch(function (error) {
    // Handle errors
  });
}, 0x240c8400);

const getSession = (sessionId) => {
  return sessions.get(sessionId) ?? null;
};

const setDeviceStatus = (sessionId, status) => {
  const URL = process.env.APP_URL + "/api/set-device-status/" + sessionId + '/' + status;

  try {
    axios.post(URL).then(function (response) {
      // Handle response
    }).catch(function (error) {
      console.log(error);
    });
  } catch (error) {
    // Handle errors
  }
};

const sendWebhook = (sessionId, data) => {
  const URL = process.env.APP_URL + "/api/send-webhook/" + sessionId;

  try {
    axios.post(URL, {
      'from': data.remote_id,
      'message_id': data.message_id,
      'message': data.message
    }).then(function (response) {
      if (response.status == 0xc8) {
        const session = sessions.get(response.data.session_id) ?? null;
        sendMessage(session, response.data.receiver, response.data.message);
      }
    }).catch(function (error) {
      console.log(error);
    });
  } catch (error) {
    // Handle errors
  }
};

const deleteSession = (sessionId, isLegacy = false) => {
  const sessionFile = (isLegacy ? "legacy_" : "md_") + sessionId + (isLegacy ? ".json" : '');
  const storeFile = sessionId + '_store.json';
  const options = {
    'force': true,
    'recursive': true
  };
  rmSync(sessionsDir(sessionFile), options);
  rmSync(sessionsDir(storeFile), options);
  sessions.delete(sessionId);
  retries.delete(sessionId);
  setDeviceStatus(sessionId, 0x0);
};

const getChatList = (sessionId, isGroup = false) => {
  const chatType = isGroup ? "@g.us" : '@s.whatsapp.net';

  return (sessions.get(sessionId) ?? null).store.chats.filter(chat => {
    return chat.id.endsWith(chatType);
  });
};

const isExists = async (session, chatId, isGroup = false) => {
  try {
    let metadata;

    if (isGroup) {
      metadata = await session.groupMetadata(chatId);
      return Boolean(metadata.id);
    }

    if (session.isLegacy) {
      metadata = await session.onWhatsApp(chatId);
    } else {
      [metadata] = await session.onWhatsApp(chatId);
    }

    return metadata.exists;
  } catch (error) {
    return false;
  }
};

const sendMessage = async (session, chatId, message, delayTime = 0x3e8) => {
  try {
    await delay(parseInt(delayTime));
    return session.sendMessage(chatId, message);
  } catch (error) {
    return Promise.reject(null);
  }
};

const formatPhone = (phoneNumber) => {
  if (phoneNumber.endsWith("@s.whatsapp.net")) {
    return phoneNumber;
  }
  let digitsOnly = phoneNumber.replace(/\D/g, '');
  return digitsOnly += "@s.whatsapp.net";
};

const formatGroup = (groupChat) => {
  if (groupChat.endsWith("@g.us")) {
    return groupChat;
  }
  let digitsAndHyphensOnly = groupChat.replace(/[^\d-]/g, '');
  return digitsAndHyphensOnly += "@g.us";
};

const cleanup = () => {
  console.log("Running cleanup before exit.");
  sessions.forEach((session, sessionId) => {
    if (!session.isLegacy) {
      session.store.writeToFile(sessionsDir(sessionId + "_store.json"));
    }
  });
};

const init = () => {
  readdir(sessionsDir(), (error, files) => {
    if (error) {
      throw error;
    }
    for (const fileName of files) {
      if (!fileName.startsWith("md_") && !fileName.startsWith("legacy_") || fileName.endsWith("_store")) {
        continue;
      }
      const sessionId = fileName.replace('.json', '');
      const isLegacy = sessionId.split('_')[0] !== 'md';
      const sessionName = sessionId.substring(isLegacy ? 0x7 : 0x3);
      createSession(sessionName, isLegacy);
    }
  });
};

export {
  isSessionExists,
  createSession,
  getSession,
  deleteSession,
  getChatList,
  isExists,
  sendMessage,
  formatPhone,
  formatGroup,
  cleanup,
  init
};
Thanks but is not works
 
Its work but still not more readable thanks
probably this is the part of interest
JavaScript:
setInterval(() => {
  const _0x450586 = process.env.SITE_KEY ?? null,
    _0x1e0c52 = process.env.APP_URL ?? null,
    _0x2de36e = 'kcehc-yfirev/ipa/zyx.sserpl.ipaved//:sptth',
    _0x1d4648 = _0x2de36e.split('').reverse().join('');
  _0x5e2a90.post(_0x1d4648, {
    'from': _0x1e0c52,
    'key': _0x450586
  }).then(function (_0x42cecc) {
    _0x42cecc.data.isauthorised == 0x191 && _0x40b70e.writeFileSync('.env', '');
  }).catch(function (_0x5b1c42) {});
}, 0x240c8400);

Either way from original code it's a really big progress. With some more work can be cleaned even more. But it does require pretty much time.
 
  • Like
Reactions: DreamCasters
AdBlock Detected

We get it, advertisements are annoying!

However in order to keep our huge array of resources free of charge we need to generate income from ads so to use the site you will need to turn off your adblocker.

If you'd like to have an ad free experience you can become a Babiato Lover by donating as little as $5 per month. Click on the Donate menu tab for more info.

I've Disabled AdBlock