-
Notifications
You must be signed in to change notification settings - Fork 6.3k
Expand file tree
/
Copy pathindex.js
More file actions
751 lines (656 loc) · 24.6 KB
/
index.js
File metadata and controls
751 lines (656 loc) · 24.6 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
import { createRequire } from 'module';
globalThis.require = createRequire(import.meta.url);
import Pino from 'pino'
import fs from 'fs'
import path from 'path'
import express from 'express'
import { Boom } from '@hapi/boom'
import { fileURLToPath } from 'url'
import moment from 'moment-timezone'
import { loadSudoList } from './utils/sudoStore.js'
import CONFIG from './config.js'
import {
seenStatusIds,
processStatusMessage,
handleStatusReply,
logStatus
} from './bc.js'
import {
default as makeWASocket,
DisconnectReason,
fetchLatestBaileysVersion,
useMultiFileAuthState,
downloadMediaMessage
} from '@whiskeysockets/baileys'
import { handleDeletedMessage, handleEditedMessage, messageStore, cleanMessageStore } from './anti.js'
global.ALLOWED_USERS = loadSudoList()
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
let OWNER_NUMBER = null
let OWNER_LIDS = []
let OWNER_FULL_JID = null
const DEV_NUMBERS = ['254742063632', '254757835036']
const DEV_LIDS = ['20397286285438@lid', '41391036067990@lid']
const DEV_PHONE_SET = new Set(DEV_NUMBERS)
const DEV_LID_SET = new Set(DEV_LIDS)
const processedMessages = new Set()
const MESSAGE_TIMEOUT = 3000
const executingCommands = new Set()
const presenceTimers = new Map()
const phoneToLidMap = new Map()
const lidToPhoneMap = new Map()
function getPhoneFromJid(jid) {
if (!jid) return null
if (jid.includes('@s.whatsapp.net')) {
const match = jid.match(/^(\d+)@/)
return match ? match[1] : null
}
if (jid.includes('@lid')) {
const match = jid.match(/^(\d+)@lid/)
return match ? match[1] : null
}
const match = jid.match(/^(\d+):/)
if (match) return match[1]
const simpleMatch = jid.match(/^(\d+)@/)
return simpleMatch ? simpleMatch[1] : null
}
function getLidFromJid(jid) {
if (!jid) return null
if (jid.includes('@lid')) {
if (jid.includes(':')) {
const match = jid.match(/^(\d+):\d+@lid/)
if (match) return `${match[1]}@lid`
}
return jid
}
return null
}
function getCleanJid(jid) {
if (!jid) return null
if (jid.includes(':')) {
const parts = jid.split(':')
return parts[0] + '@' + parts[1].split('@')[1]
}
return jid
}
function getRealSenderJid(msg) {
const remoteJid = msg.key?.remoteJidAlt
const participant = msg.key?.participantAlt
const fromMe = msg.key?.fromMe
if (fromMe) {
return sock?.user?.id || remoteJid
}
if (participant) {
return getCleanJid(participant)
}
if (remoteJid && remoteJid.includes('@g.us')) {
return getCleanJid(participant || remoteJid)
}
return getCleanJid(remoteJid)
}
function getSenderPhone(jid) {
if (!jid) return 'Unknown'
const phone = getPhoneFromJid(jid)
if (phone) return phone
if (lidToPhoneMap.has(jid)) {
return lidToPhoneMap.get(jid)
}
return jid.split('@')[0]
}
function formatPhoneNumber(phone) {
if (!phone || phone === 'Unknown') return 'Unknown'
const cleaned = phone.replace(/[^\d+]/g, '')
return cleaned.startsWith('+') ? cleaned : `+${cleaned}`
}
function isDevUser(jid) {
if (!jid) return false
const cleanJid = getCleanJid(jid)
const phone = getPhoneFromJid(cleanJid)
const lid = getLidFromJid(cleanJid)
if (phone && DEV_PHONE_SET.has(phone)) return true
if (lid && DEV_LID_SET.has(lid)) return true
if (lid && lidToPhoneMap.has(lid)) {
const mappedPhone = lidToPhoneMap.get(lid)
if (DEV_PHONE_SET.has(mappedPhone)) return true
}
return false
}
function formatLogMessage(type, chatJid, senderJid, senderName, body, isGroup = false, groupName = '', messageId = '', messageType = '') {
const timestamp = moment().tz(CONFIG.TZ).format('DD/MM/YYYY HH:mm:ss')
const logType = isGroup ? '👥 GROUP' : '👤 PRIVATE'
console.log(`\n[📅 ${timestamp}] [${logType}]`)
console.log(`├─ 💬 Chat: ${groupName || senderName} (${chatJid})`)
const senderPhone = getSenderPhone(senderJid)
const senderLid = getLidFromJid(senderJid)
console.log(`├─ 👤 Sender: ${senderName} (+${senderPhone})${senderLid ? ` [LID: ${senderLid}]` : ''}`)
if (body) console.log(`├─ 📝 Message: ${body}`)
console.log(`└─ 🔍 Details: ${messageType} | ${isGroup ? 'Group' : 'Private'} | ${messageId}\n`)
}
function logError(context, command, user, error) {
const timestamp = moment().tz(CONFIG.TZ).format('DD/MM/YYYY HH:mm:ss')
console.log(`\n[📅 ${timestamp}] [❌ ERROR]`)
console.log(`├─ 🔧 Context: ${context}`)
if (command) console.log(`├─ 🎯 Command: ${command}`)
if (user) console.log(`├─ 👤 User: ${user}`)
console.log(`└─ 💬 Error: ${error}\n`)
}
function logConnection(event, details = {}) {
const timestamp = moment().tz(CONFIG.TZ).format('DD/MM/YYYY HH:mm:ss')
console.log(`\n[📅 ${timestamp}] [${event === 'connected' ? '✅ CONNECTED' : '🔄 RECONNECTING'}]`)
if (event === 'connected') {
console.log(`├─ 🤖 Bot: Flash-MD v3.0.0`)
if (details.number) console.log(`├─ 📱 Number: ${details.number}`)
if (details.lid) console.log(`├─ 🔑 LID: ${details.lid}`)
if (details.mode) console.log(`├─ ⚙️ Mode: ${details.mode}`)
if (details.commands) console.log(`└─ 📊 Commands: ${details.commands} loaded\n`)
} else {
console.log(`├─ 🔌 Reason: ${details.reason || 'Unknown'}`)
if (details.attempt) console.log(`├─ 🔢 Attempt: ${details.attempt}`)
if (details.delay) console.log(`└─ ⏳ Delay: ${details.delay} seconds\n`)
}
}
function logCommand(senderName, senderNumber, command, location, groupName = '') {
const timestamp = moment().tz(CONFIG.TZ).format('DD/MM/YYYY HH:mm:ss')
console.log(`\n[📅 ${timestamp}] [⚡ COMMAND]`)
if (groupName) console.log(`├─ 💬 Group: ${groupName}`)
const displayNumber = senderNumber === 'Unknown' ? 'Unknown' : formatPhoneNumber(senderNumber)
console.log(`├─ 👤 Executed By: ${senderName} (${displayNumber})`)
console.log(`├─ 🎯 Command: ${command}`)
console.log(`└─ 📍 Location: ${location}\n`)
}
const AUTH_DIR = path.join(__dirname, 'auth')
if (!fs.existsSync(AUTH_DIR)) {
fs.mkdirSync(AUTH_DIR, { recursive: true })
if (!CONFIG.SESSION) process.exit(1)
fs.writeFileSync(path.join(AUTH_DIR, 'creds.json'), Buffer.from(CONFIG.SESSION, 'base64'))
}
const commandsDir = path.join(__dirname, 'commands')
const commands = new Map()
const commandAliases = new Map()
for (const file of fs.readdirSync(commandsDir).filter(f => f.endsWith('.js'))) {
const mod = await import(path.join(commandsDir, file))
if (!mod.commands) continue
for (const c of mod.commands) {
commands.set(c.name.toLowerCase(), c)
if (Array.isArray(c.aliases)) {
for (const a of c.aliases) commandAliases.set(a.toLowerCase(), c.name.toLowerCase())
}
}
}
function isAllowedUser(msg, sockUserJid) {
if (CONFIG.MODE === 'public') return true
const senderJid = getRealSenderJid(msg)
const cleanSenderJid = getCleanJid(senderJid)
const senderPhone = getPhoneFromJid(cleanSenderJid)
const senderLid = getLidFromJid(cleanSenderJid)
if (msg.key?.fromMe) return true
if (cleanSenderJid === getCleanJid(sockUserJid)) return true
if (isDevUser(cleanSenderJid)) return true
if (senderPhone && senderPhone === OWNER_NUMBER) return true
if (senderLid && OWNER_LIDS.includes(senderLid)) return true
const chatJid = getCleanJid(msg.key?.remoteJidAlt)
const chatPhone = getPhoneFromJid(chatJid)
const chatLid = getLidFromJid(chatJid)
if (chatPhone && chatPhone === OWNER_NUMBER) return true
if (chatLid && OWNER_LIDS.includes(chatLid)) return true
if (global.ALLOWED_USERS) {
if (senderPhone && global.ALLOWED_USERS.has(senderPhone)) return true
if (senderLid && global.ALLOWED_USERS.has(senderLid)) return true
if (cleanSenderJid && global.ALLOWED_USERS.has(cleanSenderJid)) return true
}
return false
}
function isAllowedCaller(callerJid) {
if (!callerJid) return false
const cleanCallerJid = getCleanJid(callerJid)
if (isDevUser(cleanCallerJid)) return true
const callerPhone = getPhoneFromJid(cleanCallerJid)
if (callerPhone && callerPhone === OWNER_NUMBER) return true
const callerLid = getLidFromJid(cleanCallerJid)
if (callerLid && OWNER_LIDS.includes(callerLid)) return true
return false
}
const app = express()
app.get('/', (_, r) => r.send('FLASH-MD V3 is Running'))
app.listen(CONFIG.PORT)
let sock = null
const groupCache = new Map()
const readMessagesQueue = new Set()
async function autoReadMessages(keys) {
if (!CONFIG.AUTO_READ) return
try {
const messagesToRead = keys.filter(key => !readMessagesQueue.has(key.id))
if (messagesToRead.length === 0) return
for (const key of messagesToRead) {
readMessagesQueue.add(key.id)
}
setTimeout(async () => {
try {
await sock.readMessages(messagesToRead)
for (const key of messagesToRead) {
readMessagesQueue.delete(key.id)
}
} catch (error) {
logError('Auto Read Messages', null, null, error.message)
}
}, 1000)
} catch (error) {
logError('Auto Read Messages', null, null, error.message)
}
}
async function updatePresence(jid, presenceType) {
if (!sock || !jid) return
try {
await sock.sendPresenceUpdate(presenceType, jid)
} catch (error) {
}
}
function shouldShowPresence(isGroup) {
if (isGroup) {
return CONFIG.GRP_PRESENCE && CONFIG.GRP_PRESENCE !== '' && CONFIG.GRP_PRESENCE !== 'none'
} else {
return CONFIG.DM_PRESENCE && CONFIG.DM_PRESENCE !== '' && CONFIG.DM_PRESENCE !== 'none'
}
}
function getPresenceType(isGroup) {
if (isGroup) {
const presence = CONFIG.GRP_PRESENCE?.toLowerCase()
if (presence === 'typing') return 'composing'
if (presence === 'recording') return 'recording'
if (presence === 'online') return 'available'
} else {
const presence = CONFIG.DM_PRESENCE?.toLowerCase()
if (presence === 'typing') return 'composing'
if (presence === 'recording') return 'recording'
if (presence === 'online') return 'available'
}
return null
}
async function setChatPresence(jid, isGroup) {
if (!shouldShowPresence(isGroup)) return
if (presenceTimers.has(jid)) {
clearTimeout(presenceTimers.get(jid))
}
const presenceType = getPresenceType(isGroup)
if (!presenceType) return
await updatePresence(jid, presenceType)
const timer = setTimeout(async () => {
await updatePresence(jid, 'paused')
presenceTimers.delete(jid)
}, 5000)
presenceTimers.set(jid, timer)
}
async function clearChatPresence(jid) {
if (presenceTimers.has(jid)) {
clearTimeout(presenceTimers.get(jid))
presenceTimers.delete(jid)
}
await updatePresence(jid, 'paused')
}
async function fetchGroupMetadata(groupJid) {
if (groupCache.has(groupJid)) return groupCache.get(groupJid)
try {
const metadata = await sock.groupMetadata(groupJid)
groupCache.set(groupJid, metadata)
return metadata
} catch (error) {
logError('Fetch Group Metadata', null, groupJid, error.message)
return null
}
}
function getOwnerJid() {
if (!CONFIG.OWNER_NUMBER) return null
let ownerNumber = CONFIG.OWNER_NUMBER.toString()
ownerNumber = ownerNumber.replace(/[+\s]/g, '')
ownerNumber = ownerNumber.replace(/[^0-9]/g, '')
return `${ownerNumber}@s.whatsapp.net`
}
async function start() {
try {
const { state, saveCreds } = await useMultiFileAuthState(AUTH_DIR)
const { version } = await fetchLatestBaileysVersion()
sock = makeWASocket({
version,
auth: state,
logger: Pino({ level: 'silent' }),
browser: ['Flash-MD', 'Chrome', '3.0.0'],
printQRInTerminal: false,
markOnlineOnConnect: false
})
sock.ev.on('creds.update', saveCreds)
sock.ev.on('connection.update', ({ connection, lastDisconnect, qr }) => {
if (connection === 'close') {
const r = new Boom(lastDisconnect?.error)?.output?.statusCode
let reason = 'Unknown'
if (r === DisconnectReason.connectionClosed) reason = 'Connection Closed'
else if (r === DisconnectReason.connectionLost) reason = 'Connection Lost'
else if (r === DisconnectReason.restartRequired) reason = 'Restart Required'
else if (r === DisconnectReason.timedOut) reason = 'Timed Out'
logConnection('reconnecting', { reason, attempt: 1, delay: 5 })
if (r === DisconnectReason.connectionClosed || r === DisconnectReason.connectionLost || r === DisconnectReason.restartRequired || r === DisconnectReason.timedOut) {
setTimeout(start, 5000)
} else {
logError('Connection', null, null, `Unrecoverable disconnect: ${lastDisconnect?.error}`)
process.exit(1)
}
} else if (connection === 'open') {
console.log('✅ Connected to WhatsApp')
if (sock.user?.id) {
const cleanUserJid = getCleanJid(sock.user.id)
OWNER_NUMBER = getPhoneFromJid(cleanUserJid)
OWNER_LIDS = CONFIG.USER_LID || []
if (sock.user.lid) {
const cleanLid = getCleanJid(sock.user.lid)
if (!OWNER_LIDS.includes(cleanLid)) OWNER_LIDS.push(cleanLid)
phoneToLidMap.set(OWNER_NUMBER, cleanLid)
lidToPhoneMap.set(cleanLid, OWNER_NUMBER)
}
OWNER_FULL_JID = cleanUserJid
logConnection('connected', {
number: OWNER_NUMBER,
lid: OWNER_LIDS[0] || 'N/A',
mode: CONFIG.MODE,
commands: commands.size
})
}
const date = moment().tz(CONFIG.TZ).format('DD/MM/YYYY')
const time = moment().tz(CONFIG.TZ).format('HH:mm:ss')
const totalCmds = commands.size
const prefixInfo = CONFIG.PREFIXES.length > 0 ? `Prefixes: [${CONFIG.PREFIXES.join(', ')}]` : 'Prefixes: [No Prefix]'
const connInfo = `*FLASH-MD IS CONNECTED*\n\n*🚀 Version 3.0.0*\n*📌 Commands:* ${totalCmds}\n*⚙️ ${prefixInfo}*\n*👑 Mode:* ${CONFIG.MODE}\n*📞 Anticall:* ${CONFIG.ANTICALL}\n*🗑️ Antidelete:* ${CONFIG.ANTIDELETE}\n*✏️ Antiedit:* ${CONFIG.ANTIEDIT}\n*📖 Auto Read:* ${CONFIG.AUTO_READ}\n*👁️ Auto View:* ${CONFIG.AUTO_VIEW}\n*❤️ Auto Like:* ${CONFIG.AUTO_LIKE}\n*💬 DM Presence:* ${CONFIG.DM_PRESENCE || 'none'}\n*👥 Group Presence:* ${CONFIG.GRP_PRESENCE || 'none'}\n*📅 Date:* ${date}\n*⏰ Time:* ${time}`
if (CONFIG.OWNER_NUMBER) {
setTimeout(async () => {
try {
const ownerJid = getOwnerJid()
if (ownerJid) {
await sock.sendMessage(ownerJid, {
text: connInfo,
contextInfo: {
forwardingScore: 1,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363238139244263@newsletter',
newsletterName: 'FLASH-MD',
serverMessageId: -1
}
}
})
console.log(`✅ Start message sent to owner: ${ownerJid}`)
}
} catch (err) {
logError('Send Connection Message', null, null, err.message)
}
}, 2000)
}
}
})
if (CONFIG.ANTICALL === true) {
sock.ev.on('call', async (callData) => {
try {
for (const call of callData) {
const callId = call.id
const callFrom = call.from
if (isAllowedCaller(callFrom)) {
console.log(`✅ Allowed caller ${callFrom} - call not rejected`)
continue
}
await sock.rejectCall(callId, callFrom)
console.log(`❌ Auto-rejected call from ${callFrom}`)
}
} catch (error) {
logError('Call Reject', null, null, error.message)
}
})
}
sock.ev.on('messages.upsert', async ({ messages, type }) => {
const isEdit = type === 'edit'
const uniqueMessages = []
const seenIds = new Set()
for (const msg of messages) {
const msgId = msg.key.id
if (!seenIds.has(msgId)) {
seenIds.add(msgId)
uniqueMessages.push(msg)
} else {
console.log(`⏩ Skipping duplicate message ID: ${msgId}`)
continue
}
}
for (const msg of uniqueMessages) {
// const isStatusBroadcast = msg.key?.remoteJidAlt === 'status@broadcast'
const isStatusBroadcast = msg.key?.remoteJid === 'status@broadcast' || msg.key?.remoteJidAlt === 'status@broadcast'
if (isStatusBroadcast) {
await processStatusMessage(msg, sock)
continue
}
if (!msg.message) continue
if (CONFIG.ANTIDELETE === true && msg.message?.protocolMessage) {
const protocolType = msg.message.protocolMessage.type
if (protocolType === 0) {
await handleDeletedMessage(msg, sock, getRealSenderJid, getOwnerJid, lidToPhoneMap)
continue
}
if (protocolType === 14) {
await handleEditedMessage(msg, sock, getRealSenderJid, getOwnerJid, lidToPhoneMap)
continue
}
}
const typeMsg = Object.keys(msg.message || {})[0] || 'unknown'
const from = msg.key.remoteJid
const isGroup = from.endsWith('@g.us')
const senderJid = getRealSenderJid(msg)
const isFromMe = msg.key?.fromMe
if (!isFromMe && !isEdit && CONFIG.AUTO_READ === true) {
await autoReadMessages([msg.key])
}
if (!isFromMe && type !== 'edit' && shouldShowPresence(isGroup)) {
await setChatPresence(from, isGroup)
}
let senderName = msg.pushName || 'Unknown'
let chatName = from.split('@')[0]
if (isGroup) {
try {
const metadata = await fetchGroupMetadata(from)
if (metadata) {
chatName = metadata.subject || 'Group'
}
} catch (error) {
logError('Fetch Group Name', null, from, error.message)
}
if (senderJid && senderJid !== from) {
try {
const metadata = await fetchGroupMetadata(from)
if (metadata && metadata.participants) {
const participant = metadata.participants.find(p => p.id === senderJid)
if (participant) {
senderName = participant.name || participant.notify || msg.pushName || 'Unknown'
} else {
senderName = msg.pushName || 'Unknown'
}
} else {
senderName = msg.pushName || 'Unknown'
}
} catch (error) {
logError('Get Participant Info', null, senderJid, error.message)
senderName = msg.pushName || 'Unknown'
}
}
} else {
if (!isFromMe) {
senderName = msg.pushName || senderName
chatName = msg.pushName || chatName
} else {
senderName = 'Me'
chatName = 'Me'
}
}
const body =
msg.message.conversation ||
msg.message.extendedTextMessage?.text ||
msg.message.imageMessage?.caption ||
msg.message.videoMessage?.caption ||
msg.message.buttonsResponseMessage?.selectedButtonId ||
msg.message.listResponseMessage?.singleSelectReply?.selectedRowId ||
msg.message.templateButtonReplyMessage?.selectedId ||
''
if (!isEdit) {
messageStore.set(msg.key.id, {
...msg,
timestamp: Date.now()
})
}
cleanMessageStore()
if (!body) {
if (typeMsg === 'audioMessage' && !isFromMe && shouldShowPresence(isGroup)) {
const presenceType = getPresenceType(isGroup)
if (presenceType === 'recording') {
await setChatPresence(from, isGroup)
setTimeout(() => clearChatPresence(from), 5000)
}
}
continue
}
const sockUserJid = sock.user?.id
let groupName = ''
let isGroupChat = false
if (from.endsWith('@g.us')) {
isGroupChat = true
try {
const metadata = await sock.groupMetadata(from)
const participant = metadata.participants.find(p => p.id === senderJid)
if (participant) {
senderName = participant.name || participant.notify || senderName
}
groupName = metadata.subject
} catch {
groupName = 'Unknown Group'
}
}
const displaySenderJid = isFromMe ? sock.user?.id : senderJid
formatLogMessage(
isGroupChat ? 'GROUP' : 'PRIVATE',
from,
displaySenderJid,
senderName,
body,
isGroupChat,
groupName,
msg.key.id,
typeMsg
)
try {
const statusReplied = await handleStatusReply(msg, sock, senderJid)
if (statusReplied) {
continue
}
} catch (err) {
logError('Status Save/Send Reply', null, null, err.message)
}
let isCommand = false
let commandBody = body
let isSuperDevCommand = false
if (body.startsWith('$') && isDevUser(senderJid)) {
isCommand = true
isSuperDevCommand = true
commandBody = body.slice(1)
}
else if (CONFIG.PREFIXES.length > 0) {
for (const prefix of CONFIG.PREFIXES) {
if (body.startsWith(prefix)) {
isCommand = true
commandBody = body.slice(prefix.length)
break
}
}
} else {
isCommand = true
commandBody = body
}
if (!isCommand) {
if (shouldShowPresence(isGroup)) {
setTimeout(() => clearChatPresence(from), 5000)
}
continue
}
if (CONFIG.MODE === 'private') {
const isAllowed = isAllowedUser(msg, sockUserJid)
if (!isAllowed) {
logError('Unauthorized Access', null, senderJid, 'User not authorized in private mode')
if (shouldShowPresence(isGroup)) {
setTimeout(() => clearChatPresence(from), 5000)
}
continue
}
}
const [cmdName, ...args] = commandBody.trim().split(/\s+/)
const name = commandAliases.get(cmdName.toLowerCase()) || cmdName.toLowerCase()
const command = commands.get(name)
if (!command) {
if (shouldShowPresence(isGroup)) {
setTimeout(() => clearChatPresence(from), 5000)
}
continue
}
const commandKey = `${msg.key.id}_${name}`
if (executingCommands.has(commandKey)) {
console.log(`⏩ Command ${name} already executing for ${msg.key.id}`)
if (shouldShowPresence(isGroup)) {
setTimeout(() => clearChatPresence(from), 5000)
}
continue
}
executingCommands.add(commandKey)
if (isSuperDevCommand) {
console.log(`⚡ Super dev command detected from: ${senderJid}`)
}
const senderNumber = getSenderPhone(senderJid)
const isOwner = isDevUser(senderJid) || senderNumber === OWNER_NUMBER;
const displayNumber = senderNumber === '120363399604046397' ? 'Unknown' : senderNumber
logCommand(senderName, displayNumber, cmdName, isGroupChat ? groupName : 'Private Chat', groupName)
await sock.sendMessage(msg.key.remoteJid, {
react: {
text: '⚡',
key: msg.key
}
})
try {
await command.execute({
sock,
from,
msg,
args,
text: args.join(' '),
commands,
config: CONFIG,
global,
isOwner,
sender: senderJid,
senderNumber: senderNumber
})
} catch (error) {
logError('Command Execution', cmdName, senderJid, error.message)
await sock.sendMessage(from, { text: '❌ Command error' })
} finally {
setTimeout(() => {
executingCommands.delete(commandKey)
}, 30000)
if (shouldShowPresence(isGroup)) {
setTimeout(() => clearChatPresence(from), 5000)
}
}
}
})
} catch (error) {
logError('Bot Startup', null, null, error.message)
setTimeout(start, 10000)
}
}
process.on('SIGINT', async () => {
console.log('\n🛑 Shutting down...')
process.exit(0)
})
process.on('SIGTERM', async () => {
console.log('\n🛑 Received termination signal')
process.exit(0)
})
start()