-
-
Notifications
You must be signed in to change notification settings - Fork 735
Expand file tree
/
Copy pathhandler.js
More file actions
1408 lines (1211 loc) · 50.8 KB
/
handler.js
File metadata and controls
1408 lines (1211 loc) · 50.8 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
/**
* Message Handler - Processes incoming messages and executes commands
*/
const config = require('./config');
const database = require('./database');
const { loadCommands } = require('./utils/commandLoader');
const { addMessage } = require('./utils/groupstats');
const { jidDecode, jidEncode } = require('@whiskeysockets/baileys');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
// Group metadata cache to prevent rate limiting
const groupMetadataCache = new Map();
const CACHE_TTL = 60000; // 1 minute cache
// Load all commands
const commands = loadCommands();
// Unwrap WhatsApp containers (ephemeral, view once, etc.)
const getMessageContent = (msg) => {
if (!msg || !msg.message) return null;
let m = msg.message;
// Common wrappers in modern WhatsApp
if (m.ephemeralMessage) m = m.ephemeralMessage.message;
if (m.viewOnceMessageV2) m = m.viewOnceMessageV2.message;
if (m.viewOnceMessage) m = m.viewOnceMessage.message;
if (m.documentWithCaptionMessage) m = m.documentWithCaptionMessage.message;
// You can add more wrappers if needed later
return m;
};
// Cached group metadata getter with rate limit handling (for non-admin checks)
const getCachedGroupMetadata = async (sock, groupId) => {
try {
// Validate group JID before attempting to fetch
if (!groupId || !groupId.endsWith('@g.us')) {
return null;
}
// Check cache first
const cached = groupMetadataCache.get(groupId);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data; // Return cached data (even if null for forbidden groups)
}
// Fetch from API
const metadata = await sock.groupMetadata(groupId);
// Cache it
groupMetadataCache.set(groupId, {
data: metadata,
timestamp: Date.now()
});
return metadata;
} catch (error) {
// Handle forbidden (403) errors - cache null to prevent retry storms
if (error.message && (
error.message.includes('forbidden') ||
error.message.includes('403') ||
error.statusCode === 403 ||
error.output?.statusCode === 403 ||
error.data === 403
)) {
// Cache null for forbidden groups to prevent repeated attempts
groupMetadataCache.set(groupId, {
data: null,
timestamp: Date.now()
});
return null; // Silently return null for forbidden groups
}
// Handle rate limit errors
if (error.message && error.message.includes('rate-overlimit')) {
const cached = groupMetadataCache.get(groupId);
if (cached) {
return cached.data;
}
return null;
}
// For other errors, try cached data as fallback
const cached = groupMetadataCache.get(groupId);
if (cached) {
return cached.data;
}
// Return null instead of throwing to prevent crashes
return null;
}
};
// Live group metadata getter (always fresh, no cache) - for admin checks
const getLiveGroupMetadata = async (sock, groupId) => {
try {
// Always fetch fresh metadata, bypass cache
const metadata = await sock.groupMetadata(groupId);
// Update cache for other features (antilink, welcome, etc.)
groupMetadataCache.set(groupId, {
data: metadata,
timestamp: Date.now()
});
return metadata;
} catch (error) {
// On error, try cached data as fallback
const cached = groupMetadataCache.get(groupId);
if (cached) {
return cached.data;
}
return null;
}
};
// Alias for backward compatibility (non-admin features use cached)
const getGroupMetadata = getCachedGroupMetadata;
// Helper functions
const isOwner = (sender) => {
if (!sender) return false;
// Normalize sender JID to handle LID
const normalizedSender = normalizeJidWithLid(sender);
const senderNumber = normalizeJid(normalizedSender);
// Check against owner numbers
return config.ownerNumber.some(owner => {
const normalizedOwner = normalizeJidWithLid(owner.includes('@') ? owner : `${owner}@s.whatsapp.net`);
const ownerNumber = normalizeJid(normalizedOwner);
return ownerNumber === senderNumber;
});
};
const isMod = (sender) => {
const number = sender.split('@')[0];
return database.isModerator(number);
};
// LID mapping cache
const lidMappingCache = new Map();
// Helper to normalize JID to just the number part
const normalizeJid = (jid) => {
if (!jid) return null;
if (typeof jid !== 'string') return null;
// Remove device ID if present (e.g., "1234567890:0@s.whatsapp.net" -> "1234567890")
if (jid.includes(':')) {
return jid.split(':')[0];
}
// Remove domain if present (e.g., "1234567890@s.whatsapp.net" -> "1234567890")
if (jid.includes('@')) {
return jid.split('@')[0];
}
return jid;
};
// Get LID mapping value from session files
const getLidMappingValue = (user, direction) => {
if (!user) return null;
const cacheKey = `${direction}:${user}`;
if (lidMappingCache.has(cacheKey)) {
return lidMappingCache.get(cacheKey);
}
const sessionPath = path.join(__dirname, config.sessionName || 'session');
const suffix = direction === 'pnToLid' ? '.json' : '_reverse.json';
const filePath = path.join(sessionPath, `lid-mapping-${user}${suffix}`);
if (!fs.existsSync(filePath)) {
lidMappingCache.set(cacheKey, null);
return null;
}
try {
const raw = fs.readFileSync(filePath, 'utf8').trim();
const value = raw ? JSON.parse(raw) : null;
lidMappingCache.set(cacheKey, value || null);
return value || null;
} catch (error) {
lidMappingCache.set(cacheKey, null);
return null;
}
};
// Normalize JID handling LID conversion
const normalizeJidWithLid = (jid) => {
if (!jid) return jid;
try {
const decoded = jidDecode(jid);
if (!decoded?.user) {
return `${jid.split(':')[0].split('@')[0]}@s.whatsapp.net`;
}
let user = decoded.user;
let server = decoded.server === 'c.us' ? 's.whatsapp.net' : decoded.server;
const mapToPn = () => {
const pnUser = getLidMappingValue(user, 'lidToPn');
if (pnUser) {
user = pnUser;
server = server === 'hosted.lid' ? 'hosted' : 's.whatsapp.net';
return true;
}
return false;
};
if (server === 'lid' || server === 'hosted.lid') {
mapToPn();
} else if (server === 's.whatsapp.net' || server === 'hosted') {
mapToPn();
}
if (server === 'hosted') {
return jidEncode(user, 'hosted');
}
return jidEncode(user, 's.whatsapp.net');
} catch (error) {
return jid;
}
};
// Build comparable JID variants (PN + LID) for matching
const buildComparableIds = (jid) => {
if (!jid) return [];
try {
const decoded = jidDecode(jid);
if (!decoded?.user) {
return [normalizeJidWithLid(jid)].filter(Boolean);
}
const variants = new Set();
const normalizedServer = decoded.server === 'c.us' ? 's.whatsapp.net' : decoded.server;
variants.add(jidEncode(decoded.user, normalizedServer));
const isPnServer = normalizedServer === 's.whatsapp.net' || normalizedServer === 'hosted';
const isLidServer = normalizedServer === 'lid' || normalizedServer === 'hosted.lid';
if (isPnServer) {
const lidUser = getLidMappingValue(decoded.user, 'pnToLid');
if (lidUser) {
const lidServer = normalizedServer === 'hosted' ? 'hosted.lid' : 'lid';
variants.add(jidEncode(lidUser, lidServer));
}
} else if (isLidServer) {
const pnUser = getLidMappingValue(decoded.user, 'lidToPn');
if (pnUser) {
const pnServer = normalizedServer === 'hosted.lid' ? 'hosted' : 's.whatsapp.net';
variants.add(jidEncode(pnUser, pnServer));
}
}
return Array.from(variants);
} catch (error) {
return [jid];
}
};
// Find participant by either PN JID or LID JID
const findParticipant = (participants = [], userIds) => {
const targets = (Array.isArray(userIds) ? userIds : [userIds])
.filter(Boolean)
.flatMap(id => buildComparableIds(id));
if (!targets.length) return null;
return participants.find(participant => {
if (!participant) return false;
const participantIds = [
participant.id,
participant.lid,
participant.userJid
]
.filter(Boolean)
.flatMap(id => buildComparableIds(id));
return participantIds.some(id => targets.includes(id));
}) || null;
};
const isAdmin = async (sock, participant, groupId, groupMetadata = null) => {
if (!participant) return false;
// Early return for non-group JIDs (DMs) - prevents slow sock.groupMetadata() call
if (!groupId || !groupId.endsWith('@g.us')) {
return false;
}
// Always fetch live metadata for admin checks
let liveMetadata = groupMetadata;
if (!liveMetadata || !liveMetadata.participants) {
if (groupId) {
liveMetadata = await getLiveGroupMetadata(sock, groupId);
} else {
return false;
}
}
if (!liveMetadata || !liveMetadata.participants) return false;
// Use findParticipant to handle LID matching
const foundParticipant = findParticipant(liveMetadata.participants, participant);
if (!foundParticipant) return false;
return foundParticipant.admin === 'admin' || foundParticipant.admin === 'superadmin';
};
const isBotAdmin = async (sock, groupId, groupMetadata = null) => {
if (!sock.user || !groupId) return false;
// Early return for non-group JIDs (DMs) - prevents slow sock.groupMetadata() call
if (!groupId.endsWith('@g.us')) {
return false;
}
try {
// Get bot's JID - Baileys stores it in sock.user.id
const botId = sock.user.id;
const botLid = sock.user.lid;
if (!botId) return false;
// Prepare bot JIDs to check - findParticipant will normalize them via buildComparableIds
const botJids = [botId];
if (botLid) {
botJids.push(botLid);
}
// ALWAYS fetch live metadata for bot admin checks (never use cached)
const liveMetadata = await getLiveGroupMetadata(sock, groupId);
if (!liveMetadata || !liveMetadata.participants) return false;
const participant = findParticipant(liveMetadata.participants, botJids);
if (!participant) return false;
return participant.admin === 'admin' || participant.admin === 'superadmin';
} catch (error) {
return false;
}
};
const isUrl = (text) => {
const urlRegex = /(https?:\/\/[^\s]+)/gi;
return urlRegex.test(text);
};
const hasGroupLink = (text) => {
const linkRegex = /chat.whatsapp.com\/([0-9A-Za-z]{20,24})/i;
return linkRegex.test(text);
};
// System JID filter - checks if JID is from broadcast/status/newsletter
const isSystemJid = (jid) => {
if (!jid) return true;
return jid.includes('@broadcast') ||
jid.includes('status.broadcast') ||
jid.includes('@newsletter') ||
jid.includes('@newsletter.');
};
// Main message handler
const handleMessage = async (sock, msg) => {
try {
// Debug logging to see all messages
// Debug log removed
if (!msg.message) return;
const from = msg.key.remoteJid;
// System message filter - ignore broadcast/status/newsletter messages
if (isSystemJid(from)) {
return; // Silently ignore system messages
}
// Auto-React System
try {
// Clear cache to get fresh config values
delete require.cache[require.resolve('./config')];
const config = require('./config');
if (config.autoReact && msg.message && !msg.key.fromMe) {
const content = msg.message.ephemeralMessage?.message || msg.message;
const text =
content.conversation ||
content.extendedTextMessage?.text ||
'';
const jid = msg.key.remoteJid;
const emojis = ['❤️','🔥','👌','💀','😁','✨','👍','🤨','😎','😂','🤝','💫'];
const mode = config.autoReactMode || 'bot';
if (mode === 'bot') {
const prefixList = ['.', '/', '#'];
if (prefixList.includes(text?.trim()[0])) {
await sock.sendMessage(jid, {
react: { text: '⏳', key: msg.key }
});
}
}
if (mode === 'all') {
const rand = emojis[Math.floor(Math.random() * emojis.length)];
await sock.sendMessage(jid, {
react: { text: rand, key: msg.key }
});
}
}
} catch (e) {
console.error('[AutoReact Error]', e.message);
}
// Unwrap containers first
const content = getMessageContent(msg);
// Note: We don't return early if content is null because forwarded status messages might not have content
// Still check for actual message content for regular processing
let actualMessageTypes = [];
if (content) {
const allKeys = Object.keys(content);
// Filter out protocol/system messages and find actual message content
const protocolMessages = ['protocolMessage', 'senderKeyDistributionMessage', 'messageContextInfo'];
actualMessageTypes = allKeys.filter(key => !protocolMessages.includes(key));
}
// We'll check for empty content later after we've processed group messages
// Use the first actual message type (conversation, extendedTextMessage, etc.)
const messageType = actualMessageTypes[0];
// from already defined above in DM block check
const sender = msg.key.fromMe ? sock.user.id.split(':')[0] + '@s.whatsapp.net' : msg.key.participant || msg.key.remoteJid;
const isGroup = from.endsWith('@g.us'); // Should always be true now due to DM block above
// Fetch group metadata immediately if it's a group
const groupMetadata = isGroup ? await getGroupMetadata(sock, from) : null;
// Anti-group mention protection (check BEFORE prefix check, as these are non-command messages)
if (isGroup) {
// Debug logging to confirm we're trying to call the handler
const groupSettings = database.getGroupSettings(from);
// Debug log removed
if (groupSettings.antigroupmention) {
// Debug log removed
}
try {
await handleAntigroupmention(sock, msg, groupMetadata);
} catch (error) {
console.error('Error in antigroupmention handler:', error);
}
}
// Track group message statistics
if (isGroup) {
addMessage(from, sender);
}
// Return early for non-group messages with no recognizable content
if (!content || actualMessageTypes.length === 0) return;
// 🔹 Button response should also check unwrapped content
const btn = content.buttonsResponseMessage || msg.message?.buttonsResponseMessage;
if (btn) {
const buttonId = btn.selectedButtonId;
const displayText = btn.selectedDisplayText;
// Handle button clicks by routing to commands
if (buttonId === 'btn_menu') {
// Execute menu command
const menuCmd = commands.get('menu');
if (menuCmd) {
await menuCmd.execute(sock, msg, [], {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
}
return;
} else if (buttonId === 'btn_ping') {
// Execute ping command
const pingCmd = commands.get('ping');
if (pingCmd) {
await pingCmd.execute(sock, msg, [], {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
}
return;
} else if (buttonId === 'btn_help') {
// Execute list command again (help)
const listCmd = commands.get('list');
if (listCmd) {
await listCmd.execute(sock, msg, [], {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
}
return;
}
}
// Get message body from unwrapped content
let body = '';
if (content.conversation) {
body = content.conversation;
} else if (content.extendedTextMessage) {
body = content.extendedTextMessage.text || '';
} else if (content.imageMessage) {
body = content.imageMessage.caption || '';
} else if (content.videoMessage) {
body = content.videoMessage.caption || '';
}
body = (body || '').trim();
// Check antiall protection (owner only feature)
if (isGroup) {
const groupSettings = database.getGroupSettings(from);
if (groupSettings.antiall) {
const senderIsAdmin = await isAdmin(sock, sender, from, groupMetadata);
const senderIsOwner = isOwner(sender);
if (!senderIsAdmin && !senderIsOwner) {
const botIsAdmin = await isBotAdmin(sock, from, groupMetadata);
if (botIsAdmin) {
await sock.sendMessage(from, { delete: msg.key });
return;
}
}
}
// Anti-tag protection (check BEFORE text check, as tagall can have no text)
if (groupSettings.antitag && !msg.key.fromMe) {
const ctx = content.extendedTextMessage?.contextInfo;
const mentionedJids = ctx?.mentionedJid || [];
const messageText = (
body ||
content.imageMessage?.caption ||
content.videoMessage?.caption ||
''
);
const textMentions = messageText.match(/@[\d+\s\-()~.]+/g) || [];
const numericMentions = messageText.match(/@\d{10,}/g) || [];
const uniqueNumericMentions = new Set();
numericMentions.forEach((mention) => {
const numMatch = mention.match(/@(\d+)/);
if (numMatch) uniqueNumericMentions.add(numMatch[1]);
});
const mentionedJidCount = mentionedJids.length;
const numericMentionCount = uniqueNumericMentions.size;
const totalMentions = Math.max(mentionedJidCount, numericMentionCount);
if (totalMentions >= 3) {
try {
const participants = groupMetadata.participants || [];
const mentionThreshold = Math.max(3, Math.ceil(participants.length * 0.5));
const hasManyNumericMentions = numericMentionCount >= 10 ||
(numericMentionCount >= 5 && numericMentionCount >= mentionThreshold);
if (totalMentions >= mentionThreshold || hasManyNumericMentions) {
const senderIsAdmin = await isAdmin(sock, sender, from, groupMetadata);
const senderIsOwner = isOwner(sender);
if (!senderIsAdmin && !senderIsOwner) {
const action = (groupSettings.antitagAction || 'delete').toLowerCase();
if (action === 'delete') {
try {
await sock.sendMessage(from, { delete: msg.key });
await sock.sendMessage(from, {
text: '⚠️ *Tagall Detected!*',
mentions: [sender]
}, { quoted: msg });
} catch (e) {
console.error('Failed to delete tagall message:', e);
}
} else if (action === 'kick') {
try {
await sock.sendMessage(from, { delete: msg.key });
} catch (e) {
console.error('Failed to delete tagall message:', e);
}
const botIsAdmin = await isBotAdmin(sock, from, groupMetadata);
if (botIsAdmin) {
try {
await sock.groupParticipantsUpdate(from, [sender], 'remove');
} catch (e) {
console.error('Failed to kick for antitag:', e);
}
const usernames = [`@${sender.split('@')[0]}`];
await sock.sendMessage(from, {
text: `🚫 *Antitag Detected!*\n\n${usernames.join(', ')} has been kicked for tagging all members.`,
mentions: [sender],
}, { quoted: msg });
}
}
return;
}
}
} catch (e) {
console.error('Error during anti-tag enforcement:', e);
}
}
}
}
// Anti-group mention protection (check BEFORE prefix check, as these are non-command messages)
if (isGroup) {
// Debug logging to confirm we're trying to call the handler
const groupSettings = database.getGroupSettings(from);
if (groupSettings.antigroupmention) {
// Debug log removed
}
try {
await handleAntigroupmention(sock, msg, groupMetadata);
} catch (error) {
console.error('Error in antigroupmention handler:', error);
}
}
// AutoSticker feature - convert images/videos to stickers automatically
if (isGroup) { // Process all messages in groups (including bot's own messages)
const groupSettings = database.getGroupSettings(from);
if (groupSettings.autosticker) {
const mediaMessage = content?.imageMessage || content?.videoMessage;
// Only process if it's an image or video (not documents)
if (mediaMessage) {
// Skip if message has a command prefix (let command handle it)
if (!body.startsWith(config.prefix)) {
try {
// Import sticker command logic
const stickerCmd = commands.get('sticker');
if (stickerCmd) {
// Execute sticker conversion silently
await stickerCmd.execute(sock, msg, [], {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
return; // Don't process as command after auto-converting
}
} catch (error) {
console.error('[AutoSticker Error]:', error);
// Continue to normal processing if autosticker fails
}
}
}
}
}
// Check for active bomb games (before prefix check)
try {
const bombModule = require('./commands/fun/bomb');
if (bombModule.gameState && bombModule.gameState.has(sender)) {
const bombCommand = commands.get('bomb');
if (bombCommand && bombCommand.execute) {
// User has active game, process input
await bombCommand.execute(sock, msg, [], {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
return; // Don't process as command
}
}
} catch (e) {
// Silently ignore if bomb command doesn't exist or has errors
}
// Check for active tictactoe games (before prefix check)
try {
const tictactoeModule = require('./commands/fun/tictactoe');
if (tictactoeModule.handleTicTacToeMove) {
// Check if user is in an active game
const isInGame = Object.values(tictactoeModule.games || {}).some(room =>
room.id.startsWith('tictactoe') &&
[room.game.playerX, room.game.playerO].includes(sender) &&
room.state === 'PLAYING'
);
if (isInGame) {
// User has active game, process input
const handled = await tictactoeModule.handleTicTacToeMove(sock, msg, {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
if (handled) return; // Don't process as command if move was handled
}
}
} catch (e) {
// Silently ignore if tictactoe command doesn't exist or has errors
}
// Check if message starts with prefix
if (!body.startsWith(config.prefix)) return;
// Parse command
const args = body.slice(config.prefix.length).trim().split(/\s+/);
const commandName = args.shift().toLowerCase();
// Get command
const command = commands.get(commandName);
if (!command) return;
// Check self mode (private mode) - only owner can use commands
if (config.selfMode && !isOwner(sender)) {
return;
}
// Permission checks
if (command.ownerOnly && !isOwner(sender)) {
return sock.sendMessage(from, { text: config.messages.ownerOnly }, { quoted: msg });
}
if (command.modOnly && !isMod(sender) && !isOwner(sender)) {
return sock.sendMessage(from, { text: '🔒 This command is only for moderators!' }, { quoted: msg });
}
if (command.groupOnly && !isGroup) {
return sock.sendMessage(from, { text: config.messages.groupOnly }, { quoted: msg });
}
if (command.privateOnly && isGroup) {
return sock.sendMessage(from, { text: config.messages.privateOnly }, { quoted: msg });
}
if (command.adminOnly && !(await isAdmin(sock, sender, from, groupMetadata)) && !isOwner(sender)) {
return sock.sendMessage(from, { text: config.messages.adminOnly }, { quoted: msg });
}
if (command.botAdminNeeded) {
const botIsAdmin = await isBotAdmin(sock, from, groupMetadata);
if (!botIsAdmin) {
return sock.sendMessage(from, { text: config.messages.botAdminNeeded }, { quoted: msg });
}
}
// Auto-typing
if (config.autoTyping) {
await sock.sendPresenceUpdate('composing', from);
}
// Execute command
console.log(`Executing command: ${commandName} from ${sender}`);
await command.execute(sock, msg, args, {
from,
sender,
isGroup,
groupMetadata,
isOwner: isOwner(sender),
isAdmin: await isAdmin(sock, sender, from, groupMetadata),
isBotAdmin: await isBotAdmin(sock, from, groupMetadata),
isMod: isMod(sender),
reply: (text) => sock.sendMessage(from, { text }, { quoted: msg }),
react: (emoji) => sock.sendMessage(from, { react: { text: emoji, key: msg.key } })
});
} catch (error) {
console.error('Error in message handler:', error);
// Don't send error messages for rate limit errors
if (error.message && error.message.includes('rate-overlimit')) {
console.warn('⚠️ Rate limit reached. Skipping error message.');
return;
}
try {
await sock.sendMessage(msg.key.remoteJid, {
text: `${config.messages.error}\n\n${error.message}`
}, { quoted: msg });
} catch (e) {
// Don't log rate limit errors when sending error messages
if (!e.message || !e.message.includes('rate-overlimit')) {
console.error('Error sending error message:', e);
}
}
}
};
// Group participant update handler
const handleGroupUpdate = async (sock, update) => {
try {
const { id, participants, action } = update;
// Validate group JID before processing
if (!id || !id.endsWith('@g.us')) {
return;
}
const groupSettings = database.getGroupSettings(id);
if (!groupSettings.welcome && !groupSettings.goodbye) return;
const groupMetadata = await getGroupMetadata(sock, id);
if (!groupMetadata) return; // Skip if metadata unavailable (forbidden or error)
// Helper to extract participant JID
const getParticipantJid = (participant) => {
if (typeof participant === 'string') {
return participant;
}
if (participant && participant.id) {
return participant.id;
}
if (participant && typeof participant === 'object') {
// Try to find JID in object
return participant.jid || participant.participant || null;
}
return null;
};
for (const participant of participants) {
const participantJid = getParticipantJid(participant);
if (!participantJid) {
console.warn('Could not extract participant JID:', participant);
continue;
}
const participantNumber = participantJid.split('@')[0];
if (action === 'add' && groupSettings.welcome) {
try {
// Get user's display name - find participant using phoneNumber or JID
let displayName = participantNumber;
// Try to find participant in group metadata
const participantInfo = groupMetadata.participants.find(p => {
const pId = p.id || p.jid || p.participant;
const pPhone = p.phoneNumber;
// Match by JID or phoneNumber
return pId === participantJid ||
pId?.split('@')[0] === participantNumber ||
pPhone === participantJid ||
pPhone?.split('@')[0] === participantNumber;
});
// Get phoneNumber JID to fetch contact name
let phoneJid = null;
if (participantInfo && participantInfo.phoneNumber) {
phoneJid = participantInfo.phoneNumber;
} else {
// Try to normalize participantJid to phoneNumber format
// If it's a LID, try to convert to phoneNumber
try {
const normalized = normalizeJidWithLid(participantJid);
if (normalized && normalized.includes('@s.whatsapp.net')) {
phoneJid = normalized;
}
} catch (e) {
// If normalization fails, try using participantJid directly if it's a valid JID
if (participantJid.includes('@s.whatsapp.net')) {
phoneJid = participantJid;
}
}
}
// Try to get contact name from phoneNumber JID
if (phoneJid) {
try {
// Method 1: Try to get from contact store if available
if (sock.store && sock.store.contacts && sock.store.contacts[phoneJid]) {
const contact = sock.store.contacts[phoneJid];
if (contact.notify && contact.notify.trim() && !contact.notify.match(/^\d+$/)) {
displayName = contact.notify.trim();
} else if (contact.name && contact.name.trim() && !contact.name.match(/^\d+$/)) {
displayName = contact.name.trim();
}
}
// Method 2: Try to fetch contact using onWhatsApp and then check store
if (displayName === participantNumber) {
try {
await sock.onWhatsApp(phoneJid);
// After onWhatsApp, check store again (might populate after check)
if (sock.store && sock.store.contacts && sock.store.contacts[phoneJid]) {
const contact = sock.store.contacts[phoneJid];
if (contact.notify && contact.notify.trim() && !contact.notify.match(/^\d+$/)) {
displayName = contact.notify.trim();
}
}
} catch (fetchError) {
// Silently handle fetch errors
}
}
} catch (contactError) {
// Silently handle contact errors
}
}
// Final fallback: use participantInfo.notify or name if available
if (displayName === participantNumber && participantInfo) {
if (participantInfo.notify && participantInfo.notify.trim() && !participantInfo.notify.match(/^\d+$/)) {
displayName = participantInfo.notify.trim();
} else if (participantInfo.name && participantInfo.name.trim() && !participantInfo.name.match(/^\d+$/)) {
displayName = participantInfo.name.trim();
}
}
// Get user's profile picture URL
let profilePicUrl = '';
try {
profilePicUrl = await sock.profilePictureUrl(participantJid, 'image');
} catch (ppError) {
// If profile picture not available, use default avatar
profilePicUrl = 'https://img.pyrocdn.com/dbKUgahg.png';
}
// Get group name and description
const groupName = groupMetadata.subject || 'the group';
const groupDesc = groupMetadata.desc || 'No description';
// Get current time string
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', {
hour: '2-digit',
minute: '2-digit',
hour12: true
});
// Create formatted welcome message
const welcomeMsg = `╭╼━≪•𝙽𝙴𝚆 𝙼𝙴𝙼𝙱𝙴𝚁•≫━╾╮\n┃𝚆𝙴𝙻𝙲𝙾𝙼𝙴: @${displayName} 👋\n┃Member count: #${groupMetadata.participants.length}\n┃𝚃𝙸𝙼𝙴: ${timeString}⏰\n╰━━━━━━━━━━━━━━━╯\n\n*@${displayName}* Welcome to *${groupName}*! 🎉\n*Group 𝙳𝙴𝚂𝙲𝚁𝙸𝙿𝚃𝙸𝙾𝙽*\n${groupDesc}\n\n> *ᴘᴏᴡᴇʀᴇᴅ ʙʏ ${config.botName}*`;
// Construct API URL for welcome image
const apiUrl = `https://api.some-random-api.com/welcome/img/7/gaming4?type=join&textcolor=white&username=${encodeURIComponent(displayName)}&guildName=${encodeURIComponent(groupName)}&memberCount=${groupMetadata.participants.length}&avatar=${encodeURIComponent(profilePicUrl)}`;
// Download the welcome image
const imageResponse = await axios.get(apiUrl, { responseType: 'arraybuffer' });
const imageBuffer = Buffer.from(imageResponse.data);
// Send the welcome image with formatted caption
await sock.sendMessage(id, {
image: imageBuffer,
caption: welcomeMsg,