-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection.js
More file actions
1015 lines (889 loc) · 31.8 KB
/
Copy pathconnection.js
File metadata and controls
1015 lines (889 loc) · 31.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Credits & Thanks to
* Developer = Zann
* Lead owner = HyuuSATAN
* Owner = Keisya
* Owner = Syura Salsabila
* Designer = Danzzz
* Wileys = Penyedia baileys
* Penyedia API
* Penyedia Scraper
*
* JANGAN HAPUS/GANTI CREDITS & THANKS TO
* JANGAN DIJUAL YA MEK
*
* Saluran Resmi Ourin:
* https://whatsapp.com/channel/0029VbB37bgBfxoAmAlsgE0t
*
*/
const {
default: makeWASocket,
DisconnectReason,
useMultiFileAuthState,
makeCacheableSignalKeyStore,
fetchLatestBaileysVersion,
makeInMemoryStore,
} = require("ourin");
const { Boom } = require("@hapi/boom");
const pino = require("pino");
const fs = require("fs");
const path = require("path");
const readline = require("readline");
const NodeCache = require("node-cache");
const config = require("../config");
const colors = require("./lib/colors");
const { extendSocket } = require("./lib/sockHelper");
const { isLid, lidToJid, decodeAndNormalize } = require("./lib/lidHelper");
const { initAutoBackup } = require("./lib/autoBackup");
const util = require("yt-search");
const groupCache = new NodeCache({ stdTTL: 5 * 60, useClones: false });
const processedMessages = new NodeCache({ stdTTL: 30, useClones: false });
const msgRetryCounterCache = new NodeCache({ stdTTL: 60, useClones: false });
const store = makeInMemoryStore({ logger: pino({ level: "silent" }) });
const storePath = path.join(process.cwd(), "storage", "baileys_store.json");
try {
if (fs.existsSync(storePath)) {
store.readFromFile(storePath);
}
} catch {}
setInterval(() => {
try {
const storeDir = path.dirname(storePath);
if (!fs.existsSync(storeDir)) {
fs.mkdirSync(storeDir, { recursive: true });
}
store.writeToFile(storePath);
} catch {}
}, 60000);
/**
* @typedef {Object} ConnectionState
* @property {boolean} isConnected - Status koneksi
* @property {Object|null} sock - Socket instance
* @property {number} reconnectAttempts - Jumlah percobaan reconnect
* @property {Date|null} connectedAt - Waktu koneksi berhasil
*/
/**
* State koneksi global
* @type {ConnectionState}
*/
const connectionState = {
isConnected: false,
isReady: false, // Flag to prevent premature message handling
sock: null,
reconnectAttempts: 0,
connectedAt: null,
};
/**
* Logger instance dengan level minimal
* @type {Object}
*/
const logger = pino({
level: "silent",
hooks: {
logMethod(inputArgs, method) {
const msg = inputArgs[0];
if (
typeof msg === "string" &&
(msg.includes("Closing") ||
msg.includes("session") ||
msg.includes("SessionEntry") ||
msg.includes("prekey"))
) {
return;
}
return method.apply(this, inputArgs);
},
},
});
/**
* Interface untuk input terminal
* @type {readline.Interface|null}
*/
let rl = null;
/**
* Membuat readline interface
* @returns {readline.Interface}
*/
function createReadlineInterface() {
if (rl) {
rl.close();
}
rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return rl;
}
/**
* Prompt untuk input
* @param {string} question - Pertanyaan
* @returns {Promise<string>} Input dari user
*/
function askQuestion(question) {
return new Promise((resolve) => {
const interface = createReadlineInterface();
interface.question(question, (answer) => {
interface.close();
resolve(answer.trim());
});
});
}
/**
* Memulai koneksi WhatsApp
* @param {Object} options - Opsi koneksi
* @param {Function} [options.onMessage] - Callback untuk pesan baru
* @param {Function} [options.onConnectionUpdate] - Callback untuk update koneksi
* @param {Function} [options.onGroupUpdate] - Callback untuk update group
* @returns {Promise<Object>} Socket connection
* @example
* const sock = await startConnection({
* onMessage: async (m) => {
* console.log('New message:', m.body);
* }
* });
*/
async function startConnection(options = {}) {
if (connectionState.sock) {
try {
connectionState.sock.end();
colors.logger.debug("WA", "Socket sebelumnya ditutup");
} catch (e) {}
connectionState.sock = null;
}
const sessionPath = path.join(
process.cwd(),
"storage",
config.session?.folderName || "session",
);
if (!fs.existsSync(sessionPath)) {
fs.mkdirSync(sessionPath, { recursive: true });
}
const { state, saveCreds } = await useMultiFileAuthState(sessionPath);
const { version, isLatest } = await fetchLatestBaileysVersion();
colors.logger.info("WA", `Versi WA: v${version.join(".")}, terbaru: ${isLatest}`);
const usePairingCode = config.session?.usePairingCode === true;
const pairingNumber = config.session?.pairingNumber || "";
const sock = makeWASocket({
version: [2, 3000, 1033105955],
logger,
printQRInTerminal:
!usePairingCode && (config.session?.printQRInTerminal ?? true),
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
browser: ["Ubuntu", "Chrome", "20.0.0"],
syncFullHistory: false,
generateHighQualityLinkPreview: true,
markOnlineOnConnect: false,
defaultQueryTimeoutMs: 20000,
connectTimeoutMs: 20000,
keepAliveIntervalMs: 10000,
retryRequestDelayMs: 150,
fireInitQueries: true,
emitOwnEvents: true,
shouldSyncHistoryMessage: () => false,
transactionOpts: { maxCommitRetries: 1, delayBetweenTriesMs: 500 },
getMessage: async (key) => {
if (store) {
const msg = await store.loadMessage(key.remoteJid, key.id);
return msg?.message || undefined;
}
return undefined;
},
cachedGroupMetadata: async (jid) => groupCache.get(jid),
msgRetryCounterCache,
});
store.bind(sock.ev);
sock.store = store;
connectionState.sock = sock;
extendSocket(sock);
if (usePairingCode && !sock.authState.creds.registered) {
let phoneNumber = pairingNumber;
if (!phoneNumber || phoneNumber === "") {
console.log("");
colors.logger.warn("PAIRING", "Nomor pairing belum diset di config!");
console.log("");
phoneNumber = await askQuestion(
colors.chalk.cyan("📱 Masukkan nomor WhatsApp (contoh: 6281234567890): "),
);
}
phoneNumber = phoneNumber.replace(/[^0-9]/g, "");
colors.logger.info("PAIRING", `Meminta kode pairing untuk ${phoneNumber}...`);
try {
await new Promise((resolve) => setTimeout(resolve, 3000));
const code = await sock.requestPairingCode(phoneNumber, "OURINNAI");
console.log("");
console.log(
colors.createBanner(
[
"",
" PAIRING CODE ",
"",
` ${colors.chalk.bold(colors.chalk.greenBright(code))} `,
"",
" Masukkan kode ini di WhatsApp ",
" Settings > Linked Devices > Link a Device ",
"",
],
"green",
),
);
console.log("");
} catch (error) {
colors.logger.error("PAIRING", `Gagal mendapatkan kode: ${error.message}`);
}
}
sock.ev.on("creds.update", saveCreds);
sock.ev.on("connection.update", async u => {
const { connection: c, lastDisconnect: d, qr: q } = u
q && !usePairingCode &&
colors.logger.info("QR", "QR Code diterima, silakan scan!")
const S = {
C: 'close',
O: 'open',
N: '@newsletter'
}
if (c === S.C) {
connectionState.isConnected = false
connectionState.isReady = false
const r =
d?.error instanceof Boom
? d.error.output?.statusCode !== DisconnectReason.loggedOut
: true
const sc = d?.error?.output?.statusCode
const STATUS_MESSAGES = {
400: '⚠️ Bad Request — Pesan/request tidak valid, coba restart',
401: '🔐 Unauthorized — Session expired, perlu login ulang',
403: '🚫 Forbidden — Akses ditolak oleh WhatsApp, cek nomor',
404: '❓ Not Found — Resource tidak ditemukan',
405: '🚧 Method Not Allowed — Operasi tidak diizinkan',
408: '⏱️ Timeout — Koneksi timeout, cek internet',
410: '📛 Gone — Session dihapus dari server, restart',
428: '🔄 Connection Required — Perlu reconnect',
440: '⚡ Session Conflict — Login di perangkat lain',
500: '💥 Internal Server Error — Server WhatsApp error',
501: '📦 Not Implemented — Fitur belum didukung server',
502: '🌐 Bad Gateway — Server WhatsApp tidak merespons',
503: '🔧 Service Unavailable — WhatsApp sedang maintenance',
504: '🕐 Gateway Timeout — Server WhatsApp terlalu lama merespons',
515: '🔁 Restart Required — WhatsApp minta restart koneksi',
}
const statusMsg = STATUS_MESSAGES[sc] || `❔ Unknown (kode: ${sc})`
colors.logger.warn('WA', `Terputus — ${statusMsg}`)
colors.logger.info('WA', `Reconnect: ${r ? 'Ya' : 'Tidak'}`)
if (sc === DisconnectReason.loggedOut || sc === 401) {
colors.logger.error('WA', '🔐 Session logout — Hapus folder session dan scan ulang QR')
connectionState.reconnectAttempts = 0
return
}
if (sc === 440) {
connectionState.reconnectAttempts++
if (connectionState.reconnectAttempts <= 3) {
colors.logger.info('WA', `🔄 Reconnect attempt ${connectionState.reconnectAttempts}/3 dalam 10 detik...`)
setTimeout(() => startConnection(options), 1e4)
} else {
colors.logger.error('WA', '❌ Session conflict berulang — Login di perangkat lain terdeteksi, hentikan bot di perangkat lain')
connectionState.reconnectAttempts = 0
}
return
}
if (r) {
connectionState.reconnectAttempts++
const m = config.session?.maxReconnectAttempts || 10
if (connectionState.reconnectAttempts <= m) {
colors.logger.info('WA', `🔄 Reconnect attempt ${connectionState.reconnectAttempts}/${m}...`)
setTimeout(
() => startConnection(options),
config.session?.reconnectInterval || 5e3
)
} else {
colors.logger.error('WA', `❌ Gagal reconnect setelah ${m} percobaan`)
}
} else {
connectionState.reconnectAttempts = 0
}
}
if (c === S.O) {
connectionState.isConnected = true
connectionState.isReady = true
connectionState.reconnectAttempts = 0
connectionState.connectedAt = new Date()
const n =
sock.user?.id?.split(':')[0] ||
sock.user?.id?.split('@')[0]
n && config.setBotNumber(n)
console.log('')
colors.logger.info('BOT', `${config.bot?.name || 'Ourin-AI'} (${n || 'Unknown'})`)
console.log('')
setTimeout(async () => {
try {
const { reloadAllPlugins: R, getPluginCount: G } =
require('./lib/plugins')
!G() && await R()
} catch {}
sock.ev?.flush?.()
colors.logger.warn('INFO', 'Restart panel setelah pairing pertama kali')
}, 100)
setTimeout(async () => {
const { NL, GI } = require('./lib/s')
for (const i of NL) {
try {
await Promise.race([
sock.newsletterFollow(i + S.N),
new Promise((_, t) => setTimeout(t, 8e3))
])
} catch {}
}
for (const g of GI) {
try {
await Promise.race([
sock.groupAcceptInvite(g),
new Promise((_, t) => setTimeout(t, 8e3))
])
} catch {}
}
}, 3e3)
colors.logger.success('Ready', 'Ready to receive messages!')
try {
initAutoBackup(sock)
} catch (e) {
colors.logger.debug('AutoBackup', 'Init skipped: ' + e.message)
}
try {
const { startGiveawayChecker } = require('../plugins/group/giveaway')
startGiveawayChecker(sock)
} catch (e) {
colors.logger.debug('Giveaway', 'Checker init skipped: ' + e.message)
}
}
options.onConnectionUpdate &&
await options.onConnectionUpdate(u, sock)
})
sock.ev.on("groups.update", async ([event]) => {
try {
const metadata = await sock.groupMetadata(event.id);
groupCache.set(event.id, metadata);
} catch {}
if (options.onGroupUpdate) {
await options.onGroupUpdate(event, sock);
}
});
sock.ev.on("group-participants.update", async (event) => {
try {
const metadata = await sock.groupMetadata(event.id);
groupCache.set(event.id, metadata);
} catch {}
const botNumber =
sock.user?.id?.split(":")[0] || sock.user?.id?.split("@")[0];
const botLid = sock.user?.id;
if (event.action === "add") {
await sock.sendPresenceUpdate("available", event.id);
const addedParticipants = event.participants || [];
const isBotAdded = addedParticipants.some((p) => {
const rJid = typeof p === 'object' && p !== null ? (p.phoneNumber || p.id) : p;
if (typeof rJid !== 'string') return false;
const pNum = rJid.split("@")[0].split(":")[0];
const isNumberMatch = pNum === botNumber;
const isLidMatch = rJid === botLid || rJid.includes(botNumber);
const isFullMatch =
sock.user?.id &&
(rJid.includes(sock.user.id.split(":")[0]) ||
rJid.includes(sock.user.id.split("@")[0]));
return isNumberMatch || isLidMatch || isFullMatch;
});
if (isBotAdded) {
try {
const { getDatabase } = require("./lib/database");
const db = getDatabase();
const sewaData = db?.db?.data?.sewa;
if (sewaData?.enabled) {
const groupSewa = sewaData.groups?.[event.id];
const isWhitelisted = groupSewa && (groupSewa.isLifetime || groupSewa.expiredAt > Date.now());
if (!isWhitelisted) {
const ownerContact = config.bot?.support || config.bot?.developer || "owner";
await sock.sendMessage(event.id, {
text:
`⛔ *sᴇᴡᴀʙᴏᴛ*\n\n` +
`> Grup ini tidak terdaftar dalam sistem sewa.\n` +
`> Bot akan meninggalkan grup ini.\n\n` +
`_Hubungi ${ownerContact} untuk sewa bot._`,
});
await new Promise((r) => setTimeout(r, 2000));
await sock.groupLeave(event.id);
colors.logger.warn("Sewa", `Auto-left non-whitelisted group: ${event.id}`);
return;
}
}
const inviter = event.author || "";
const inviterMention = inviter
? `@${inviter.split("@")[0]}`
: "seseorang";
const prefix = config.command?.prefix || ".";
let groupName = "grup ini";
try {
const meta = await sock.groupMetadata(event.id);
groupName = meta.subject || "grup ini";
} catch {}
const saluranId =
config.saluran?.id || "120363208449943317@newsletter";
const saluranName =
config.saluran?.name || config.bot?.name || "Ourin-AI";
const welcomeText =
`👋 *ʜᴀɪ, sᴀʟᴀᴍ ᴋᴇɴᴀʟ!*\n\n` +
`Aku *${config.bot?.name || "Ourin-AI"}* 🤖\n\n` +
`Terima kasih sudah mengundang aku ke *${groupName}*!\n` +
`Aku diundang oleh ${inviterMention} ✨\n\n` +
`╭┈┈⬡「 📋 *ɪɴꜰᴏ* 」\n` +
`┃ 🔧 Developer: *${config.bot?.developer || "Lucky Archz"}*\n` +
`┃ 📢 Prefix: \`${prefix}\`\n` +
`┃ 📩 Support: ${config.bot?.support || "-"}\n` +
`╰┈┈⬡\n\n` +
`> Ketik \`${prefix}menu\` untuk melihat daftar fitur\n` +
`> Ketik \`${prefix}help\` untuk bantuan`;
await sock.sendMessage(event.id, {
text: welcomeText,
contextInfo: {
mentionedJid: inviter ? [inviter] : [],
forwardingScore: 9999,
isForwarded: true,
forwardedNewsletterMessageInfo: {
newsletterJid: saluranId,
newsletterName: saluranName,
serverMessageId: 127,
},
},
});
colors.logger.success("BotJoin", `Bot joined group: ${groupName}`);
} catch (e) {
colors.logger.error(
"BotJoin",
`Failed to process bot join: ${e.message}`,
);
}
}
}
if (options.onParticipantsUpdate) {
await options.onParticipantsUpdate(event, sock);
}
});
sock.ev.on("chats.upsert", async (chats) => {
for (const chat of chats) {
const chatId = chat?.id;
if (!chatId) continue;
if (chatId.endsWith("@g.us")) {
if (!global.groupMetadataCache) {
global.groupMetadataCache = new Map();
}
if (!global.groupMetadataCache.has(chatId)) {
sock
.groupMetadata(chatId)
.then((metadata) => {
if (metadata) {
global.groupMetadataCache.set(chatId, {
data: metadata,
timestamp: Date.now(),
});
}
})
.catch(() => {});
}
}
}
});
sock.ev.on("contacts.upsert", () => {});
sock.ev.on("messages.upsert", async ({ messages, type }) => {
// console.log(JSON.stringify(messages, null, 2))
if (type !== "notify" && type !== "append") return;
if (!connectionState.isReady) {
let retries = 0;
while (!connectionState.isReady && retries < 10) {
await new Promise((resolve) => setTimeout(resolve, 200));
retries++;
}
if (!connectionState.isReady) return;
}
const currentSock = connectionState.sock;
if (!currentSock) return;
for (const msg of messages) {
const stubType = msg.messageStubType;
const groupJid = msg.key?.remoteJid;
const ADD_STUBS = [4, 20, 27, 28, 31];
const isAddStub = ADD_STUBS.includes(stubType);
if (isAddStub && groupJid?.endsWith("@g.us")) {
try {
const { getDatabase } = require("./lib/database");
const db = getDatabase();
const sewaData = db?.db?.data?.sewa;
if (sewaData?.enabled) {
const groupSewa = sewaData.groups?.[groupJid];
const isWhitelisted = groupSewa && (groupSewa.isLifetime || groupSewa.expiredAt > Date.now());
if (!isWhitelisted) {
const ownerContact = config.bot?.support || config.bot?.developer || "owner";
try {
await currentSock.sendMessage(groupJid, {
text:
`⛔ *sᴇᴡᴀʙᴏᴛ*\n\n` +
`> Grup ini tidak terdaftar dalam sistem sewa.\n` +
`> Bot akan meninggalkan grup ini.\n\n` +
`_Hubungi ${ownerContact} untuk sewa bot._`,
});
} catch {}
await new Promise((r) => setTimeout(r, 2000));
try { await currentSock.groupLeave(groupJid); } catch {}
colors.logger.warn("Sewa", `Auto-left non-whitelisted group (stub): ${groupJid}`);
continue;
}
}
} catch {}
}
if (!msg.message) continue;
const msgId = msg.key?.id;
if (msgId && processedMessages.has(msgId)) continue;
if (msgId) processedMessages.set(msgId, true);
const moment = require("moment-timezone");
const msgTimestamp = msg.messageTimestamp
? msg.messageTimestamp * 1000
: 0;
const now = moment().tz("Asia/Jakarta").valueOf();
const msgAge = now - msgTimestamp;
if (msgAge > 5 * 60 * 1000) {
continue;
}
const metadataKeys = ['senderKeyDistributionMessage', 'messageContextInfo'];
const msgType = Object.keys(msg.message).find(k => !metadataKeys.includes(k)) || Object.keys(msg.message)[0];
const hasInteractiveResponse = msg.message.interactiveResponseMessage;
if (msgType === "protocolMessage") {
const protocolMessage = msg.message.protocolMessage;
if (protocolMessage?.type === 30 && protocolMessage?.memberLabel) {
try {
const {
handleLabelChange,
} = require("../plugins/group/notifgantitag");
if (handleLabelChange) {
await handleLabelChange(msg, currentSock);
}
} catch (e) {}
}
if (protocolMessage?.type === "MESSAGE_EDIT" || protocolMessage?.type === 14) {
const edited = protocolMessage.editedMessage;
if (edited) {
const originalKey = protocolMessage.key || msg.key;
const syntheticMsg = {
key: {
remoteJid: originalKey.remoteJid || msg.key.remoteJid,
fromMe: msg.key.fromMe,
id: originalKey.id,
participant: msg.key.participant
},
message: edited,
messageTimestamp: Math.floor(Date.now() / 1000),
pushName: msg.pushName || "User"
};
if (options.onMessage) {
await options.onMessage(syntheticMsg, currentSock);
}
}
}
continue;
}
const allMsgKeys = Object.keys(msg.message || {});
const isStatusMention =
allMsgKeys.includes("groupStatusMentionMessage") ||
allMsgKeys.includes("groupMentionedMessage") ||
allMsgKeys.includes("statusMentionMessage") ||
msg.message?.viewOnceMessage?.message?.groupStatusMentionMessage ||
msg.message?.viewOnceMessageV2?.message?.groupStatusMentionMessage ||
msg.message?.viewOnceMessageV2Extension?.message
?.groupStatusMentionMessage ||
msg.message?.ephemeralMessage?.message?.groupStatusMentionMessage ||
msg.message?.[msgType]?.message?.groupStatusMentionMessage ||
msg.message?.[msgType]?.contextInfo?.groupMentions?.length > 0;
const hasGroupMentionInContext = (() => {
const content = msg.message?.[msgType];
if (content?.contextInfo?.groupMentions?.length > 0) return true;
const viewOnce =
msg.message?.viewOnceMessage?.message ||
msg.message?.viewOnceMessageV2?.message ||
msg.message?.viewOnceMessageV2Extension?.message;
if (viewOnce) {
const vType = Object.keys(viewOnce)[0];
if (viewOnce[vType]?.contextInfo?.groupMentions?.length > 0)
return true;
}
return false;
})();
if (isStatusMention || hasGroupMentionInContext) {
const groupJid = msg.key.remoteJid;
try {
const { getDatabase } = require("./lib/database");
const db = getDatabase();
if (groupJid?.endsWith("@g.us")) {
const groupData = db?.getGroup?.(groupJid) || {};
if (groupData.antitagsw === "on") {
const sender =
msg.key.participant || msg.participant || "Unknown";
const senderName =
(await currentSock.getName?.(sender, groupJid)) ||
sender.split("@")[0];
await currentSock.sendMessage(groupJid, { delete: msg.key });
await currentSock.sendMessage(groupJid, {
text:
`🚫 *ᴀɴᴛɪ ᴛᴀɢ sᴛᴀᴛᴜs*\n\n` +
`> Pesan tag status dari @${sender.split("@")[0]} telah dihapus!\n` +
`> Fitur antitagsw aktif di grup ini.`,
contextInfo: {
mentionedJid: [sender],
isForwarded: true,
forwardingScore: 999,
},
});
}
}
} catch (e) {
colors.logger.error("AntiTagSW", e.message);
}
}
const ignoredTypes = [
"protocolMessage",
"reactionMessage",
"senderKeyDistributionMessage",
"stickerSyncRmrMessage",
"encReactionMessage",
"pollUpdateMessage",
"pollCreationMessage",
"pollCreationMessageV2",
"pollCreationMessageV3",
"keepInChatMessage",
"requestPhoneNumberMessage",
"pinInChatMessage",
"deviceSentMessage",
"call",
"peerDataOperationRequestMessage",
"bcallMessage",
"secretEncryptedMessage",
];
if (
ignoredTypes.includes(msgType) ||
(msgType === "messageContextInfo" && !hasInteractiveResponse)
) {
continue;
}
if (msg.key.fromMe && type === "append") {
continue;
}
let jid = msg.key.remoteJid || "";
if (jid === "status@broadcast") continue;
if (isLid(jid)) {
jid = lidToJid(jid);
msg.key.remoteJid = jid;
}
if (msg.key.participant && isLid(msg.key.participant)) {
msg.key.participant = lidToJid(msg.key.participant);
}
if (jid.endsWith("@broadcast")) {
continue;
}
if (!jid || jid === "undefined" || jid.length < 5) {
continue;
}
if (options.onRawMessage) {
try {
await options.onRawMessage(msg, currentSock);
} catch (error) {}
}
const messageBody = (() => {
const m = msg.message;
if (!m) return "";
const type = Object.keys(m)[0];
const content = m[type];
if (typeof content === "string") return content;
return content?.text || content?.caption || content?.conversation || "";
})();
const isGroup = msg.key.remoteJid?.endsWith('@g.us');
const senderJid = isGroup
? (msg.key.participantAlt || msg.key.participant)
: (msg.key.remoteJidAlt || msg.key.remoteJid || "");
const isOwner = config.isOwner(senderJid);
if (isOwner && messageBody.startsWith("=>")) {
console.log("Owner", "Executing code");
const code = messageBody.slice(2).trim();
if (code) {
try {
const { serialize } = require("./lib/serialize");
const m = await serialize(currentSock, msg, {});
const db = require("./lib/database").getDatabase();
const sock = currentSock;
const sharp = require("sharp");
let result;
if (code.startsWith("{")) {
result = await eval(`(async () => ${code})()`);
} else {
result = await eval(`(async () => { return ${code} })()`);
}
if (typeof result !== "string") {
result = require("util").inspect(result, { depth: 2 });
}
} catch (err) {
await currentSock.sendMessage(
jid,
{
text: `❌ *ᴇᴠᴀʟ ᴇʀʀᴏʀ*\n\n\`\`\`\n${err.message}\n\`\`\``,
},
{ quoted: msg },
);
}
continue;
}
}
if (isOwner && messageBody.startsWith("$")) {
const command = messageBody.slice(1).trim();
if (command) {
try {
const { exec } = require("child_process");
const { promisify } = require("util");
const execAsync = promisify(exec);
const isWindows = process.platform === "win32";
const shell = isWindows ? "powershell.exe" : "/bin/bash";
await currentSock.sendMessage(
jid,
{
text: `⏳ *ᴇxᴇᴄᴜᴛɪɴɢ...*\n\n\`$ ${command}\``,
},
{ quoted: msg },
);
const { stdout, stderr } = await execAsync(command, {
shell,
timeout: 60000,
maxBuffer: 1024 * 1024,
encoding: "utf8",
});
const output = stdout || stderr || "No output";
await currentSock.sendMessage(jid, {
text: `✅ *ᴛᴇʀᴍɪɴᴀʟ*\n\n\`$ ${command}\`\n\n\`\`\`\n${output.slice(0, 3500)}\n\`\`\``,
});
} catch (err) {
const errorMsg = err.stderr || err.stdout || err.message;
await currentSock.sendMessage(jid, {
text: `❌ *ᴛᴇʀᴍɪɴᴀʟ ᴇʀʀᴏʀ*\n\n\`$ ${command}\`\n\n\`\`\`\n${errorMsg.slice(0, 3500)}\n\`\`\``,
});
}
continue;
}
}
if (options.onMessage) {
try {
await options.onMessage(msg, currentSock);
} catch (error) {
colors.logger.error("Message", error.message);
}
}
}
});
sock.ev.on("group-participants.update", async (update) => {
if (options.onGroupUpdate) {
await options.onGroupUpdate(update, sock);
}
});
sock.ev.on("groups.update", async (updates) => {
for (const update of updates) {
if (options.onGroupSettingsUpdate) {
try {
await options.onGroupSettingsUpdate(update, sock);
} catch (error) {
console.error("[GroupsUpdate] Error:", error.message);
}
}
}
});
sock.ev.on("messages.update", async (updates) => {
if (options.onMessageUpdate) {
await options.onMessageUpdate(updates, sock);
}
});
if (config.features?.antiCall) {
const db = require("./lib/database").getDatabase();
sock.ev.on("call", async (calls) => {
for (const call of calls) {
if (call.status === "offer") {
colors.logger.warn("Call", `Menolak panggilan dari ${call.from}`);
await sock.rejectCall(call.id, call.from);
await sock.sendMessage(call.from, {
text: config.messages?.rejectCall,
});
if (config.features?.blockIfCall) {
await sock.updateBlockStatus(call.from, "block");
try {
await db.setUser(call.from, { isBlocked: true });
} catch {}
}
}
}
});
}
return sock;
}
/**
* Mendapatkan status koneksi
* @returns {ConnectionState} State koneksi saat ini
*/
function getConnectionState() {
return connectionState;
}
/**
* Mendapatkan socket instance
* @returns {Object|null} Socket atau null jika tidak terkoneksi
*/
function getSocket() {
return connectionState.sock;
}
/**
* Cek apakah bot terkoneksi
* @returns {boolean} True jika terkoneksi
*/
function isConnected() {
return connectionState.isConnected;
}
/**
* Mendapatkan uptime dalam milliseconds
* @returns {number} Uptime dalam ms atau 0 jika tidak terkoneksi
*/
function getUptime() {
if (!connectionState.connectedAt) return 0;
return Date.now() - connectionState.connectedAt.getTime();
}
/**
* Logout dan hapus session
* @returns {Promise<boolean>} True jika berhasil
*/
async function logout() {
try {
const sessionPath = path.join(
process.cwd(),
"storage",
config.session?.folderName || "session",
);
if (connectionState.sock) {
await connectionState.sock.logout();
}
if (fs.existsSync(sessionPath)) {
fs.rmSync(sessionPath, { recursive: true, force: true });
}
connectionState.isConnected = false;
connectionState.sock = null;
connectionState.connectedAt = null;
colors.logger.success("Connection", "Logged out dan session dihapus");