-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathmain.js
More file actions
1224 lines (1088 loc) Β· 41 KB
/
Copy pathmain.js
File metadata and controls
1224 lines (1088 loc) Β· 41 KB
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '1';
import './config.js';
import './api.js';
import { createRequire } from 'module';
import path, { join } from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { platform } from 'process';
import fs, { readdirSync, statSync, unlinkSync, existsSync, readFileSync, watch } from 'fs';
import yargs from 'yargs';
import { spawn } from 'child_process';
import lodash from 'lodash';
import chalk from 'chalk';
import syntaxerror from 'syntax-error';
import { format } from 'util';
import pino from 'pino';
import Pino from 'pino';
import { Boom } from '@hapi/boom';
import { makeWASocket, protoType, serialize } from './src/libraries/simple.js';
import { initializeSubBots } from './src/libraries/subBotManager.js';
import { Low, JSONFile } from 'lowdb';
import store from './src/libraries/store.js';
import LidResolver from './src/libraries/LidResolver.js';
const { DisconnectReason, useMultiFileAuthState, fetchLatestBaileysVersion, makeCacheableSignalKeyStore, jidNormalizedUser, PHONENUMBER_MCC } = await import("baileys");
import readline from 'readline';
import NodeCache from 'node-cache';
const { chain } = lodash;
const PORT = process.env.PORT || process.env.SERVER_PORT || 3000;
let stopped = 'close';
protoType();
serialize();
const msgRetryCounterMap = new Map();
const msgRetryCounterCache = new NodeCache({ stdTTL: 0, checkperiod: 0 });
const userDevicesCache = new NodeCache({ stdTTL: 0, checkperiod: 0 });
global.__filename = function filename(pathURL = import.meta.url, rmPrefix = platform !== 'win32') {
return rmPrefix ? /file:\/\/\//.test(pathURL) ? fileURLToPath(pathURL) : pathURL : pathToFileURL(pathURL).toString();
}; global.__dirname = function dirname(pathURL) {
return path.dirname(global.__filename(pathURL, true));
}; global.__require = function require(dir = import.meta.url) {
return createRequire(dir);
};
global.API = (name, path = '/', query = {}, apikeyqueryname) => (name in global.APIs ? global.APIs[name] : name) + path + (query || apikeyqueryname ? '?' + new URLSearchParams(Object.entries({ ...query, ...(apikeyqueryname ? { [apikeyqueryname]: global.APIKeys[name in global.APIs ? global.APIs[name] : name] } : {}) })) : '');
global.timestamp = { start: new Date };
global.videoList = [];
global.videoListXXX = [];
const __dirname = global.__dirname(import.meta.url);
global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse());
global.prefix = new RegExp('^[#!/.]')
global.db = new Low(/https?:\/\//.test(opts['db'] || '') ? new cloudDBAdapter(opts['db']) : new JSONFile(`${opts._[0] ? opts._[0] + '_' : ''}database.json`));
global.loadDatabase = async function loadDatabase() {
if (global.db.READ) {
return new Promise((resolve) => setInterval(async function () {
if (!global.db.READ) {
clearInterval(this);
resolve(global.db.data == null ? global.loadDatabase() : global.db.data);
}
}, 1 * 1000));
}
if (global.db.data !== null) return;
global.db.READ = true;
await global.db.read().catch(console.error);
global.db.READ = null;
global.db.data = {
users: {},
chats: {},
stats: {},
msgs: {},
sticker: {},
settings: {},
...(global.db.data || {}),
};
global.db.chain = chain(global.db.data);
};
loadDatabase();
/* ------------------------------------------------*/
/**
* Clase auxiliar para acceso a datos LID desde JSON
*/
class LidDataManager {
constructor(cacheFile = './src/lidsresolve.json') {
this.cacheFile = cacheFile;
}
/**
* Cargar datos del archivo JSON
*/
loadData() {
try {
if (fs.existsSync(this.cacheFile)) {
const data = fs.readFileSync(this.cacheFile, 'utf8');
return JSON.parse(data);
}
return {};
} catch (error) {
console.error('β Error cargando cache LID:', error.message);
return {};
}
}
/**
* Obtener informaciΓ³n de usuario por LID
*/
getUserInfo(lidNumber) {
const data = this.loadData();
return data[lidNumber] || null;
}
/**
* Obtener informaciΓ³n de usuario por JID
*/
getUserInfoByJid(jid) {
const data = this.loadData();
for (const [key, entry] of Object.entries(data)) {
if (entry && entry.jid === jid) {
return entry;
}
}
return null;
}
/**
* Encontrar LID por JID
*/
findLidByJid(jid) {
const data = this.loadData();
for (const [key, entry] of Object.entries(data)) {
if (entry && entry.jid === jid) {
return entry.lid;
}
}
return null;
}
/**
* Listar todos los usuarios vΓ‘lidos
*/
getAllUsers() {
const data = this.loadData();
const users = [];
for (const [key, entry] of Object.entries(data)) {
if (entry && !entry.notFound && !entry.error) {
users.push({
lid: entry.lid,
jid: entry.jid,
name: entry.name,
country: entry.country,
phoneNumber: entry.phoneNumber,
isPhoneDetected: entry.phoneDetected || entry.corrected,
timestamp: new Date(entry.timestamp).toLocaleString()
});
}
}
return users.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Obtener estadΓsticas
*/
getStats() {
const data = this.loadData();
let valid = 0, notFound = 0, errors = 0, phoneNumbers = 0, corrected = 0;
for (const [key, entry] of Object.entries(data)) {
if (entry) {
if (entry.phoneDetected || entry.corrected) phoneNumbers++;
if (entry.corrected) corrected++;
if (entry.notFound) notFound++;
else if (entry.error) errors++;
else valid++;
}
}
return {
total: Object.keys(data).length,
valid,
notFound,
errors,
phoneNumbers,
corrected,
cacheFile: this.cacheFile,
fileExists: fs.existsSync(this.cacheFile)
};
}
/**
* Obtener usuarios por paΓs
*/
getUsersByCountry() {
const data = this.loadData();
const countries = {};
for (const [key, entry] of Object.entries(data)) {
if (entry && !entry.notFound && !entry.error && entry.country) {
if (!countries[entry.country]) {
countries[entry.country] = [];
}
countries[entry.country].push({
lid: entry.lid,
jid: entry.jid,
name: entry.name,
phoneNumber: entry.phoneNumber
});
}
}
// Ordenar usuarios dentro de cada paΓs
for (const country of Object.keys(countries)) {
countries[country].sort((a, b) => a.name.localeCompare(b.name));
}
return countries;
}
}
// Instancia del manejador de datos LID
const lidDataManager = new LidDataManager();
/**
* FUNCIΓN MEJORADA: Procesar texto para resolver LIDs - VERSION MΓS ROBUSTA
*/
async function processTextMentions(text, groupId, lidResolver) {
if (!text || !groupId || !text.includes('@')) return text;
try {
// Regex mΓ‘s completa para capturar diferentes formatos de menciΓ³n
const mentionRegex = /@(\d{8,20})/g;
const mentions = [...text.matchAll(mentionRegex)];
if (!mentions.length) return text;
let processedText = text;
const processedMentions = new Set();
const replacements = new Map(); // Cache de reemplazos para este texto
// Procesar todas las menciones primero
for (const mention of mentions) {
const [fullMatch, lidNumber] = mention;
if (processedMentions.has(lidNumber)) continue;
processedMentions.add(lidNumber);
const lidJid = `${lidNumber}@lid`;
try {
const resolvedJid = await lidResolver.resolveLid(lidJid, groupId);
if (resolvedJid && resolvedJid !== lidJid && !resolvedJid.endsWith('@lid')) {
const resolvedNumber = resolvedJid.split('@')[0];
// Validar que el nΓΊmero resuelto sea diferente al LID original
if (resolvedNumber && resolvedNumber !== lidNumber) {
replacements.set(lidNumber, resolvedNumber);
}
}
} catch (error) {
console.error(`β Error procesando menciΓ³n LID ${lidNumber}:`, error.message);
}
}
// Aplicar todos los reemplazos
for (const [lidNumber, resolvedNumber] of replacements.entries()) {
// Usar regex global para reemplazar TODAS las ocurrencias
const globalRegex = new RegExp(`@${lidNumber}\\b`, 'g'); // \\b para lΓmite de palabra
processedText = processedText.replace(globalRegex, `@${resolvedNumber}`);
}
return processedText;
} catch (error) {
console.error('β Error en processTextMentions:', error);
return text;
}
}
/**
* FUNCIΓN AUXILIAR: Procesar contenido de mensaje recursivamente
*/
async function processMessageContent(messageContent, groupChatId, lidResolver) {
if (!messageContent || typeof messageContent !== 'object') return;
const messageTypes = Object.keys(messageContent);
for (const msgType of messageTypes) {
const msgContent = messageContent[msgType];
if (!msgContent || typeof msgContent !== 'object') continue;
// Procesar texto principal
if (typeof msgContent.text === 'string') {
try {
const originalText = msgContent.text;
msgContent.text = await processTextMentions(originalText, groupChatId, lidResolver);
} catch (error) {
console.error('β Error procesando texto:', error);
}
}
// Procesar caption
if (typeof msgContent.caption === 'string') {
try {
const originalCaption = msgContent.caption;
msgContent.caption = await processTextMentions(originalCaption, groupChatId, lidResolver);
} catch (error) {
console.error('β Error procesando caption:', error);
}
}
// Procesar contextInfo
if (msgContent.contextInfo) {
await processContextInfo(msgContent.contextInfo, groupChatId, lidResolver);
}
}
}
/**
* FUNCIΓN AUXILIAR: Procesar contextInfo recursivamente
*/
async function processContextInfo(contextInfo, groupChatId, lidResolver) {
if (!contextInfo || typeof contextInfo !== 'object') return;
// Procesar mentionedJid en contextInfo
if (contextInfo.mentionedJid && Array.isArray(contextInfo.mentionedJid)) {
const resolvedMentions = [];
for (const jid of contextInfo.mentionedJid) {
if (typeof jid === 'string' && jid.endsWith?.('@lid')) {
try {
const resolved = await lidResolver.resolveLid(jid, groupChatId);
resolvedMentions.push(resolved && !resolved.endsWith('@lid') ? resolved : jid);
} catch (error) {
resolvedMentions.push(jid);
}
} else {
resolvedMentions.push(jid);
}
}
contextInfo.mentionedJid = resolvedMentions;
}
// Procesar participant en contextInfo
if (typeof contextInfo.participant === 'string' && contextInfo.participant.endsWith?.('@lid')) {
try {
const resolved = await lidResolver.resolveLid(contextInfo.participant, groupChatId);
if (resolved && !resolved.endsWith('@lid')) {
contextInfo.participant = resolved;
}
} catch (error) {
console.error('β Error resolviendo participant en contextInfo:', error);
}
}
// Procesar mensajes citados recursivamente
if (contextInfo.quotedMessage) {
await processMessageContent(contextInfo.quotedMessage, groupChatId, lidResolver);
}
// Procesar otros campos que puedan contener texto
if (typeof contextInfo.stanzaId === 'string') {
contextInfo.stanzaId = await processTextMentions(contextInfo.stanzaId, groupChatId, lidResolver);
}
}
/**
* FUNCIΓN MEJORADA: Procesar mensaje completo de forma mΓ‘s exhaustiva
*/
async function processMessageForDisplay(message, lidResolver) {
if (!message || !lidResolver) return message;
try {
const processedMessage = JSON.parse(JSON.stringify(message)); // Deep copy
const groupChatId = message.key?.remoteJid?.endsWith?.('@g.us') ? message.key.remoteJid : null;
if (!groupChatId) return processedMessage;
// 1. Resolver participant LID
if (processedMessage.key?.participant?.endsWith?.('@lid')) {
try {
const resolved = await lidResolver.resolveLid(processedMessage.key.participant, groupChatId);
if (resolved && resolved !== processedMessage.key.participant && !resolved.endsWith('@lid')) {
processedMessage.key.participant = resolved;
}
} catch (error) {
console.error('β Error resolviendo participant:', error);
}
}
// 2. Procesar mentionedJid a nivel raΓz
if (processedMessage.mentionedJid && Array.isArray(processedMessage.mentionedJid)) {
const resolvedMentions = [];
for (const jid of processedMessage.mentionedJid) {
if (typeof jid === 'string' && jid.endsWith?.('@lid')) {
try {
const resolved = await lidResolver.resolveLid(jid, groupChatId);
resolvedMentions.push(resolved && !resolved.endsWith('@lid') ? resolved : jid);
} catch (error) {
resolvedMentions.push(jid);
}
} else {
resolvedMentions.push(jid);
}
}
processedMessage.mentionedJid = resolvedMentions;
}
// 3. Procesar el contenido del mensaje
if (processedMessage.message) {
await processMessageContent(processedMessage.message, groupChatId, lidResolver);
}
return processedMessage;
} catch (error) {
console.error('β Error procesando mensaje para display:', error);
return message;
}
}
/**
* FUNCIΓN AUXILIAR: Extraer todo el texto de un mensaje para debugging
*/
function extractAllText(message) {
if (!message?.message) return '';
let allText = '';
const extractFromContent = (content) => {
if (!content) return '';
let text = '';
if (content.text) text += content.text + ' ';
if (content.caption) text += content.caption + ' ';
if (content.contextInfo?.quotedMessage) {
const quotedTypes = Object.keys(content.contextInfo.quotedMessage);
for (const quotedType of quotedTypes) {
const quotedContent = content.contextInfo.quotedMessage[quotedType];
text += extractFromContent(quotedContent);
}
}
return text;
};
const messageTypes = Object.keys(message.message);
for (const msgType of messageTypes) {
allText += extractFromContent(message.message[msgType]);
}
return allText.trim();
}
/**
* FUNCIΓN MEJORADA: Interceptar mensajes con mejor manejo de errores
*/
async function interceptMessages(messages, lidResolver) {
if (!Array.isArray(messages)) return messages;
const processedMessages = [];
for (const message of messages) {
try {
// Procesar con lidResolver si existe
let processedMessage = message;
if (lidResolver && typeof lidResolver.processMessage === 'function') {
try {
processedMessage = await lidResolver.processMessage(message);
} catch (error) {
console.error('β Error en lidResolver.processMessage:', error);
// Continuar con el procesamiento manual
}
}
// Procesamiento adicional para display
processedMessage = await processMessageForDisplay(processedMessage, lidResolver);
processedMessages.push(processedMessage);
} catch (error) {
console.error('β Error interceptando mensaje:', error);
processedMessages.push(message);
}
}
return processedMessages;
}
const { state, saveCreds } = await useMultiFileAuthState(global.authFile);
const version22 = await fetchLatestBaileysVersion();
console.log(version22)
const version = version22?.version || [2, 3000, 1033893291];
let phoneNumber = global.botnumber || process.argv.find(arg => arg.startsWith('--phone='))?.split('=')[1];
const methodCodeQR = process.argv.includes('--method=qr');
const methodCode = !!phoneNumber || process.argv.includes('--method=code');
const MethodMobile = process.argv.includes("mobile");
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const question = (texto) => new Promise((resolver) => rl.question(texto, resolver));
let opcion;
if (methodCodeQR) opcion = '1';
if (!methodCodeQR && !methodCode && !fs.existsSync(`./${global.authFile}/creds.json`)) {
do {
opcion = await question('[ βΉοΈ ] Seleccione una opciΓ³n:\n1. Con cΓ³digo QR\n2. Con cΓ³digo de texto de 8 dΓgitos\n---> ');
if (!/^[1-2]$/.test(opcion)) {
console.log('[ β οΈ ] Por favor, seleccione solo 1 o 2.\n');
}
} while (opcion !== '1' && opcion !== '2' || fs.existsSync(`./${global.authFile}/creds.json`));
}
const filterStrings = [
"Q2xvc2luZyBzdGFsZSBvcGVu",
"Q2xvc2luZyBvcGVuIHNlc3Npb24=",
"RmFpbGVkIHRvIGRlY3J5cHQ=",
"U2Vzc2lvbiBlcnJvcg==",
"RXJyb3I6IEJhZCBNQUM=",
"RGVjcnlwdGVkIG1lc3NhZ2U="
];
console.info = () => { };
console.debug = () => { };
['log', 'warn', 'error'].forEach(methodName => {
const originalMethod = console[methodName];
console[methodName] = function () {
const message = arguments[0];
if (typeof message === 'string' && filterStrings.some(filterString => message.includes(Buffer.from(filterString, 'base64').toString()))) {
arguments[0] = "";
}
originalMethod.apply(console, arguments);
};
});
process.on('uncaughtException', (err) => {
if (filterStrings.includes(Buffer.from(err.message).toString('base64'))) return;
console.error('Uncaught Exception:', err);
});
const connectionOptions = {
logger: pino({ level: 'silent' }),
printQRInTerminal: opcion == '1' ? true : methodCodeQR ? true : false,
mobile: MethodMobile,
browser: opcion === '1' ? ['TheMystic-Bot-MD', 'Safari', '2.0.0'] : methodCodeQR ? ['TheMystic-Bot-MD', 'Safari', '2.0.0'] : ['Ubuntu', 'Chrome', '20.0.04'],
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, Pino({ level: "fatal" }).child({ level: "fatal" })),
},
markOnlineOnConnect: false,
generateHighQualityLinkPreview: true,
syncFullHistory: false,
getMessage: async (key) => {
try {
let jid = jidNormalizedUser(key.remoteJid);
let msg = await store.loadMessage(jid, key.id);
return msg?.message || "";
} catch (error) {
return "";
}
},
msgRetryCounterCache: msgRetryCounterCache || new Map(),
userDevicesCache: userDevicesCache || new Map(),
defaultQueryTimeoutMs: undefined,
cachedGroupMetadata: (jid) => global.conn.chats[jid] ?? {},
keepAliveIntervalMs: 55000,
maxIdleTimeMs: 60000,
version,
};
global.conn = makeWASocket(connectionOptions);
const lidResolver = new LidResolver(global.conn);
// Ejecutar anΓ‘lisis y correcciΓ³n automΓ‘tica al inicializar (SILENCIOSO)
setTimeout(async () => {
try {
if (lidResolver) {
// Ejecutar correcciΓ³n automΓ‘tica de nΓΊmeros telefΓ³nicos (sin logs)
lidResolver.autoCorrectPhoneNumbers();
}
} catch (error) {
console.error('β Error en anΓ‘lisis inicial:', error.message);
}
}, 5000);
if (!fs.existsSync(`./${global.authFile}/creds.json`)) {
if (opcion === '2' || methodCode) {
opcion = '2';
if (!conn.authState.creds.registered) {
if (MethodMobile) throw new Error('No se puede usar un cΓ³digo de emparejamiento con la API mΓ³vil');
let numeroTelefono;
if (!!phoneNumber) {
numeroTelefono = phoneNumber.replace(/[^0-9]/g, '');
if (!Object.keys(PHONENUMBER_MCC).some(v => numeroTelefono.startsWith(v))) {
console.log(chalk.bgBlack(chalk.bold.redBright("Comience con el cΓ³digo de paΓs de su nΓΊmero de WhatsApp.\nEjemplo: +5219992095479\n")));
process.exit(0);
}
} else {
while (true) {
numeroTelefono = await question(chalk.bgBlack(chalk.bold.yellowBright('Por favor, escriba su nΓΊmero de WhatsApp.\nEjemplo: +5219992095479\n')));
numeroTelefono = numeroTelefono.replace(/[^0-9]/g, '');
if (numeroTelefono.match(/^\d+$/) && Object.keys(PHONENUMBER_MCC).some(v => numeroTelefono.startsWith(v))) break;
console.log(chalk.bgBlack(chalk.bold.redBright("Por favor, escriba su nΓΊmero de WhatsApp.\nEjemplo: +5219992095479.\n")));
}
rl.close();
}
setTimeout(async () => {
let codigo = await conn.requestPairingCode(numeroTelefono);
codigo = codigo?.match(/.{1,4}/g)?.join("-") || codigo;
console.log(chalk.yellow('[ βΉοΈ ] introduce el cΓ³digo de emparejamiento en WhatsApp.'));
console.log(chalk.black(chalk.bgGreen(`Su cΓ³digo de emparejamiento: `)), chalk.black(chalk.white(codigo)));
}, 3000);
}
}
}
conn.isInit = false;
conn.well = false;
conn.logger.info(`[γβΉοΈγ] Cargando...\n`);
if (!opts['test']) {
if (global.db) {
setInterval(async () => {
if (global.db.data) await global.db.write();
if (opts['autocleartmp'] && (global.support || {}).find) {
const tmp = [os.tmpdir(), 'tmp', 'jadibts'];
tmp.forEach((filename) => cp.spawn('find', [filename, '-amin', '3', '-type', 'f', '-delete']));
}
}, 30 * 1000);
}
}
if (opts['server']) (await import('./server.js')).default(global.conn, PORT);
function clearTmp() {
const tmp = [join(__dirname, './src/tmp')];
const filename = [];
tmp.forEach((dirname) => readdirSync(dirname).forEach((file) => filename.push(join(dirname, file))));
return filename.map((file) => {
const stats = statSync(file);
if (stats.isFile() && (Date.now() - stats.mtimeMs >= 1000 * 60 * 3)) return unlinkSync(file);
return false;
});
}
const dirToWatchccc = path.join(__dirname, './');
function deleteCoreFiles(filePath) {
const coreFilePattern = /^core\.\d+$/i;
const filename = path.basename(filePath);
if (coreFilePattern.test(filename)) {
fs.unlink(filePath, (err) => {
if (err) console.error(`Error eliminando el archivo ${filePath}:`, err);
});
}
}
fs.watch(dirToWatchccc, (eventType, filename) => {
if (eventType === 'rename') {
const filePath = path.join(dirToWatchccc, filename);
fs.stat(filePath, (err, stats) => {
if (!err && stats.isFile()) deleteCoreFiles(filePath);
});
}
});
function purgeSession() {
let prekey = [];
let directorio = readdirSync("./MysticSession");
let filesFolderPreKeys = directorio.filter(file => file.startsWith('pre-key-'));
prekey = [...prekey, ...filesFolderPreKeys];
filesFolderPreKeys.forEach(files => unlinkSync(`./MysticSession/${files}`));
}
function purgeSessionSB() {
try {
let listaDirectorios = readdirSync('./jadibts/');
let SBprekey = [];
listaDirectorios.forEach(directorio => {
if (statSync(`./jadibts/${directorio}`).isDirectory()) {
let DSBPreKeys = readdirSync(`./jadibts/${directorio}`).filter(fileInDir => fileInDir.startsWith('pre-key-'));
SBprekey = [...SBprekey, ...DSBPreKeys];
DSBPreKeys.forEach(fileInDir => unlinkSync(`./jadibts/${directorio}/${fileInDir}`));
}
});
} catch (err) {
console.log(chalk.bold.red(`[ βΉοΈ ] Algo salio mal durante la eliminaciΓ³n, archivos no eliminados`));
}
}
function purgeOldFiles() {
const directories = ['./MysticSession/', './jadibts/'];
const oneHourAgo = Date.now() - (60 * 60 * 1000);
directories.forEach(dir => {
readdirSync(dir, (err, files) => {
if (err) throw err;
files.forEach(file => {
const filePath = path.join(dir, file);
stat(filePath, (err, stats) => {
if (err) throw err;
if (stats.isFile() && stats.mtimeMs < oneHourAgo && file !== 'creds.json') {
unlinkSync(filePath, err => {
if (err) throw err;
});
}
});
});
});
});
}
async function connectionUpdate(update) {
let isFirstConnection = '';
let qrAlreadyShown = false;
let qrTimeout = null;
const { connection, lastDisconnect, isNewLogin } = update;
stopped = connection;
if (isNewLogin) conn.isInit = true;
const code = lastDisconnect?.error?.output?.statusCode || lastDisconnect?.error?.output?.payload?.statusCode;
if (code && code !== DisconnectReason.loggedOut && conn?.ws.socket == null) {
await global.reloadHandler(true).catch(console.error);
global.timestamp.connect = new Date;
}
if (global.db.data == null) loadDatabase();
if (update.qr != 0 && update.qr != undefined || methodCodeQR) {
if (opcion == '1' || methodCodeQR) {
console.log(chalk.yellow('[γβΉοΈγγ] Escanea el cΓ³digo QR.'));
qrAlreadyShown = true;
if (qrTimeout) clearTimeout(qrTimeout);
qrTimeout = setTimeout(() => qrAlreadyShown = false, 60000);
}
}
if (connection == 'open') {
console.log(chalk.yellow('[γβΉοΈγγ] Conectado correctamente.'));
isFirstConnection = true;
if (!global.subBotsInitialized) {
global.subBotsInitialized = true;
try {
await initializeSubBots();
} catch (error) {
console.error(chalk.red('[ β οΈ ] Error al inicializar sub-bots:'), error);
}
}
}
let reason = new Boom(lastDisconnect?.error)?.output?.statusCode;
const lastErrors = {};
const errorTimers = {};
const errorCounters = {};
function shouldLogError(errorType) {
if (!errorCounters[errorType]) errorCounters[errorType] = { count: 0, lastShown: 0 };
const now = Date.now();
const errorData = errorCounters[errorType];
if (errorData.count >= 5) return false;
if (now - errorData.lastShown < 2000) return false;
errorData.count++;
errorData.lastShown = now;
return true;
}
if (reason == 405) {
//await fs.unlinkSync("./MysticSession/" + "creds.json");
console.log(chalk.bold.redBright(`[ β οΈ ] ConexiΓ³n replazada, Por favor espere un momento me voy a reiniciar...\nSi aparecen error vuelve a iniciar con : npm start`));
//process.send('reset');
}
if (connection === 'close') {
if (reason === DisconnectReason.badSession) {
if (shouldLogError('badSession')) {
conn.logger.error(`[ β οΈ ] SesiΓ³n incorrecta, por favor elimina la carpeta ${global.authFile} y escanea nuevamente.`);
}
await global.reloadHandler(true).catch(console.error);
} else if (reason === DisconnectReason.connectionClosed) {
if (shouldLogError('connectionClosed')) {
conn.logger.warn(`[ β οΈ ] ConexiΓ³n cerrada, reconectando...`);
}
await global.reloadHandler(true).catch(console.error);
} else if (reason === DisconnectReason.connectionLost) {
if (shouldLogError('connectionLost')) {
conn.logger.warn(`[ β οΈ ] ConexiΓ³n perdida con el servidor, reconectando...`);
}
await global.reloadHandler(true).catch(console.error);
} else if (reason === DisconnectReason.connectionReplaced) {
if (shouldLogError('connectionReplaced')) {
conn.logger.error(`[ β οΈ ] ConexiΓ³n reemplazada, se ha abierto otra nueva sesiΓ³n. Por favor, cierra la sesiΓ³n actual primero.`);
}
await global.reloadHandler(true).catch(console.error);
} else if (reason === DisconnectReason.loggedOut) {
if (shouldLogError('loggedOut')) {
conn.logger.error(`[ β οΈ ] Conexion cerrada, por favor elimina la carpeta ${global.authFile} y escanea nuevamente.`);
}
} else if (reason === DisconnectReason.restartRequired) {
if (isFirstConnection) {
if (shouldLogError('restartRequired')) {
//conn.logger.info(`[ β οΈ ] Primer inicio: Ignorando restartRequired (posible falso positivo)`);
}
isFirstConnection = false;
} else {
if (shouldLogError('restartRequired')) {
conn.logger.info(`[ β οΈ ] Reinicio necesario, reconectando...`);
}
await global.reloadHandler(true).catch(console.error);
}
} else if (reason === DisconnectReason.timedOut) {
if (shouldLogError('timedOut')) {
conn.logger.warn(`[ β οΈ ] Tiempo de conexiΓ³n agotado, reconectando...`);
}
await global.reloadHandler(true).catch(console.error);
} else {
const unknownError = `unknown_${reason || ''}_${connection || ''}`;
if (shouldLogError(unknownError)) {
conn.logger.warn(`[ β οΈ ] RazΓ³n de desconexiΓ³n desconocida. ${reason || ''}: ${connection || ''}`);
}
await global.reloadHandler(true).catch(console.error);
}
}
}
process.on('uncaughtException', console.error);
let isInit = true;
let handler = await import('./handler.js');
global.reloadHandler = async function (restatConn) {
try {
const Handler = await import(`./handler.js?update=${Date.now()}`).catch(console.error);
if (Object.keys(Handler || {}).length) handler = Handler;
} catch (e) {
console.error(e);
}
if (restatConn) {
const oldChats = global.conn.chats;
try {
global.conn.ws.close();
} catch { }
conn.ev.removeAllListeners();
global.conn = makeWASocket(connectionOptions, { chats: oldChats });
store?.bind(conn);
// Reinicializar lidResolver con la nueva conexiΓ³n
lidResolver.conn = global.conn;
isInit = true;
}
if (!isInit) {
conn.ev.off('messages.upsert', conn.handler);
conn.ev.off('group-participants.update', conn.participantsUpdate);
conn.ev.off('groups.update', conn.groupsUpdate);
conn.ev.off('message.delete', conn.onDelete);
conn.ev.off('call', conn.onCall);
conn.ev.off('connection.update', conn.connectionUpdate);
conn.ev.off('creds.update', conn.credsUpdate);
}
conn.welcome = 'π Β‘Bienvenido/a!\n@user';
conn.bye = 'π Β‘Hasta luego!\n@user';
conn.spromote = '*[ βΉοΈ ] @user Fue promovido a administrador.*';
conn.sdemote = '*[ βΉοΈ ] @user Fue degradado de administrador.*';
conn.sDesc = '*[ βΉοΈ ] La descripciΓ³n del grupo ha sido modificada.*';
conn.sSubject = '*[ βΉοΈ ] El nombre del grupo ha sido modificado.*';
conn.sIcon = '*[ βΉοΈ ] Se ha cambiado la foto de perfil del grupo.*';
conn.sRevoke = '*[ βΉοΈ ] El enlace de invitaciΓ³n al grupo ha sido restablecido.*';
const originalHandler = handler.handler.bind(global.conn);
// HANDLER MEJORADO con procesamiento LID robusto
conn.handler = async function (chatUpdate) {
try {
if (chatUpdate.messages) {
// DEBUG: Log para rastrear el procesamiento
//console.log(`π Procesando ${chatUpdate.messages.length} mensajes...`);
// Interceptar y procesar mensajes para resolver LIDs
chatUpdate.messages = await interceptMessages(chatUpdate.messages, lidResolver);
// Procesamiento adicional especΓfico para LIDs en grupos
for (let i = 0; i < chatUpdate.messages.length; i++) {
const message = chatUpdate.messages[i];
if (message?.key?.remoteJid?.endsWith('@g.us')) {
try {
// Procesar mensaje completo una vez mΓ‘s para asegurar que todo estΓ© resuelto
const fullyProcessedMessage = await processMessageForDisplay(message, lidResolver);
chatUpdate.messages[i] = fullyProcessedMessage;
// DEBUG: Verificar si hay menciones LID sin resolver
const messageText = extractAllText(fullyProcessedMessage);
if (messageText && messageText.includes('@') && /(@\d{8,20})/.test(messageText)) {
const lidMatches = messageText.match(/@(\d{8,20})/g);
if (lidMatches) {
//console.log(`β οΈ Posibles LIDs sin resolver: ${lidMatches.join(', ')}`);
}
}
} catch (error) {
console.error('β Error en procesamiento final de mensaje:', error);
}
}
}
}
return await originalHandler(chatUpdate);
} catch (error) {
console.error('β Error en handler interceptor:', error);
return await originalHandler(chatUpdate);
}
};
conn.participantsUpdate = handler.participantsUpdate.bind(global.conn);
conn.groupsUpdate = handler.groupsUpdate.bind(global.conn);
conn.onDelete = handler.deleteUpdate.bind(global.conn);
conn.onCall = handler.callUpdate.bind(global.conn);
conn.connectionUpdate = connectionUpdate.bind(global.conn);
conn.credsUpdate = saveCreds.bind(global.conn, true);
const currentDateTime = new Date();
const messageDateTime = new Date(conn.ev);
if (currentDateTime >= messageDateTime) {
const chats = Object.entries(conn.chats).filter(([jid, chat]) => !jid.endsWith('@g.us') && chat.isChats).map((v) => v[0]);
} else {
const chats = Object.entries(conn.chats).filter(([jid, chat]) => !jid.endsWith('@g.us') && chat.isChats).map((v) => v[0]);
}
conn.ev.on('messages.upsert', conn.handler);
conn.ev.on('group-participants.update', conn.participantsUpdate);
conn.ev.on('groups.update', conn.groupsUpdate);
conn.ev.on('message.delete', conn.onDelete);
conn.ev.on('call', conn.onCall);
conn.ev.on('connection.update', conn.connectionUpdate);
conn.ev.on('creds.update', conn.credsUpdate);
isInit = false;
return true;
};
// Agregar funciones de utilidad al conn para acceso desde plugins
conn.lid = {
/**
* Obtener informaciΓ³n de usuario por LID
*/
getUserInfo: (lidNumber) => lidDataManager.getUserInfo(lidNumber),
/**
* Obtener informaciΓ³n de usuario por JID
*/
getUserInfoByJid: (jid) => lidDataManager.getUserInfoByJid(jid),
/**
* Encontrar LID por JID
*/
findLidByJid: (jid) => lidDataManager.findLidByJid(jid),
/**
* Listar todos los usuarios
*/
getAllUsers: () => lidDataManager.getAllUsers(),
/**
* Obtener estadΓsticas
*/
getStats: () => lidDataManager.getStats(),
/**
* Obtener usuarios por paΓs
*/
getUsersByCountry: () => lidDataManager.getUsersByCountry(),
/**
* Validar nΓΊmero telefΓ³nico
*/
validatePhoneNumber: (phoneNumber) => {
if (!lidResolver.phoneValidator) return false;
return lidResolver.phoneValidator.isValidPhoneNumber(phoneNumber);
},
/**
* Detectar si un LID es un nΓΊmero telefΓ³nico
*/
detectPhoneInLid: (lidString) => {
if (!lidResolver.phoneValidator) return { isPhone: false };
return lidResolver.phoneValidator.detectPhoneInLid(lidString);
},
/**
* Forzar guardado del cachΓ©
*/
forceSave: () => {
try {
lidResolver.forceSave();
return true;
} catch (error) {
console.error('Error guardando cachΓ© LID:', error);
return false;
}
},
/**
* Mostrar informaciΓ³n completa del cachΓ©
*/
getCacheInfo: () => {
try {
const stats = lidDataManager.getStats();
const analysis = lidResolver.analyzePhoneNumbers();
return `π± *ESTADΓSTICAS DEL CACHΓ LID*
π *General:*
β’ Total de entradas: ${stats.total}
β’ Entradas vΓ‘lidas: ${stats.valid}
β’ No encontradas: ${stats.notFound}