forked from mruniquehacker/Knightbot-MD
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
683 lines (641 loc) · 31.3 KB
/
main.js
File metadata and controls
683 lines (641 loc) · 31.3 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
const settings = require('./settings');
const { loadCommands } = require('./utils');
require('./config.js');
const { isBanned } = require('./lib/isBanned');
const yts = require('youtube-yts');
const { fetchBuffer } = require('./lib/myfunc');
const ytdl = require('./lib/ytdl2');
const fs = require('fs');
const fetch = require('node-fetch');
// Command imports
const tagAllCommand = require('./commands/tagall');
const helpCommand = require('./commands/help');
const banCommand = require('./commands/ban');
const { promoteCommand } = require('./commands/promote');
const { demoteCommand } = require('./commands/demote');
const muteCommand = require('./commands/mute');
const unmuteCommand = require('./commands/unmute');
const stickerCommand = require('./commands/sticker');
const isAdmin = require('./helpers/isAdmin');
const warnCommand = require('./commands/warn');
const warningsCommand = require('./commands/warnings');
const ttsCommand = require('./commands/tts');
const { tictactoeCommand, handleTicTacToeMove } = require('./commands/tictactoe');
const { incrementMessageCount, topMembers } = require('./commands/topmembers');
const ownerCommand = require('./commands/owner');
const deleteCommand = require('./commands/delete');
const { handleAntilinkCommand, handleLinkDetection } = require('./commands/antilink');
const { Antilink } = require('./lib/antilink');
const memeCommand = require('./commands/meme');
const tagCommand = require('./commands/tag');
const jokeCommand = require('./commands/joke');
const quoteCommand = require('./commands/quote');
const factCommand = require('./commands/fact');
const weatherCommand = require('./commands/weather');
const newsCommand = require('./commands/news');
const kickCommand = require('./commands/kick');
const simageCommand = require('./commands/simage');
const attpCommand = require('./commands/attp');
const { startHangman, guessLetter } = require('./commands/hangman');
const { startTrivia, answerTrivia } = require('./commands/trivia');
const { complimentCommand } = require('./commands/compliment');
const { insultCommand } = require('./commands/insult');
const { eightBallCommand } = require('./commands/eightball');
const { lyricsCommand } = require('./commands/lyrics');
const { dareCommand } = require('./commands/dare');
const { truthCommand } = require('./commands/truth');
const { clearCommand } = require('./commands/clear');
const pingCommand = require('./commands/ping');
const aliveCommand = require('./commands/alive');
const blurCommand = require('./commands/img-blur');
const welcomeCommand = require('./commands/welcome');
const goodbyeCommand = require('./commands/goodbye');
const githubCommand = require('./commands/github');
const { handleAntiBadwordCommand, handleBadwordDetection } = require('./lib/antibadword');
const antibadwordCommand = require('./commands/antibadword');
const { handleChatbotCommand, handleChatbotResponse } = require('./commands/chatbot');
const takeCommand = require('./commands/take');
const { flirtCommand } = require('./commands/flirt');
const characterCommand = require('./commands/character');
const wastedCommand = require('./commands/wasted');
const shipCommand = require('./commands/ship');
const groupInfoCommand = require('./commands/groupinfo');
const resetlinkCommand = require('./commands/resetlink');
const staffCommand = require('./commands/staff');
const unbanCommand = require('./commands/unban');
const emojimixCommand = require('./commands/emojimix');
const { handlePromotionEvent } = require('./commands/promote');
const { handleDemotionEvent } = require('./commands/demote');
const viewOnceCommand = require('./commands/viewonce');
const clearSessionCommand = require('./commands/clearsession');
const { autoStatusCommand, handleStatusUpdate } = require('./commands/autostatus');
// Global settings
global.packname = settings.packname;
global.author = settings.author;
global.channelLink = "https://whatsapp.com/channel/0029Va90zAnIHphOuO8Msp3A";
global.ytch = "Mr Unique Hacker";
// Add this near the top of main.js with other global configurations
const channelInfo = {
contextInfo: {
forwardingScore: 999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: '120363161513685998@newsletter',
newsletterName: 'KnightBot MD',
serverMessageId: -1
}
}
};
async function handleMessages(sock, messageUpdate, printLog) {
try {
const { messages, type } = messageUpdate;
if (type !== 'notify') return;
const message = messages[0];
if (!message?.message) return;
const chatId = message.key.remoteJid;
const senderId = message.key.participant || message.key.remoteJid;
const isGroup = chatId.endsWith('@g.us');
let userMessage = message.message?.conversation?.trim().toLowerCase() ||
message.message?.extendedTextMessage?.text?.trim().toLowerCase() || '';
userMessage = userMessage.replace(/\.\s+/g, '.').trim();
// Only log command usage
if (userMessage.startsWith('.')) {
console.log(`📝 Command used in ${isGroup ? 'group' : 'private'}: ${userMessage}`);
}
// Check if user is banned (skip ban check for unban command)
if (isBanned(senderId) && !userMessage.startsWith('.unban')) {
// Only respond occasionally to avoid spam
if (Math.random() < 0.1) {
await sock.sendMessage(chatId, {
text: '❌ You are banned from using the bot. Contact an admin to get unbanned.',
...channelInfo
});
}
return;
}
// First check if it's a game move
if (/^[1-9]$/.test(userMessage) || userMessage.toLowerCase() === 'surrender') {
await handleTicTacToeMove(sock, chatId, senderId, userMessage);
return;
}
// Basic message response in private chat
if (!isGroup && (userMessage === 'hi' || userMessage === 'hello' || userMessage === 'bot' || userMessage === 'hlo' || userMessage === 'hey' || userMessage === 'bro')) {
await sock.sendMessage(chatId, {
text: 'Hi, How can I help you?\nYou can use .menu for more info and commands.',
...channelInfo
});
return;
}
if (!message.key.fromMe) incrementMessageCount(chatId, senderId);
// Check for bad words FIRST, before ANY other processing
if (isGroup && userMessage) {
await handleBadwordDetection(sock, chatId, message, userMessage, senderId);
}
// Then check for command prefix
if (!userMessage.startsWith('.')) {
if (isGroup) {
// Process non-command messages first
await handleChatbotResponse(sock, chatId, message, userMessage, senderId);
await Antilink(message, sock);
await handleBadwordDetection(sock, chatId, message, userMessage, senderId);
}
return;
}
// List of admin commands
const adminCommands = ['.mute', '.unmute', '.ban', '.unban', '.promote', '.demote', '.kick', '.tagall', '.antilink'];
const isAdminCommand = adminCommands.some(cmd => userMessage.startsWith(cmd));
let isSenderAdmin = false;
let isBotAdmin = false;
if (isGroup && isAdminCommand) {
const adminStatus = await isAdmin(sock, chatId, senderId);
isSenderAdmin = adminStatus.isSenderAdmin;
isBotAdmin = adminStatus.isBotAdmin;
if (!isBotAdmin) {
await sock.sendMessage(chatId, { text: 'Please make the bot an admin to use admin commands.', ...channelInfo });
return;
}
if (
userMessage.startsWith('.mute') ||
userMessage === '.unmute' ||
userMessage.startsWith('.ban') ||
userMessage.startsWith('.unban') ||
userMessage.startsWith('.promote') ||
userMessage.startsWith('.demote')
) {
if (!isSenderAdmin && !message.key.fromMe) {
await sock.sendMessage(chatId, {
text: 'Sorry, only group admins can use this command.',
...channelInfo
});
return;
}
}
}
// Add this near the start of your message handling logic, before processing commands
try {
const data = JSON.parse(fs.readFileSync('./data/messageCount.json'));
const senderNumber = senderId.split('@')[0];
// Allow owner to use bot even in private mode
if (!data.isPublic && senderNumber !== settings.ownerNumber) {
return; // Silently ignore messages from non-owners when in private mode
}
} catch (error) {
console.error('Error checking access mode:', error);
// Default to public mode if there's an error reading the file
}
// Command handlers
switch (true) {
case userMessage === '.simage': {
const quotedMessage = message.message?.extendedTextMessage?.contextInfo?.quotedMessage;
if (quotedMessage?.stickerMessage) {
await simageCommand(sock, quotedMessage, chatId);
} else {
await sock.sendMessage(chatId, { text: 'Please reply to a sticker with the .simage command to convert it.', ...channelInfo });
}
break;
}
case userMessage.startsWith('.kick'):
const mentionedJidListKick = message.message.extendedTextMessage?.contextInfo?.mentionedJid || [];
await kickCommand(sock, chatId, senderId, mentionedJidListKick, message);
break;
case userMessage.startsWith('.mute'):
const muteDuration = parseInt(userMessage.split(' ')[1]);
if (isNaN(muteDuration)) {
await sock.sendMessage(chatId, { text: 'Please provide a valid number of minutes.\neg to mute 10 minutes\n.mute 10', ...channelInfo });
} else {
await muteCommand(sock, chatId, senderId, muteDuration);
}
break;
case userMessage === '.unmute':
await unmuteCommand(sock, chatId, senderId);
break;
case userMessage.startsWith('.ban'):
await banCommand(sock, chatId, message);
break;
case userMessage.startsWith('.unban'):
await unbanCommand(sock, chatId, message);
break;
case userMessage === '.help' || userMessage === '.menu' || userMessage === '.bot' || userMessage === '.list':
await helpCommand(sock, chatId, global.channelLink);
break;
case userMessage === '.sticker' || userMessage=== '.s':
await stickerCommand(sock, chatId, message);
break;
case userMessage.startsWith('.warnings'):
const mentionedJidListWarnings = message.message.extendedTextMessage?.contextInfo?.mentionedJid || [];
await warningsCommand(sock, chatId, mentionedJidListWarnings);
break;
case userMessage.startsWith('.warn'):
const mentionedJidListWarn = message.message.extendedTextMessage?.contextInfo?.mentionedJid || [];
await warnCommand(sock, chatId, senderId, mentionedJidListWarn, message);
break;
case userMessage.startsWith('.tts'):
const text = userMessage.slice(4).trim();
await ttsCommand(sock, chatId, text);
break;
case userMessage === '.delete' || userMessage === '.del':
await deleteCommand(sock, chatId, message, senderId);
break;
case userMessage.startsWith('.attp'):
await attpCommand(sock, chatId, message);
break;
case userMessage.startsWith('.mode'):
// Check if sender is the owner number from settings
const senderNumber = senderId.split('@')[0];
if (senderNumber !== settings.ownerNumber) {
await sock.sendMessage(chatId, { text: 'Only bot owner can use this command!', ...channelInfo });
return;
}
// Read current data first
let data;
try {
data = JSON.parse(fs.readFileSync('./data/messageCount.json'));
} catch (error) {
console.error('Error reading access mode:', error);
await sock.sendMessage(chatId, { text: 'Failed to read bot mode status', ...channelInfo });
return;
}
const action = userMessage.split(' ')[1]?.toLowerCase();
// If no argument provided, show current status
if (!action) {
const currentMode = data.isPublic ? 'public' : 'private';
await sock.sendMessage(chatId, {
text: `Current bot mode: *${currentMode}*\n\nUsage: .mode public/private\n\nExample:\n.mode public - Allow everyone to use bot\n.mode private - Restrict to owner only`,
...channelInfo
});
return;
}
if (action !== 'public' && action !== 'private') {
await sock.sendMessage(chatId, {
text: 'Usage: .mode public/private\n\nExample:\n.mode public - Allow everyone to use bot\n.mode private - Restrict to owner only',
...channelInfo
});
return;
}
try {
// Update access mode
data.isPublic = action === 'public';
// Save updated data
fs.writeFileSync('./data/messageCount.json', JSON.stringify(data, null, 2));
await sock.sendMessage(chatId, { text: `Bot is now in *${action}* mode`, ...channelInfo });
} catch (error) {
console.error('Error updating access mode:', error);
await sock.sendMessage(chatId, { text: 'Failed to update bot access mode', ...channelInfo });
}
break;
case userMessage === '.owner':
await ownerCommand(sock, chatId);
break;
case userMessage === '.tagall':
if (isSenderAdmin || message.key.fromMe) {
await tagAllCommand(sock, chatId, senderId);
} else {
await sock.sendMessage(chatId, { text: 'Sorry, only group admins can use the .tagall command.', ...channelInfo });
}
break;
case userMessage.startsWith('.tag'):
const messageText = userMessage.slice(4).trim();
const replyMessage = message.message?.extendedTextMessage?.contextInfo?.quotedMessage || null;
await tagCommand(sock, chatId, senderId, messageText, replyMessage);
break;
case userMessage.startsWith('.antilink'):
if (!isGroup) {
await sock.sendMessage(chatId, {
text: 'This command can only be used in groups.',
...channelInfo
});
return;
}
if (!isBotAdmin) {
await sock.sendMessage(chatId, {
text: 'Please make the bot an admin first.',
...channelInfo
});
return;
}
await handleAntilinkCommand(sock, chatId, userMessage, senderId, isSenderAdmin);
break;
case userMessage === '.meme':
await memeCommand(sock, chatId);
break;
case userMessage === '.joke':
await jokeCommand(sock, chatId);
break;
case userMessage === '.quote':
await quoteCommand(sock, chatId);
break;
case userMessage === '.fact':
await factCommand(sock, chatId);
break;
case userMessage.startsWith('.weather'):
const city = userMessage.slice(9).trim();
if (city) {
await weatherCommand(sock, chatId, city);
} else {
await sock.sendMessage(chatId, { text: 'Please specify a city, e.g., .weather London', ...channelInfo });
}
break;
case userMessage === '.news':
await newsCommand(sock, chatId);
break;
case userMessage.startsWith('.ttt') || userMessage.startsWith('.tictactoe'):
const tttText = userMessage.split(' ').slice(1).join(' ');
await tictactoeCommand(sock, chatId, senderId, tttText);
break;
case userMessage.startsWith('.move'):
const position = parseInt(userMessage.split(' ')[1]);
if (isNaN(position)) {
await sock.sendMessage(chatId, { text: 'Please provide a valid position number for Tic-Tac-Toe move.', ...channelInfo });
} else {
tictactoeMove(sock, chatId, senderId, position);
}
break;
case userMessage === '.topmembers':
topMembers(sock, chatId, isGroup);
break;
case userMessage.startsWith('.hangman'):
startHangman(sock, chatId);
break;
case userMessage.startsWith('.guess'):
const guessedLetter = userMessage.split(' ')[1];
if (guessedLetter) {
guessLetter(sock, chatId, guessedLetter);
} else {
sock.sendMessage(chatId, { text: 'Please guess a letter using .guess <letter>', ...channelInfo });
}
break;
case userMessage.startsWith('.trivia'):
startTrivia(sock, chatId);
break;
case userMessage.startsWith('.answer'):
const answer = userMessage.split(' ').slice(1).join(' ');
if (answer) {
answerTrivia(sock, chatId, answer);
} else {
sock.sendMessage(chatId, { text: 'Please provide an answer using .answer <answer>', ...channelInfo });
}
break;
case userMessage.startsWith('.compliment'):
await complimentCommand(sock, chatId, message);
break;
case userMessage.startsWith('.insult'):
await insultCommand(sock, chatId, message);
break;
case userMessage.startsWith('.8ball'):
const question = userMessage.split(' ').slice(1).join(' ');
await eightBallCommand(sock, chatId, question);
break;
case userMessage.startsWith('.lyrics'):
const songTitle = userMessage.split(' ').slice(1).join(' ');
await lyricsCommand(sock, chatId, songTitle);
break;
case userMessage === '.dare':
await dareCommand(sock, chatId);
break;
case userMessage === '.truth':
await truthCommand(sock, chatId);
break;
case userMessage === '.clear':
if (isGroup) await clearCommand(sock, chatId);
break;
case userMessage.startsWith('.promote'):
const mentionedJidListPromote = message.message.extendedTextMessage?.contextInfo?.mentionedJid || [];
await promoteCommand(sock, chatId, mentionedJidListPromote, message);
break;
case userMessage.startsWith('.demote'):
const mentionedJidListDemote = message.message.extendedTextMessage?.contextInfo?.mentionedJid || [];
await demoteCommand(sock, chatId, mentionedJidListDemote, message);
break;
case userMessage === '.ping':
await pingCommand(sock, chatId);
break;
case userMessage === '.alive':
await aliveCommand(sock, chatId);
break;
case userMessage.startsWith('.blur'):
const quotedMessage = message.message?.extendedTextMessage?.contextInfo?.quotedMessage;
await blurCommand(sock, chatId, message, quotedMessage);
break;
case userMessage.startsWith('.welcome'):
if (isGroup) {
// Check admin status if not already checked
if (!isSenderAdmin) {
const adminStatus = await isAdmin(sock, chatId, senderId);
isSenderAdmin = adminStatus.isSenderAdmin;
}
if (isSenderAdmin || message.key.fromMe) {
await welcomeCommand(sock, chatId, message);
} else {
await sock.sendMessage(chatId, { text: 'Sorry, only group admins can use this command.', ...channelInfo });
}
} else {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups.', ...channelInfo });
}
break;
case userMessage.startsWith('.goodbye'):
if (isGroup) {
// Check admin status if not already checked
if (!isSenderAdmin) {
const adminStatus = await isAdmin(sock, chatId, senderId);
isSenderAdmin = adminStatus.isSenderAdmin;
}
if (isSenderAdmin || message.key.fromMe) {
await goodbyeCommand(sock, chatId, message);
} else {
await sock.sendMessage(chatId, { text: 'Sorry, only group admins can use this command.', ...channelInfo });
}
} else {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups.', ...channelInfo });
}
break;
case userMessage === '.git':
case userMessage === '.github':
case userMessage === '.sc':
case userMessage === '.script':
case userMessage === '.repo':
await githubCommand(sock, chatId);
break;
case userMessage.startsWith('.antibadword'):
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups.', ...channelInfo });
return;
}
const adminStatus = await isAdmin(sock, chatId, senderId);
isSenderAdmin = adminStatus.isSenderAdmin;
isBotAdmin = adminStatus.isBotAdmin;
if (!isBotAdmin) {
await sock.sendMessage(chatId, { text: '*Bot must be admin to use this feature*', ...channelInfo });
return;
}
await antibadwordCommand(sock, chatId, message, senderId, isSenderAdmin);
break;
case userMessage.startsWith('.chatbot'):
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups.', ...channelInfo });
return;
}
// Check if sender is admin
const chatbotAdminStatus = await isAdmin(sock, chatId, senderId);
if (!chatbotAdminStatus.isSenderAdmin) {
await sock.sendMessage(chatId, { text: '*Only admins can use this command*', ...channelInfo });
return;
}
const match = userMessage.slice(8).trim();
await handleChatbotCommand(sock, chatId, message, match);
break;
case userMessage.startsWith('.take'):
const takeArgs = userMessage.slice(5).trim().split(' ');
await takeCommand(sock, chatId, message, takeArgs);
break;
case userMessage === '.flirt':
await flirtCommand(sock, chatId);
break;
case userMessage.startsWith('.character'):
await characterCommand(sock, chatId, message);
break;
case userMessage.startsWith('.waste'):
await wastedCommand(sock, chatId, message);
break;
case userMessage === '.ship':
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups!', ...channelInfo });
return;
}
await shipCommand(sock, chatId, message);
break;
case userMessage === '.groupinfo' || userMessage === '.infogp' || userMessage === '.infogrupo':
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups!', ...channelInfo });
return;
}
await groupInfoCommand(sock, chatId, message);
break;
case userMessage === '.resetlink' || userMessage === '.revoke' || userMessage === '.anularlink':
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups!', ...channelInfo });
return;
}
await resetlinkCommand(sock, chatId, senderId);
break;
case userMessage === '.staff' || userMessage === '.admins' || userMessage === '.listadmin':
if (!isGroup) {
await sock.sendMessage(chatId, { text: 'This command can only be used in groups!', ...channelInfo });
return;
}
await staffCommand(sock, chatId, message);
break;
case userMessage.startsWith('.emojimix') || userMessage.startsWith('.emix'):
await emojimixCommand(sock, chatId, message);
break;
case userMessage.startsWith('.play') || userMessage.startsWith('.song'):
try {
const text = userMessage.split(' ').slice(1).join(' ');
if (!text) {
await sock.sendMessage(chatId, {
text: `❌ Please provide a search term!\n\nExample: .play harleys in hawaii`,
...channelInfo
});
return;
}
// Search for the video
const search = await yts(text);
if (!search.videos.length) {
await sock.sendMessage(chatId, {
text: '❌ No results found!',
...channelInfo
});
return;
}
const video = search.videos[0];
// Send processing message
await sock.sendMessage(chatId, {
text: `🎵 Downloading: ${video.title}\n⏳ Please wait...`,
...channelInfo
});
// Download and process audio
const audioData = await ytdl.mp3(video.url);
// Get thumbnail
const response = await fetch(video.thumbnail);
const thumbBuffer = await response.buffer();
// Send the audio
await sock.sendMessage(chatId, {
audio: fs.readFileSync(audioData.path),
mimetype: 'audio/mp4',
fileName: `${video.title}.mp3`,
contextInfo: {
externalAdReply: {
title: video.title,
body: global.botname,
thumbnail: thumbBuffer,
mediaType: 2,
mediaUrl: video.url,
}
}
});
// Cleanup
try {
fs.unlinkSync(audioData.path);
} catch (err) {
console.error('Error cleaning up audio file:', err);
}
} catch (error) {
console.error('Error in play command:', error);
await sock.sendMessage(chatId, {
text: '❌ Failed to play audio! Try again later.',
...channelInfo
});
}
break;
case userMessage === '.vv':
await viewOnceCommand(sock, chatId, message);
break;
case userMessage === '.clearsession' || userMessage === '.clearsesi':
await clearSessionCommand(sock, chatId, senderId);
break;
case userMessage.startsWith('.autostatus'):
const autoStatusArgs = userMessage.split(' ').slice(1);
await autoStatusCommand(sock, chatId, senderId, autoStatusArgs);
break;
default:
if (isGroup) {
// Handle non-command group messages
if (userMessage) { // Make sure there's a message
await handleChatbotResponse(sock, chatId, message, userMessage, senderId);
}
await Antilink(message, sock);
await handleBadwordDetection(sock, chatId, message, userMessage, senderId);
}
break;
}
} catch (error) {
console.error('❌ Error in message handler:', error.message);
// Only try to send error message if we have a valid chatId
if (chatId) {
await sock.sendMessage(chatId, {
text: '❌ Failed to process command!',
...channelInfo
});
}
}
}
// Instead, export the handlers along with handleMessages
module.exports = {
handleMessages,
handleGroupParticipantUpdate: async (sock, update) => {
const { id, participants, action, author } = update;
console.log('Group Update in Main:', {
id,
participants,
action,
author
}); // Add this debug log
if (action === 'promote') {
await handlePromotionEvent(sock, id, participants, author);
} else if (action === 'demote') {
await handleDemotionEvent(sock, id, participants, author);
}
},
handleStatus: async (sock, status) => {
await handleStatusUpdate(sock, status);
}
};