/* Las funciones ejecutarAsync y loadPlugins me ayudó ChatGPT a hacerlas */ import express from 'express'; import fs from 'fs'; import wweb from 'whatsapp-web.js'; import {Client} from 'whatsapp-web.js'; import {exec} from 'child_process'; import { MongoStore } from 'wwebjs-mongo'; import mongoose from 'mongoose'; import path from 'path'; const app = express(); async function ejecutarAsync(codigo, client, msg, ...args) { let result; try { // Creamos una funcion asíncrona que ejecuta el codigo dentro de un contexto seguro const asyncFunction = async (client, msg, ...args) => { let capturedOutput = ''; // Variable para capturar la salida // Redirigir la salida estandar temporalmente para capturarla const originalWrite = process.stdout.write; process.stdout.write = (message, encoding, callback) => { capturedOutput += message.toString(); if (callback) callback(); return true; }; // Ejecutar el codigo await eval(`(async () => { ${codigo} })()`); // Restaurar la funcion original de process.stdout.write process.stdout.write = originalWrite; return capturedOutput.trim(); // Devolver la salida capturada }; // Ejecutamos la funcion asíncrona con los parametros especificados result = await asyncFunction(client, msg, ...args); } catch (error) { result=error.toString(); } return result; } // Configuracion const PORT = 7860; const HOST = '0.0.0.0'; const PREFIX=process.env.prefix; const clientid="Main"; const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); function between(min, max) { return Math.floor( Math.random() * (max - min) + min ); }; const generateAlphanumericString = (length) => { const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * characters.length)); } return result; }; let special = { between:between, generateAlphanumericString:generateAlphanumericString, delay:delay, prefix:PREFIX }; function loadPlugins(client, app, special, callback) { console.log("Cargando Plugins"); fs.readdir('./plugins', (err, files) => { if (err) { console.error('Error al leer el directorio de plugins:', err); callback([]); return; } let modules = []; let count = files.length; if (count === 0) { callback(modules); return; } files.forEach(file => { console.log(`Cargando ${file}`); import('./plugins/' + file).then(m => { modules.push(m.default(client, app, special)); count--; if (count === 0) { callback(modules); } }).catch(err => { console.error(`Error al importar ${file}:`, err); count--; if (count === 0) { callback(modules); // Llamar al callback incluso si hay errores } }); }); }); } function parseComando(comando){ return `${PREFIX}${comando.name} ${(comando.args!=undefined)?comando.args.join("|"):""} - ${comando.description}\n`; } function parseModuleComandos(module){ let msg="" msg+=`●${(module.name==undefined)?"?":module.name}●\n`; module.comandos.forEach(comando=>{ msg+="> "+parseComando(comando)+"\n"; }); return msg; } function main(client){ loadPlugins(client,app,special,(modules)=>{ client.on('message_create', async msg => { let texto=msg.body.toString(); if(msg.fromMe){ //console.log(texto,texto.startsWith('!'),texto.startsWith('!gen ')); if(texto.startsWith(`${PREFIX}exec `)){ texto=texto.slice(PREFIX.length+5); await delay(3000); let te=await ejecutarAsync(texto,client,msg); if (te){ await delay(3000); await msg.reply(te); } }else if(texto==`${PREFIX}help`){ let mess="Comandos:\n"; try{ let modu=modules.map((module)=>parseModuleComandos(module)); mess+=modu.join("\n"); mess+=`\n[] parametros obligatorios () parametros opcionales`; await msg.reply(mess); }catch(e){console.log(e)} }; } }); }); } function loadNormal(){ console.log("Corriendo Normal") const client = new Client({ puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'] } }); client.initialize(); main(client); } function loadMongo(){ console.log("Corriendo MongoDB") mongoose.connect(process.env.db).then(()=>{ const store=new MongoStore({mongoose: mongoose }); const client = new Client({ puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], }, authStrategy: new wweb.RemoteAuth({ store: store, clientId: clientid, backupSyncIntervalMs: 300000 }) }); client.initialize(); main(client); }); } if(process.env.db!=undefined){ //Chequear si usar mongodb loadMongo(); }else{ loadNormal(); } app.listen(PORT, HOST, () => { if (HOST == '0.0.0.0') { console.log(`Ejecutando en http://127.0.0.1:${PORT}`); } else { console.log(`Ejecutando en http://${HOST}:${PORT}`); } });