File size: 5,420 Bytes
ce0599b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
/*


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}`);
    }
    
});