-
Notifications
You must be signed in to change notification settings - Fork 318
Expand file tree
/
Copy pathindex.js
More file actions
1084 lines (991 loc) · 35.9 KB
/
Copy pathindex.js
File metadata and controls
1084 lines (991 loc) · 35.9 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
/* ═════════════════════════════════
* 🚀 MALVIN KING TECH - YT
* ═════════════════════════════════
*
* 📺 YouTube : https://www.youtube.com/@malvintech2
* 💻 GitHub : https://github.com/XdKing2
* 🌐 Website : Coming Soon
* 🪀 WhatsApp : https://whatsapp.com/channel/0029VbB3YxTDJ6H15SKoBv3S
*
* 👨💻 Developer : Malvin King
* 📧 Contact : Available on GitHub
*
* ⚠️ Please do not remove this watermark
* ═════════════════════════════════
* © 2025 Malvin Tech - All Rights Reserved
* ════════════════════════════════ */
require("./settings");
const { default: makeWASocket, useMultiFileAuthState, fetchLatestBaileysVersion, DisconnectReason, delay, Browsers, makeCacheableSignalKeyStore, jidDecode, downloadContentFromMessage, getAggregateVotesInPollMessage, generateWAMessageFromContent, generateForwardMessageContent, getMessage } = require('@whiskeysockets/baileys');
const { modul } = require("./module");
const moment = require("moment-timezone");
const figlet = require("figlet");
const gradient = require("gradient-string");
const { baileys, chalk, fs, FileType, path, pino, PhoneNumber, axios, os } = modul;
const { makeInMemoryStore } = require("./lib/store/");
const { color, bgcolor } = require("./lib/color");
const { uncache, nocache } = require("./lib/loader");
const Pino = require("pino");
const readline = require("readline");
const yargs = require('yargs/yargs')
const _ = require('lodash')
const NodeCache = require("node-cache");
const { smsg, isUrl, generateMessageTag, getBuffer, getSizeMedia, fetchJson, await, sleep, reSize, tanggal, day, bulan, tahun, weton, loadModule, protex } = require("./lib/myfunc");
const { imageToWebp, videoToWebp, writeExifImg, writeExifVid, addExif, imageToWebpAvatar, videoToWebpAvatar, writeExifImgAvatar, writeExifVidAvatar } = require('./lib/exif')
const more = String.fromCharCode(8206);
const readmore = more.repeat(4001);
const prefix = "";
const type = (x) => x?.constructor?.name || (x === null ? "null" : "undefined");
const isStringSame = (x, y) => (Array.isArray(y) ? y.includes(x) : y === x);
const buttonTypes = [];
// Main database path
const dbPath = path.join(__dirname, "database");
const dbFile = path.join(dbPath, "database.json");
const pentingFile = path.join(dbPath, "penting.json");
const usersJson = path.join(dbPath, "user.json");
const contactsFile = path.join(dbPath, "contacts.vcf");
if (!fs.existsSync(dbPath)) {
fs.mkdirSync(dbPath);
console.log(chalk.greenBright("[Database] Folder created automatically."));
}
if (!fs.existsSync(dbFile)) {
fs.writeFileSync(dbFile, JSON.stringify({}, null, 2));
console.log(chalk.greenBright("[Database] database.json file created."));
}
if (!fs.existsSync(usersJson)) {
const userDefault = []
fs.writeFileSync(usersJson, JSON.stringify(userDefault, null, 2));
console.log(chalk.greenBright("[Database] user.json file created."));
}
if (!fs.existsSync(pentingFile)) {
const pentingDefault = {
blacklistJpm: [],
autoJpm: {
status: false,
interval: 0,
type: "hour",
messages: [],
lastIndex: 0,
},
};
fs.writeFileSync(pentingFile, JSON.stringify(pentingDefault, null, 2));
console.log(chalk.greenBright("[Database] penting.json file created."));
}
if (!fs.existsSync(contactsFile)) {
fs.writeFileSync(contactsFile, "");
console.log(chalk.greenBright("[Database] contacts.vcf file created."));
}
const { handleIncomingMessage } = require("./lib/user");
const pentingPath = path.join(process.cwd(), "database", "penting.json")
let penting = JSON.parse(fs.readFileSync(pentingPath))
// Save changes to file
function savePenting() {
fs.writeFileSync(pentingPath, JSON.stringify(penting, null, 2))
}
var low
try {
low = require('lowdb')
} catch (e) {
low = require('./lib/lowdb')}
const { Low, JSONFile } = low
const mongoDB = require('./lib/mongoDB')
const store = makeInMemoryStore({
logger: pino().child({
level: "silent",
stream: "store",
}),
});
global.opts = new Object(yargs(process.argv.slice(2)).exitProcess(false).parse())
global.db = new Low(
/https?:\/\//.test(opts['db'] || '') ?
new cloudDBAdapter(opts['db']) : /mongodb/.test(opts['db']) ?
new mongoDB(opts['db']) :
new JSONFile(`./database/database.json`)
)
global.DATABASE = global.db // Backwards Compatibility
global.loadDatabase = async function loadDatabase() {
if (global.db.READ) return new Promise((resolve) => setInterval(function () { (!global.db.READ ? (clearInterval(this), resolve(global.db.data == null ? global.loadDatabase() : global.db.data)) : null) }, 1 * 1000))
if (global.db.data !== null) return
global.db.READ = true
await global.db.read()
global.db.READ = false
global.db.data = {
users: {},
chats: {},
game: {},
database: {},
settings: {},
setting: {},
others: {},
sticker: {},
...(global.db.data || {})}
global.db.chain = _.chain(global.db.data)}
loadDatabase()
// ===================== CONSOLE SETUP ===================== //
console.clear();
console.log(
chalk.yellow("[ Starting ] ") + chalk.white.bold("Welcome In Terminal Mk-bot!")
);
process.on("unhandledRejection", (reason, promise) => {
console.log(chalk.red("[Error] Unhandled Rejection →"), reason);
});
process.on("rejectionHandled", (promise) => {
console.log(chalk.gray("[Info] Rejection handled."));
});
process.on("Something went wrong", function (err) {
console.log(chalk.red("[Exception]"), err);
});
// ========== STARTUP SPLASH ========== //
setTimeout(() => {
console.clear();
console.log(
chalk.cyan.bold(
figlet.textSync("M-K", { horizontalLayout: "full" })
)
);
console.log(gradient.pastel.multiline("Booting Mk-Bot Engine..."));
console.log(chalk.gray("──────────────────────────────────────────────"));
console.log(chalk.white("Welcome to Mk-Bot - YT Malvin Tech"));
console.log(chalk.gray("──────────────────────────────────────────────\n"));
console.log(
chalk.cyan.bold("Operating System Information:"),
"\n",
chalk.white(`├ Platform : ${os.platform()} ${os.arch()}`),
"\n",
chalk.white(`├ Release : ${os.release()}`),
"\n",
chalk.white(`├ Hostname : ${os.hostname()}`),
"\n",
chalk.white(`├ Total RAM: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)} GB`),
"\n",
chalk.white(`├ Free RAM : ${(os.freemem() / 1024 / 1024 / 1024).toFixed(2)} GB`),
"\n",
chalk.white(`└ Uptime : ${os.uptime()} sec\n`)
);
console.log(chalk.magenta.bold("==============================================="));
console.log(chalk.cyan.bold("Preparing environment..."));
}, 1000);
protex();
const ask = (text) => {
return new Promise((resolve) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question(text, (answer) => {
rl.close();
resolve(answer.trim());
});
});
};
// ========== FIXED SESSION HANDLER ==========
async function initializeSession() {
const sessionDir = "./session";
// Create session directory if it doesn't exist
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
const credsPath = path.join(sessionDir, "creds.json");
// Check if we have a session ID in settings
if (global.SESSION_ID && global.SESSION_ID.startsWith('starcore~')) {
console.log(chalk.blue('🔄 Found SESSION_ID in settings, injecting...'));
try {
const base64Data = global.SESSION_ID.replace('starcore~', '');
if (base64Data && /^[A-Za-z0-9+/=]+$/.test(base64Data)) {
const decodedData = Buffer.from(base64Data, "base64");
const sessionData = JSON.parse(decodedData.toString("utf-8"));
console.log(chalk.blue('📦 Session data structure:'));
console.log(chalk.blue(` - Has creds: ${!!sessionData.creds}`));
console.log(chalk.blue(` - Has keys: ${!!sessionData.keys}`));
console.log(chalk.blue(` - Registered: ${sessionData.creds?.registered || 'unknown'}`));
// Always inject the session ID data (overwrite existing)
fs.writeFileSync(credsPath, JSON.stringify(sessionData, null, 2));
console.log(chalk.green('✅ Session ID successfully injected into creds.json'));
// Verify the file was written
if (fs.existsSync(credsPath)) {
const writtenData = JSON.parse(fs.readFileSync(credsPath, 'utf-8'));
console.log(chalk.green(`✅ Verification: creds.json created with registered status: ${writtenData.creds?.registered || 'unknown'}`));
}
} else {
console.log(chalk.red('❌ Invalid base64 format in SESSION_ID'));
}
} catch (error) {
console.log(chalk.red('❌ Failed to parse SESSION_ID:'), error.message);
}
} else {
console.log(chalk.yellow('ℹ️ No SESSION_ID found in settings, using existing session files'));
}
// Use Baileys' multi-file auth state (this will read the creds.json we just created)
console.log(chalk.green('✓ Loading session using multi-file auth state'));
const { state, saveCreds } = await useMultiFileAuthState(sessionDir);
// Debug session state
console.log(chalk.blue('🔍 Session state after loading:'));
console.log(chalk.blue(` - Registered: ${state.creds.registered ? 'YES' : 'NO'}`));
console.log(chalk.blue(` - Me ID: ${state.creds.me?.id || 'Not set'}`));
console.log(chalk.blue(` - Device ID: ${state.creds.deviceId || 'Not set'}`));
return { state, saveCreds };
}
async function startsesi() {
await new Promise((r) => setTimeout(r, 2000));
console.clear();
console.log(gradient.morning(figlet.textSync("Mk-Bot v1.0.1", { horizontalLayout: "full" })));
console.log(chalk.gray("──────────────────────────────────────────────"));
console.log(chalk.cyanBright("Initializing Mk System..."));
console.log(chalk.gray("──────────────────────────────────────────────\n"));
// Initialize session first
const sessionResult = await initializeSession();
// Check session status
const hasExistingSession = sessionResult.state.creds.registered;
console.log(chalk.white(`🔐 Session status: ${hasExistingSession ? '✅ REGISTERED' : '❌ NOT REGISTERED'}`));
// Only ask for bot number if we don't have a registered session
let botNumber = global.nomorbot;
if (!hasExistingSession && (!botNumber || botNumber.trim() === "")) {
console.log(chalk.yellow("\n📱 Bot Setup Required"));
console.log(chalk.yellow("Enter bot number for pairing (ex: 26371xxxxxx): "));
botNumber = await ask("> ");
global.nomorbot = botNumber;
// Save to settings
const settingsPath = "./settings.js";
if (fs.existsSync(settingsPath)) {
let settingsContent = fs.readFileSync(settingsPath, "utf-8");
settingsContent = settingsContent.replace(/global\.nomorbot\s*=\s*(['"`]).*?\1/, `global.nomorbot = '${botNumber}'`);
fs.writeFileSync(settingsPath, settingsContent, "utf-8");
console.log(chalk.green('✓ Bot number saved to settings.js'));
}
} else if (hasExistingSession) {
console.log(chalk.green('✅ Using existing registered session'));
botNumber = global.nomorbot || sessionResult.state.creds.me?.id?.split(':')[0];
}
// Owner info (only ask if not set)
if (!global.ownernumber || global.ownernumber.trim() === "") {
console.log(chalk.yellow("\n👤 Register owner number (ex: 26371xxxxxx): "));
global.ownernumber = await ask("> ");
}
if (!global.ownername || global.ownername.trim() === "") {
console.log(chalk.yellow("What is your name?: "));
global.ownername = await ask("> ");
}
// Save owner info to settings
try {
const settingsPath = "./settings.js";
if (fs.existsSync(settingsPath)) {
let settingsContent = fs.readFileSync(settingsPath, "utf-8");
settingsContent = settingsContent
.replace(/global\.ownernumber\s*=\s*(['"`]).*?\1/, `global.ownernumber = '${global.ownernumber}'`)
.replace(/global\.ownername\s*=\s*(['"`]).*?\1/, `global.ownername = '${global.ownername}'`);
fs.writeFileSync(settingsPath, settingsContent, "utf-8");
console.log(chalk.greenBright("✓ Owner data saved to settings.js"));
}
} catch (err) {
console.log(chalk.red("Failed to save to settings.js:"), err);
}
console.log(chalk.cyanBright("\n📊 System Info:"));
console.log(chalk.white(`├ Hostname : ${os.hostname()}`));
console.log(chalk.white(`├ Platform : ${os.platform()} ${os.arch()}`));
console.log(chalk.white(`├ RAM Total: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)} GB`));
console.log(chalk.white(`├ Node.js : ${process.version}`));
console.log(chalk.white(`├ Owner : ${global.ownername} (${global.ownernumber})`));
console.log(chalk.white(`└ Bot : ${botNumber || 'Not set'}`));
console.log(chalk.gray("\n──────────────────────────────────────────────"));
console.log(chalk.blueBright("🔗 Creating connection...\n"));
// ========== BAILEYS CONNECTION ==========
const msgRetryCounterCache = new NodeCache();
const mking = makeWASocket({
logger: Pino({ level: "fatal" }),
printQRInTerminal: !sessionResult.state.creds.registered,
browser: Browsers.macOS("Safari"),
auth: {
creds: sessionResult.state.creds,
keys: makeCacheableSignalKeyStore(sessionResult.state.keys, Pino({ level: "fatal" })),
},
markOnlineOnConnect: true,
generateHighQualityLinkPreview: true,
msgRetryCounterCache,
});
// Handle credentials updates
mking.ev.on("creds.update", sessionResult.saveCreds);
// Connection event handler
mking.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect, qr } = update;
if (qr) {
console.log(chalk.yellow("📱 QR Code received - Scan with WhatsApp"));
}
if (connection === "connecting") {
console.log(chalk.yellow("🔄 Connecting to WhatsApp..."));
} else if (connection === "open") {
console.log(chalk.green.bold('✅ Connected Successfully to WhatsApp'));
console.log(chalk.white(`🤖 Bot Name: ${mking.user?.name || 'Unknown'}`));
console.log(chalk.white(`📞 Bot Number: ${mking.user?.id.split(':')[0] || 'Unknown'}`));
// Update settings with actual bot number
if (mking.user?.id) {
const actualBotNumber = mking.user.id.split(':')[0];
if (actualBotNumber !== global.nomorbot) {
global.nomorbot = actualBotNumber;
const settingsPath = "./settings.js";
if (fs.existsSync(settingsPath)) {
let settingsContent = fs.readFileSync(settingsPath, "utf-8");
settingsContent = settingsContent.replace(/global\.nomorbot\s*=\s*(['"`]).*?\1/, `global.nomorbot = '${actualBotNumber}'`);
fs.writeFileSync(settingsPath, settingsContent, "utf-8");
console.log(chalk.green(`✓ Updated bot number in settings: ${actualBotNumber}`));
}
}
}
// Load modules after successful connection
loadModule(mking);
// Auto join group
let inviteLink = "https://chat.whatsapp.com/Dx7HbtW7Cf12iCVjJBpD0x";
try {
let inviteCode = inviteLink.split('/')[3];
await mking.groupAcceptInvite(inviteCode);
console.log(chalk.green('✓ Joined support group'));
} catch (error) {
// Silent fail for group join
}
} else if (connection === "close") {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
console.log(chalk.red(`Connection closed. ${shouldReconnect ? 'Reconnecting...' : 'Please restart the bot.'}`));
if (shouldReconnect) {
setTimeout(() => {
startsesi();
}, 5000);
}
}
});
// Only request pairing code if not registered
if (!sessionResult.state.creds.registered) {
setTimeout(async () => {
try {
console.log(chalk.yellow('🔐 Requesting pairing code...'));
const code = await mking.requestPairingCode(botNumber);
const formattedCode = code?.match(/.{1,4}/g)?.join("-") || code;
console.log(chalk.black.bgGreen("🎯 PAIRING CODE:"), chalk.white.bold(formattedCode));
console.log(chalk.cyan("\n📱 How to pair:"));
console.log(chalk.white("1. Open WhatsApp → Settings → Linked Devices"));
console.log(chalk.white("2. Tap 'Link a Device'"));
console.log(chalk.white("3. Enter the code above"));
console.log(chalk.gray("──────────────────────────────────────────────"));
} catch (error) {
console.log(chalk.red('❌ Failed to get pairing code:'), error.message);
}
}, 3000);
} else {
console.log(chalk.green('✅ Session is pre-registered, no pairing needed'));
}
// Auto JPM functionality
setInterval(async () => {
try {
if (!penting.autoJpm || !penting.autoJpm.status) return
if (!penting.autoJpm.messages || !penting.autoJpm.messages.length) return
let ms = penting.autoJpm.interval * 60000
if (penting.autoJpm.type === "hour") ms *= 60
if (penting.autoJpm.type === "day") ms *= 1440
if (!penting.autoJpm._lastRun) penting.autoJpm._lastRun = Date.now()
if (Date.now() - penting.autoJpm._lastRun < ms) return
penting.autoJpm._lastRun = Date.now()
if (typeof penting.autoJpm.lastIndex !== "number") penting.autoJpm.lastIndex = 0
let idx = penting.autoJpm.lastIndex % penting.autoJpm.messages.length
let pesan = penting.autoJpm.messages[idx]
const allGroups = await mking.groupFetchAllParticipating()
const groupIDs = Object.keys(allGroups).filter(id => !penting.blacklistJpm.includes(id))
for (const gid of groupIDs) {
try {
if (pesan.type === "text") {
await mking.sendMessage(gid, { text: pesan.text })
} else {
if (!fs.existsSync(pesan.path)) continue
await mking.sendMessage(gid, {
[pesan.type]: fs.readFileSync(pesan.path),
caption: pesan.caption || ""
})
}
await sleep(global.delayJpm || 4000)
} catch (e) {
console.error(`❌ Failed to send to ${gid}:`, e.message)
}
}
penting.autoJpm.lastIndex = idx + 1
savePenting()
} catch (err) {
console.error("❌ AutoJpm Error:", err.message)
}
}, 60 * 1000)
// Call event handler
mking.ev.on('call', async (call) => {
if (!global.anticall) return
for (let ff of call) {
if (ff.isGroup == false) {
if (ff.status == "offer") {
let sendcall = await mking.sendMessage(ff.from, {
text: `@${ff.from.split("@")[0]} Sorry, I will block you because the bot owner has activated the *Anticall* feature\nIf this was accidental, please contact the owner immediately to unblock`,
contextInfo: {
mentionedJid: [ff.from],
externalAdReply: {
thumbnail: fs.readFileSync("./media/warning.jpg"),
title: "「 CALL DETECTED 」",
previewType: "PHOTO"
}
}
}, {quoted: null})
mking.sendContact(ff.from, [global.ownernumber], "Developer WhatsApp Bot", sendcall)
await sleep(10000)
await mking.updateBlockStatus(ff.from, "block")
}
}
}
})
// Message event handler
mking.ev.on("messages.upsert", async (chatUpdate) => {
try {
const kay = chatUpdate.messages[0];
if (!kay.message) return;
kay.message = Object.keys(kay.message)[0] === "ephemeralMessage"
? kay.message.ephemeralMessage.message
: kay.message;
const m = smsg(mking, kay, store);
if (!m.message) return
m.message = (Object.keys(m.message)[0] === 'ephemeralMessage') ? m.message.ephemeralMessage.message : m.message
if (m.isBaileys) return
if (m.key && m.key.remoteJid === 'status@broadcast') {
if (global.autoreadsw) mking.readMessages([m.key])
}
let fill = [global.ownernumber]
if (!mking.public && !fill.includes(m.key.remoteJid.split("@")[0]) && !m.key.fromMe && chatUpdate.type === 'notify') return
if (global.autoread) mking.readMessages([m.key])
if (
!mking.public &&
!(
kay.key.fromMe ||
(kay.key.participant && global.ownernumber.includes(kay.key.participant.split("@")[0])) ||
global.ownernumber.includes(m.sender.split("@")[0])
) &&
chatUpdate.type === "notify"
) {
return;
}
// mking.public = true;
if (kay.key.id.startsWith("BAE5") && kay.key.id.length === 16) return;
if (!m.key.fromMe && m.key.remoteJid.endsWith("@s.whatsapp.net") && m.text) {
handleIncomingMessage(mking, m.key.remoteJid);
}
require("./case")(mking, m, chatUpdate, store);
} catch (err) {
console.error("Error while processing message:", err);
}
});
// ========== COMPLETE UTILITY METHODS ==========
mking.sendTextWithMentions = async (jid, text, quoted, options = {}) =>
mking.sendMessage(
jid,
{
text: text,
contextInfo: {
mentionedJid: [...text.matchAll(/@(\d{0,16})/g)].map(
(v) => v[1] + "@s.whatsapp.net",
),
},
...options,
},
{
quoted,
},
);
mking.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;
};
mking.ev.on("contacts.update", (update) => {
for (let contact of update) {
let id = mking.decodeJid(contact.id);
if (store && store.contacts)
store.contacts[id] = {
id,
name: contact.notify,
};
}
});
mking.getName = (jid, withoutContact = false) => {
let id = mking.decodeJid(jid);
withoutContact = mking.withoutContact || withoutContact;
let v;
if (id.endsWith("@g.us"))
return new Promise(async (resolve) => {
v = store.contacts[id] || {};
if (!(v.name || v.subject)) v = mking.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 === mking.decodeJid(mking.user.id)
? mking.user
: store.contacts[id] || {};
return (
(withoutContact ? "" : v.name) ||
v.subject ||
v.verifiedName ||
PhoneNumber("+" + jid.replace("@s.whatsapp.net", "")).getNumber("international")
);
};
mking.parseMention = (text = "") => {
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(
(v) => v[1] + "@s.whatsapp.net",
);
};
mking.sendContact = async (jid, kon, quoted = "", opts = {}) => {
let list = [];
for (let i of kon) {
list.push({
displayName: await mking.getName(i),
vcard: `BEGIN:VCARD\nVERSION:3.0\nN:${await mking.getName(i)}\nFN:${await mking.getName(i)}\nitem1.TEL;waid=${i}:${i}\nitem1.X-ABLabel:Click here to chat\nitem2.EMAIL;type=INTERNET:${global.ytname || ''}\nitem2.X-ABLabel:YouTube\nitem3.URL:${global.socialm || ''}\nitem3.X-ABLabel:GitHub\nitem4.ADR:;;${global.location || ''};;;;\nitem4.X-ABLabel:Region\nEND:VCARD`,
});
}
mking.sendMessage(
jid,
{
contacts: {
displayName: `${list.length} Contact`,
contacts: list,
},
...opts,
},
{
quoted,
},
);
};
mking.setStatus = (status) => {
mking.query({
tag: "iq",
attrs: {
to: "@s.whatsapp.net",
type: "set",
xmlns: "status",
},
content: [
{
tag: "status",
attrs: {},
content: Buffer.from(status, "utf-8"),
},
],
});
return status;
};
mking.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 getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
return await mking.sendMessage(
jid,
{
image: buffer,
caption: caption,
...options,
},
{
quoted,
},
);
};
mking.sendImageAsSticker = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path)
? path
: /^data:.*?\/.*?;base64,/i.test(path)
? Buffer.from(path.split`,`[1], "base64")
: /^https?:\/\//.test(path)
? await getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifImg(buff, options);
} else {
buffer = await imageToWebp(buff);
}
await mking.sendMessage(
jid,
{
sticker: {
url: buffer,
},
...options,
},
{
quoted,
},
).then((response) => {
fs.unlinkSync(buffer);
return response;
});
};
mking.sendVideoAsSticker = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path)
? path
: /^data:.*?\/.*?;base64,/i.test(path)
? Buffer.from(path.split`,`[1], "base64")
: /^https?:\/\//.test(path)
? await getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifVid(buff, options);
} else {
buffer = await videoToWebp(buff);
}
await mking.sendMessage(
jid,
{
sticker: {
url: buffer,
},
...options,
},
{
quoted,
},
);
return buffer;
};
mking.sendImageAsStickerAvatar = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path)
? path
: /^data:.*?\/.*?;base64,/i.test(path)
? Buffer.from(path.split`,`[1], "base64")
: /^https?:\/\//.test(path)
? await getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifImgAvatar(buff, options);
} else {
buffer = await imageToWebpAvatar(buff);
}
await mking.sendMessage(
jid,
{
sticker: {
url: buffer,
},
...options,
},
{
quoted,
},
).then((response) => {
fs.unlinkSync(buffer);
return response;
});
};
mking.sendVideoAsStickerAvatar = async (jid, path, quoted, options = {}) => {
let buff = Buffer.isBuffer(path)
? path
: /^data:.*?\/.*?;base64,/i.test(path)
? Buffer.from(path.split`,`[1], "base64")
: /^https?:\/\//.test(path)
? await getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
let buffer;
if (options && (options.packname || options.author)) {
buffer = await writeExifVidAvatar(buff, options);
} else {
buffer = await videoToWebpAvatar(buff);
}
await mking.sendMessage(
jid,
{
sticker: {
url: buffer,
},
...options,
},
{
quoted,
},
);
return buffer;
};
mking.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 mking.relayMessage(jid, waMessage.message, {
messageId: waMessage.key.id,
});
return waMessage;
};
mking.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);
let trueFileName;
if (type.ext == "ogg" || type.ext == "opus") {
trueFileName = attachExtension ? filename + ".mp3" : filename;
await fs.writeFileSync(trueFileName, buffer);
} else {
trueFileName = attachExtension ? filename + "." + type.ext : filename;
await fs.writeFileSync(trueFileName, buffer);
}
return trueFileName;
};
mking.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;
};
mking.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);
let type = (await FileType.fromBuffer(data)) || {
mime: "application/octet-stream",
ext: ".bin",
};
if (data && save) fs.promises.writeFile(filename, data);
return {
res,
filename,
size: await getSizeMedia(data),
...type,
data,
};
};
mking.sendText = (jid, text, quoted = "", options) =>
mking.sendMessage(
jid,
{
text: text,
...options,
},
{
quoted,
},
);
mking.serializeM = (m) => smsg(mking, m, store);
mking.sendFile = async (jid, media, options = {}) => {
let file = await mking.getFile(media);
let mime = file.ext,
type;
// Determine file type based on extension
if (mime == "mp3") {
type = "audio";
options.mimetype = "audio/mpeg";
options.ptt = options.ptt || false;
} else if (mime == "jpg" || mime == "jpeg" || mime == "png") {
type = "image";
} else if (mime == "webp") {
type = "sticker";
} else if (mime == "mp4") {
type = "video";
} else {
type = "document";
}
// Add caption and quoted to message sending
return mking.sendMessage(
jid,
{
[type]: file.data,
caption: options.caption || "", // Add caption if exists
...options,
},
{
quoted: options.quoted || "", // Add quoted if exists
...options,
},
);
};
mking.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 mking.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 mking.sendMessage(
jid,
{
document: await getBuffer(url),
mimetype: "application/pdf",
caption: caption,
...options,
},