-
Notifications
You must be signed in to change notification settings - Fork 329
Expand file tree
/
Copy pathindex.ts
More file actions
662 lines (580 loc) · 24.2 KB
/
index.ts
File metadata and controls
662 lines (580 loc) · 24.2 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
import './config.js';
import fs from 'fs';
import { existsSync, mkdirSync, rmSync } from 'fs';
import path, { dirname } from 'path';
import chalk from 'chalk';
import syntaxerror from 'syntax-error';
import { parsePhoneNumber as PhoneNumber } from 'awesome-phonenumber';
import readline from 'readline';
import QRCode from 'qrcode';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import { smsg } from './lib/myfunc.js';
import { compileAll } from './lib/compile.js';
import makeWASocket, {
useMultiFileAuthState,
DisconnectReason,
fetchLatestBaileysVersion,
Browsers,
jidDecode,
jidNormalizedUser,
makeCacheableSignalKeyStore,
delay
} from '@whiskeysockets/baileys';
import NodeCache from 'node-cache';
import pino from 'pino';
import config from './config.js';
import store from './lib/lightweight_store.js';
import SaveCreds from './lib/session.js';
import { server, PORT } from './lib/server.js';
import { printLog } from './lib/print.js';
import { writeErrorLog } from './lib/logger.js';
import {
handleMessages,
handleGroupParticipantUpdate,
handleStatus,
handleCall
} from './lib/messageHandler.js';
import commandHandler from './lib/commandHandler.js';
store.readFromFile();
setInterval(() => store.writeToFile(), config.storeWriteInterval || 10000);
setInterval(() => {
if (global.gc) {
global.gc();
console.log('🧹 Garbage collection completed');
}
}, 60_000);
setInterval(() => {
const used = process.memoryUsage().rss / 1024 / 1024;
if (used > 400) {
printLog('warning', 'RAM too high (>400MB), restarting bot...');
process.exit(1);
}
}, 30_000);
const phoneNumber: string = config.pairingNumber || config.ownerNumber || "923051391005";
// Auto-create data directory and default files on startup
const DATA_DEFAULTS: Record<string, any> = {
'owner.json': [],
'banned.json': [],
'premium.json': [],
'warnings.json': {},
'notes.json': {},
'autoAi.json': {},
'messageCount.json': { isPublic: true, messageCount: {} },
'userGroupData.json': { users: [], groups: [], antilink: {}, antibadword: {}, warnings: {}, sudo: [], welcome: {}, goodbye: {}, chatbot: {}, autoReaction: false },
'autoStatus.json': { enabled: false },
'autoread.json': { enabled: false },
'autotyping.json': { enabled: false },
'pmblocker.json': { enabled: false },
'anticall.json': { enabled: false },
'stealthMode.json': { enabled: false },
'autoBio.json': { enabled: false, customBio: null },
'autoReaction.json': { enabled: false },
'antidelete.json': { enabled: false },
'antilink.json': {},
'antibadword.json': {},
};
fs.mkdirSync('./data', { recursive: true });
for (const [file, def] of Object.entries(DATA_DEFAULTS)) {
const fp = `./data/${file}`;
if (!fs.existsSync(fp)) fs.writeFileSync(fp, JSON.stringify(def, null, 2));
}
let owner: string[] = [];
try {
owner = JSON.parse(fs.readFileSync('./data/owner.json', 'utf-8'));
} catch { owner = []; }
global.botname = config.botName || "MEGA-MD";
global.themeemoji = "•";
const pairingCode = !process.argv.includes("--qr-code");
const useMobile = process.argv.includes("--mobile");
let rl: readline.Interface | null = null;
let rlClosed = false;
if (process.stdin.isTTY && !config.pairingNumber) {
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.on('close', () => { rlClosed = true; });
}
const question = (text: string): Promise<string> => {
if (rl && !rlClosed) {
return new Promise((resolve) => rl!.question(text, resolve as any));
} else {
return Promise.resolve(config.ownerNumber || phoneNumber);
}
};
process.on('exit', () => {
if (rl && !rlClosed) rl.close();
});
process.on('SIGINT', () => {
if (rl && !rlClosed) rl.close();
process.exit(0);
});
function ensureSessionDirectory(): string {
const sessionPath = path.join(__dirname, 'session');
if (!existsSync(sessionPath)) {
mkdirSync(sessionPath, { recursive: true });
}
return sessionPath;
}
function hasValidSession(): boolean {
try {
const credsPath = path.join(__dirname, 'session', 'creds.json');
if (!existsSync(credsPath)) return false;
const fileContent = fs.readFileSync(credsPath, 'utf8');
if (!fileContent || fileContent.trim().length === 0) {
printLog('warning', 'creds.json exists but is empty');
return false;
}
try {
const creds = JSON.parse(fileContent);
if (!creds.noiseKey || !creds.signedIdentityKey || !creds.signedPreKey) {
printLog('warning', 'creds.json is missing required fields');
return false;
}
if (creds.registered === false) {
printLog('warning', 'Session not registered. Clearing for fresh pairing...');
try { rmSync(path.join(__dirname, 'session'), { recursive: true, force: true }); } catch (_e: any) { /* ignore */ }
return false;
}
printLog('success', 'Valid and registered session credentials found');
return true;
} catch (_parseError: any) {
printLog('warning', 'creds.json contains invalid JSON');
return false;
}
} catch (error: any) {
printLog('error', `Error checking session validity: ${error.message}`);
return false;
}
}
async function initializeSession(): Promise<boolean> {
ensureSessionDirectory();
const txt = config.sessionId;
if (!txt) {
if (hasValidSession()) {
printLog('success', 'Existing session found. Using saved credentials');
return true;
}
return false;
}
if (hasValidSession()) return true;
try {
await SaveCreds(txt);
await delay(2000);
if (hasValidSession()) {
printLog('success', 'Session file verified and valid');
await delay(1000);
return true;
} else {
printLog('error', 'Session file not valid after download');
return false;
}
} catch (error: any) {
printLog('error', `Error downloading session: ${error.message}`);
return false;
}
}
server.listen(PORT, () => {
printLog('success', `Server listening on port ${PORT}`);
});
async function startQasimDev(): Promise<any> {
try {
const { version } = await fetchLatestBaileysVersion();
ensureSessionDirectory();
await delay(1000);
const { state, saveCreds } = await useMultiFileAuthState(`./session`);
const _saveCreds = async () => {
ensureSessionDirectory();
await saveCreds();
};
const msgRetryCounterCache = new NodeCache();
const ghostMode = await store.getSetting('global', 'stealthMode');
const isGhostActive = ghostMode && ghostMode.enabled;
const QasimDev = makeWASocket({
version,
logger: pino({ level: 'silent' }),
browser: Browsers.macOS('Chrome'),
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, pino({ level: "fatal" }).child({ level: "fatal" })),
},
markOnlineOnConnect: !isGhostActive,
generateHighQualityLinkPreview: true,
syncFullHistory: false,
getMessage: async (key: any) => {
const jid = jidNormalizedUser(key.remoteJid);
const msg = await store.loadMessage(jid, key.id);
return msg?.message || "";
},
msgRetryCounterCache,
defaultQueryTimeoutMs: 60000,
connectTimeoutMs: 60000,
keepAliveIntervalMs: 10000,
}) as any;
QasimDev.store = store;
const originalSendPresenceUpdate = QasimDev.sendPresenceUpdate;
const originalReadMessages = QasimDev.readMessages;
const originalSendReceipt = QasimDev.sendReceipt;
QasimDev.sendPresenceUpdate = async function (...args: any[]) {
const ghostMode = await store.getSetting('global', 'stealthMode');
if (ghostMode && ghostMode.enabled) {
printLog('info', '👻 Blocked presence update (stealth mode)');
return;
}
return originalSendPresenceUpdate.apply(this, args);
};
QasimDev.readMessages = async function (...args: any[]) {
const ghostMode = await store.getSetting('global', 'stealthMode');
if (ghostMode && ghostMode.enabled) return;
return originalReadMessages.apply(this, args);
};
if (originalSendReceipt) {
QasimDev.sendReceipt = async function (...args: any[]) {
const ghostMode = await store.getSetting('global', 'stealthMode');
if (ghostMode && ghostMode.enabled) return;
return originalSendReceipt.apply(this, args);
};
}
const originalQuery = QasimDev.query;
QasimDev.query = async function (node: any, ...args: any[]) {
const ghostMode = await store.getSetting('global', 'stealthMode');
if (ghostMode && ghostMode.enabled) {
if (node && node.tag === 'receipt') return;
if (node && node.attrs && (node.attrs.type === 'read' || node.attrs.type === 'read-self')) return;
}
return originalQuery.apply(this, [node, ...args]);
};
QasimDev.isGhostMode = async () => {
const ghostMode = await store.getSetting('global', 'stealthMode');
return ghostMode && ghostMode.enabled;
};
QasimDev.ev.on('creds.update', _saveCreds);
store.bind(QasimDev.ev);
QasimDev.ev.on('messages.upsert', async (chatUpdate: any) => {
try {
const mek = chatUpdate.messages[0];
if (!mek.message) return;
mek.message = (Object.keys(mek.message)[0] === 'ephemeralMessage')
? mek.message.ephemeralMessage.message
: mek.message;
if (mek.key && mek.key.remoteJid === 'status@broadcast') {
await handleStatus(QasimDev, chatUpdate);
return;
}
if (!QasimDev.public && !mek.key.fromMe && chatUpdate.type === 'notify') {
const isGroup = mek.key?.remoteJid?.endsWith('@g.us');
if (!isGroup) return;
}
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return;
if (QasimDev?.msgRetryCounterCache) {
QasimDev.msgRetryCounterCache.clear();
}
try {
await handleMessages(QasimDev, chatUpdate);
} catch (err: any) {
printLog('error', `Error in handleMessages: ${err.message}`);
if (mek.key && mek.key.remoteJid) {
await QasimDev.sendMessage(mek.key.remoteJid, {
text: '❌ An error occurred while processing your message.',
contextInfo: {
forwardingScore: 1,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363319098372999@newsletter',
newsletterName: 'GlobalTechInc',
serverMessageId: -1
}
}
}).catch(console.error);
}
}
} catch (err: any) {
printLog('error', `Error in messages.upsert: ${err.message}`);
}
});
QasimDev.decodeJid = (jid: any) => {
if (!jid) return jid;
if (/:\d+@/gi.test(jid)) {
const decode = jidDecode(jid) || {};
return (decode as any).user && (decode as any).server && (decode as any).user + '@' + (decode as any).server || jid;
} else return jid;
};
QasimDev.ev.on('contacts.update', (update: any[]) => {
for (const contact of update) {
const id = QasimDev.decodeJid(contact.id);
if (store && store.contacts) (store.contacts as any)[id] = { id, name: contact.notify };
}
});
QasimDev.getName = (jid: any, withoutContact = false) => {
const id = QasimDev.decodeJid(jid);
withoutContact = QasimDev.withoutContact || withoutContact;
let v: any;
if (id.endsWith("@g.us")) return new Promise(async (resolve) => {
v = (store.contacts as any)[id] || {};
if (!(v.name || v.subject)) v = QasimDev.groupMetadata(id) || {};
resolve(v.name || v.subject || PhoneNumber('+' + id.replace('@s.whatsapp.net', '')).number?.international);
});
else v = id === '0@s.whatsapp.net' ? {
id,
name: 'WhatsApp'
} : id === QasimDev.decodeJid(QasimDev.user.id) ?
QasimDev.user :
((store.contacts as any)[id] || {});
return (withoutContact ? '' : v.name) || v.subject || v.verifiedName || PhoneNumber('+' + jid.replace('@s.whatsapp.net', '')).number?.international;
};
QasimDev.public = true;
QasimDev.serializeM = (m: any) => smsg(QasimDev, m, store);
const isRegistered = state.creds?.registered === true;
if (pairingCode && !isRegistered) {
if (useMobile) throw new Error('Cannot use pairing code with mobile api');
let phoneNumberInput: string;
if (config.pairingNumber) {
phoneNumberInput = config.pairingNumber;
} else if (process.env.PAIRING_NUMBER) {
phoneNumberInput = process.env.PAIRING_NUMBER;
} else if (rl && !rlClosed) {
phoneNumberInput = await question(chalk.bgBlack(chalk.greenBright(`Please type your WhatsApp number 😍\nFormat: 923001234567 (without + or spaces) : `)));
} else {
phoneNumberInput = phoneNumber;
printLog('info', `Using default phone number: ${phoneNumberInput}`);
}
phoneNumberInput = phoneNumberInput.replace(/[^0-9]/g, '');
const pn = PhoneNumber('+' + phoneNumberInput);
if (!pn.valid) {
printLog('error', 'Invalid phone number format');
if (rl && !rlClosed) rl.close();
process.exit(1);
}
const doPairing = async (num: string, attempt: number = 1): Promise<void> => {
try {
let code = await QasimDev.requestPairingCode(num);
code = code?.match(/.{1,4}/g)?.join("-") || code;
console.log(chalk.black(chalk.bgGreen(`Your Pairing Code : `)), chalk.black(chalk.white(code)));
printLog('success', `Pairing code generated: ${code}`);
if (rl && !rlClosed) { rl.close(); rl = null; }
} catch (error: any) {
if (attempt < 3) {
try { rmSync('./session', { recursive: true, force: true }); } catch (_e: any) { /* ignore */ }
await delay(3000);
startQasimDev();
} else {
printLog('error', 'All 3 pairing attempts failed. Please restart manually.');
}
}
};
setTimeout(() => doPairing(phoneNumberInput), 3000);
} else if (isRegistered) {
if (rl && !rlClosed) {
rl.close();
rl = null;
}
} else {
printLog('warning', 'Waiting for connection to establish...');
if (rl && !rlClosed) {
rl.close();
rl = null;
}
}
QasimDev.ev.on('connection.update', async (s: any) => {
const { connection, lastDisconnect, qr } = s;
if (qr) {
if (!pairingCode) {
try {
console.log(await QRCode.toString(qr, { type: 'terminal', small: true }));
} catch (_e: any) { console.log('QR:', qr); }
}
}
if (connection === "open") {
printLog('success', 'Bot connected successfully!');
try {
const setbioModule = await import('./plugins/setbio.js');
const startAutoBio = setbioModule.startAutoBio || (setbioModule.default as any)?.startAutoBio;
if (typeof startAutoBio === 'function') startAutoBio(QasimDev);
} catch (e: any) {
printLog('error', `Failed to start auto bio: ${e.message}`);
}
const ghostMode = await store.getSetting('global', 'stealthMode');
if (ghostMode && ghostMode.enabled) {
printLog('info', '👻 STEALTH MODE ACTIVE');
}
printLog('success', 'Connected to => ' + JSON.stringify(QasimDev.user, null, 2));
try {
const botNumber = QasimDev.user.id.split(':')[0] + '@s.whatsapp.net';
const ghostStatus = (ghostMode && ghostMode.enabled) ? '\n👻 Stealth Mode: ACTIVE' : '';
await QasimDev.sendMessage(botNumber, {
text: `🤖 Bot Connected Successfully!\n\n⏰ Time: ${new Date().toLocaleString()}\n✅ Status: Online and Ready!${ghostStatus}\n\n✅Make sure to join below channel`,
contextInfo: {
forwardingScore: 1,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363319098372999@newsletter',
newsletterName: 'GlobalTechInc',
serverMessageId: -1
}
}
});
} catch (error: any) {
printLog('error', `Failed to send connection message: ${error.message}`);
}
await delay(1999);
try { owner = JSON.parse(fs.readFileSync('./data/owner.json', 'utf-8')); } catch (_e: any) {}
printLog('info', `[ ${config.botName || 'MEGA-MD'} ]`);
printLog('info', `WA NUMBER : ${owner[0] || config.ownerNumber || ''}`);
printLog('success', `Bot Connected Successfully!`);
printLog('info', `Plugins : ${commandHandler.commands.size}`);
printLog('info', `Prefixes : ${config.prefixes.join(', ')}`);
printLog('store', `Backend : ${store.getStats().backend}`);
console.log();
}
if (connection === 'close') {
const statusCode = lastDisconnect?.error?.output?.statusCode;
const shouldReconnect = statusCode !== DisconnectReason.loggedOut && statusCode !== 401;
if (statusCode === DisconnectReason.loggedOut || statusCode === 401) {
try { rmSync('./session', { recursive: true, force: true }); } catch (_e: any) { /* ignore */ }
await delay(3000);
startQasimDev();
return;
}
if (shouldReconnect) {
printLog('connection', 'Reconnecting in 5 seconds...');
await delay(5000);
startQasimDev();
}
}
});
QasimDev.ev.on('call', async (calls: any) => {
await handleCall(QasimDev, calls);
});
QasimDev.ev.on('group-participants.update', async (update: any) => {
await handleGroupParticipantUpdate(QasimDev, update);
});
QasimDev.ev.on('status.update', async (status: any) => {
await handleStatus(QasimDev, status);
});
QasimDev.ev.on('messages.reaction', async (reaction: any) => {
await handleStatus(QasimDev, reaction);
});
return QasimDev;
} catch (error: any) {
printLog('error', `Error in startQasimDev: ${error.message}`);
if (rl && !rlClosed) {
rl.close();
rl = null;
}
await delay(5000);
startQasimDev();
}
}
async function main() {
await compileAll();
await commandHandler.loadCommands();
printLog('info', 'Starting MEGA MD BOT...');
await initializeSession();
await delay(3000);
startQasimDev().catch((error: any) => {
printLog('error', `Fatal error: ${error.message}`);
if (rl && !rlClosed) rl.close();
process.exit(1);
});
}
main();
// Session cleanup interval
const sessionDir = path.join(process.cwd(), 'session');
setInterval(() => {
if (!fs.existsSync(sessionDir)) return;
fs.readdir(sessionDir, (err, files) => {
if (err) return;
for (const file of files) {
if (file === 'creds.json') continue;
if (file.startsWith('app-state-sync-key-')) continue;
fs.unlink(path.join(sessionDir, file), () => {});
}
});
}, 3 * 60 * 1000);
// Temp folder setup
const customTemp = path.join(process.cwd(), 'temp');
if (!fs.existsSync(customTemp)) fs.mkdirSync(customTemp, { recursive: true });
process.env.TMPDIR = customTemp;
process.env.TEMP = customTemp;
process.env.TMP = customTemp;
// Temp folder cleanup
setInterval(() => {
fs.readdir(customTemp, (err, files) => {
if (err) return;
for (const file of files) {
const filePath = path.join(customTemp, file);
fs.stat(filePath, (err, stats) => {
if (!err && Date.now() - stats.mtimeMs > 3 * 60 * 60 * 1000) {
fs.unlink(filePath, () => {});
}
});
}
});
}, 1 * 60 * 60 * 1000);
// Syntax check dist files
const folders = [
path.join(__dirname, './dist/lib'),
path.join(__dirname, './dist/plugins')
];
folders.forEach(folder => {
if (!fs.existsSync(folder)) return;
fs.readdirSync(folder)
.filter(file => file.endsWith('.js'))
.forEach(file => {
const filePath = path.join(folder, file);
try {
const code = fs.readFileSync(filePath, 'utf-8');
const err = syntaxerror(code, file, {
sourceType: 'module',
allowAwaitOutsideFunction: true
});
if (err) {
console.error(chalk.red(`❌ Syntax error in ${filePath}:\n${err}`));
}
} catch (e: any) {
console.error(chalk.yellow(`⚠️ Cannot read file ${filePath}:\n${e}`));
}
});
});
// Error handlers
process.on('uncaughtException', (err) => {
printLog('error', `Uncaught Exception: ${(err as any).message}`);
console.error((err as any).stack);
writeErrorLog({
type: 'uncaughtException',
error: (err as any).message,
stack: (err as any).stack,
timestamp: new Date().toISOString()
});
});
process.on('unhandledRejection', (err) => {
printLog('error', `Unhandled Rejection: ${(err as any).message}`);
console.error((err as any).stack);
writeErrorLog({
type: 'unhandledRejection',
error: (err as any).message,
stack: (err as any).stack,
timestamp: new Date().toISOString()
});
});
server.on('error', (error) => {
if ((error as any).code === 'EADDRINUSE') {
printLog('error', `Address localhost:${PORT} in use`);
writeErrorLog({
type: 'serverError',
error: `Address localhost:${PORT} in use`,
timestamp: new Date().toISOString()
});
server.close();
} else {
printLog('error', `Server error: ${error.message}`);
writeErrorLog({
type: 'serverError',
error: error.message,
stack: (error as any).stack,
timestamp: new Date().toISOString()
});
}
});