-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2096 lines (1883 loc) · 99.9 KB
/
Copy pathserver.js
File metadata and controls
2096 lines (1883 loc) · 99.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
// server.js — no Express/HTTP server (manager.js handles all UI via IPC)
const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');
const { execFile } = require('child_process');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);
const yts = require('yt-search');
const { askAI, generateOnce, parseCommandFromAI } = require('./ai.js');
const { generateTTS } = require('./tts.js');
const { handlePeerUtterance, getVoiceStatus } = require('./voice.js');
// ── yt-dlp: ambil direct stream URL ────────────────────────────────────────────
// Cache: hindari re-fetch URL yang sama (YouTube stream URL valid ~4-6 jam)
const _streamUrlCache = new Map(); // videoUrl → { url, fetchedAt }
const STREAM_CACHE_TTL = 4 * 60 * 60 * 1000; // 4 jam
const _pendingFetches = new Map(); // dedup: cegah 2 call yt-dlp untuk URL yang sama
async function getStreamUrl(videoUrl) {
// 1. Cache hit
const cached = _streamUrlCache.get(videoUrl);
if (cached && Date.now() - cached.fetchedAt < STREAM_CACHE_TTL) {
console.log(`[MUSIC] Cache hit: ${videoUrl.slice(-20)}`);
return cached.url;
}
// 2. Dedup: kalau sudah ada fetch yang pending untuk URL ini, tunggu itu saja
if (_pendingFetches.has(videoUrl)) {
console.log(`[MUSIC] Dedup — waiting for pending fetch: ${videoUrl.slice(-20)}`);
return _pendingFetches.get(videoUrl);
}
// 3. Fetch baru
const fetchPromise = (async () => {
try {
const { stdout } = await execFileAsync('yt-dlp', [
// Format audio-only (lebih cepat, tidak perlu merge video)
// 140 = m4a 128k, 251 = webm/opus, 250 = webm/opus low
'-f', '140/251/250/bestaudio[ext=m4a]/bestaudio',
'--get-url',
'--no-playlist',
'--no-warnings',
'--no-call-home',
'--socket-timeout', '10',
videoUrl
]);
const url = stdout.trim().split('\n').find(l => l.startsWith('http'));
if (!url) throw new Error('yt-dlp returned no valid URL');
_streamUrlCache.set(videoUrl, { url, fetchedAt: Date.now() });
return url;
} finally {
_pendingFetches.delete(videoUrl);
}
})();
_pendingFetches.set(videoUrl, fetchPromise);
return fetchPromise;
}
// Pre-fetch stream URL di background (untuk next song di queue)
function preFetchNextSong() {
if (botState.queue.length > 0) {
const next = botState.queue[0];
if (next?.url && !_streamUrlCache.has(next.url) && !_pendingFetches.has(next.url)) {
console.log(`[MUSIC] Pre-fetching next song: ${next.title}`);
getStreamUrl(next.url).catch(() => {}); // fire & forget
}
}
}
// ── Static role config (roles.json) — hot-reloaded on change ────────────────────
const ROLES_PATH = path.join(__dirname, 'roles.json');
let staticRoles = { owners: [], coOwners: [], moderators: [], admins: [] };
function loadRoles() {
try {
staticRoles = JSON.parse(fs.readFileSync(ROLES_PATH, 'utf8'));
console.log(`[ROLES] Loaded: ${staticRoles.owners?.length||0} owners, ${staticRoles.moderators?.length||0} mods`);
} catch (_) {}
}
loadRoles();
fs.watchFile(ROLES_PATH, () => { loadRoles(); applyStaticRoles(); });
/** Apply staticRoles to participantDetails (call after roles.json changes or after participants load) */
function applyStaticRoles() {
const map = [
['Owner', staticRoles.owners || []],
['Co-owner', staticRoles.coOwners || []],
['Moderator', staticRoles.moderators || []],
['Admin', staticRoles.admins || []],
];
for (const [role, uids] of map) {
for (const uid of uids) {
const existing = participantDetails.get(uid) || { name: uid };
participantDetails.set(uid, { ...existing, role });
}
}
updateParticipants();
}
// ── IPC: terima perintah dari manager.js via process.send() ──────────────
// ── Bot runtime state ────────────────────────────────────────────────────────
let browser = null;
let context = null;
let page = null;
let botState = {
status: 'OFFLINE',
currentSong: null,
queue: [],
searchResults:[],
isPlaying: false,
isRepeating: false,
volume: 10,
botName: 'Music Bot Pro',
participants: [], // [{uid, name, role}] — real-time room list
aiMuteUntil: 0, // timestamp ms; 0 = AI aktif, >now = AI di-mute (set via !ai off/sleep)
voiceListenActive: true // Voice conversation mode (wake word listen via Groq STT)
};
// ── Hot-reload commands.js ───────────────────────────────────────────────────
let commandHandler = require('./commands.js');
fs.watchFile(path.join(__dirname, 'commands.js'), () => {
try {
delete require.cache[require.resolve('./commands.js')];
commandHandler = require('./commands.js');
log('Commands reloaded!', 'success');
} catch (e) {
log('Failed to reload commands: ' + e.message, 'error');
}
});
// ── Logging ──────────────────────────────────────────────────────────────────
function log(msg, type = 'info') {
const time = new Date().toLocaleTimeString('id-ID', { hour12: false }).replace(/\./g, '.');
// Kirim via IPC ke manager (untuk dashboard broadcast)
if (process.send) process.send({ type: 'bot-log', time, msg, level: type });
console.log(`[${time}] [${type}] ${msg}`);
}
function updateStatus() {
if (process.send) process.send({ type: 'bot-status', state: botState });
}
function updateParticipants() {
botState.participants = [...participantDetails.entries()].map(([uid, d]) => ({
uid, name: d.name || uid, role: d.role || 'Member'
}));
updateStatus();
// Trigger auto-leave check setiap kali participant list berubah
checkEmptyRoom();
}
// ── Auto-leave: keluar jika room kosong selama AUTO_LEAVE_SEC detik ──────────
const AUTO_LEAVE_SEC = 30;
let emptyRoomTimer = null;
function checkEmptyRoom() {
if (botState.status !== 'ONLINE') return;
// Hitung peserta selain bot sendiri
const others = botState.participants.filter(p => p.uid !== botMyId);
if (others.length === 0) {
if (!emptyRoomTimer) {
log(`[AUTO-LEAVE] Room kosong — akan keluar dalam ${AUTO_LEAVE_SEC} detik...`, 'warn');
emptyRoomTimer = setTimeout(() => {
leaveRoom('Room kosong selama ' + AUTO_LEAVE_SEC + ' detik.');
}, AUTO_LEAVE_SEC * 1000);
}
} else {
// Ada orang → batalkan timer
if (emptyRoomTimer) {
clearTimeout(emptyRoomTimer);
emptyRoomTimer = null;
log('[AUTO-LEAVE] Timer dibatalkan — ada peserta masuk.', 'info');
}
}
}
// Ref ke sendMessage dan scanDomForOwner — diset saat bot start
let _sendMessage = null;
let _scanDomForOwner = null;
let _resolveWsReady = null; // resolve saat WS room confirm pertama
let _domScanInterval = null; // ID interval DOM scan — di-clear saat bot stop
async function leaveRoom(reason = 'Keluar room.') {
log(`[AUTO-LEAVE] ${reason}`, 'warn');
clearTimeout(emptyRoomTimer);
emptyRoomTimer = null;
// Stop DOM scan interval supaya tidak error setelah context ditutup
if (_domScanInterval) { clearInterval(_domScanInterval); _domScanInterval = null; }
_scanDomForOwner = null;
try { if (_sendMessage) await _sendMessage(`👋 Bot keluar: ${reason}`); } catch (_) {}
await new Promise(r => setTimeout(r, 1500));
if (context) { try { await context.close(); } catch (_) {} }
if (browser) { try { await browser.close(); } catch (_) {} }
browser = null;
context = null;
page = null;
botJwk = null;
botMyId = null;
participantDetails.clear();
participantsCache.clear();
botState.status = 'OFFLINE';
botState.participants = [];
botState.currentSong = null;
botState.queue = [];
botState.isPlaying = false;
updateStatus();
log('Bot offline. Process akan exit dalam 2 detik.', 'info');
// Exit process — manager akan detect dan mark STOPPED
setTimeout(() => process.exit(0), 2000);
}
// ── Anti-loop guard ──────────────────────────────────────────────────────────
const sentMessages = new Set();
let botLastSentAt = 0;
const BOT_SEND_COOLDOWN = 8000; // ms
const BOT_OWN_NAMES = ['GicellBot', 'riyan', 'rj'];
// Bot identity (for Option 3 direct send)
let botJwk = null; // { x, y, d } dari JWK keypair
let botMyId = null; // uid bot di Free4Talk
// AI mutex
let isAIProcessing = false;
function normalizeMsg(text) {
return text
.replace(/[`*_~|]/g, '')
.replace(/\s+/g, ' ')
.trim()
.substring(0, 150);
}
// ── Participants cache ────────────────────────────────────────────────────────
const participantsCache = new Map(); // name.toLowerCase() → uid
const participantDetails = new Map(); // uid → { name, role }
const msgSeenKeys = new Set(); // dedup
// ── Voice: WebRTC trackId → participant name mapping ─────────────────────────
// Diisi via __onTrackJoined (best-effort: nama participant yang baru join
// dikorelasikan ke track yang baru muncul dalam 3s window)
const _trackParticipantNames = new Map();
/** Lookup clean name by uid */
function nameOf(uid) {
return participantDetails.get(uid)?.name || uid || 'Unknown';
}
/** Lookup role by uid */
function roleOf(uid) {
return participantDetails.get(uid)?.role || 'Member';
}
/** Normalize Free4Talk role strings → canonical form */
function resolveRole(raw) {
const r = (raw || '').toString().toLowerCase();
// PENTING: cek co-owner SEBELUM owner (co-owner juga contains 'owner')
if (r.includes('co-owner') || r.includes('coowner') || r === 'co') return 'Co-owner';
if (r.includes('owner')) return 'Owner';
if (r.includes('moderator') || r.includes('mod')) return 'Moderator';
if (r.includes('admin')) return 'Admin';
return 'Member';
}
// ════════════════════════════════════════════════════════════════════════════
// SEND MESSAGE — DOM primary (DataChannel direct disabled pending debug)
// ════════════════════════════════════════════════════════════════════════════
async function sendMessage(text) {
if (!page) return;
try {
botLastSentAt = Date.now();
const fp = normalizeMsg(text);
sentMessages.add(fp);
setTimeout(() => sentMessages.delete(fp), 15000);
// ── Option 3: sign message with ECDSA and send via transporter ────────
// NOTE: MSG:DIRECT sends but messages don't appear (silent reject by receiver).
// Kept here for future debugging — bot uses DOM fallback which works reliably.
// if (botJwk && botMyId) { ... }
// ── Send via DOM (React native setter + keyboard events) ──────────────
const sel = 'textarea[placeholder*="Type a message"], input[placeholder*="Type a message"]';
const sent = await page.evaluate(async (msg) => {
const input = document.querySelector(
'textarea[placeholder*="Type a message"], input[placeholder*="Type a message"]'
);
if (!input) return false;
const proto = input instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
setter.call(input, msg);
input.dispatchEvent(new Event('input', { bubbles: true }));
await new Promise(r => setTimeout(r, 30));
const opts = { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true, cancelable: true };
input.dispatchEvent(new KeyboardEvent('keydown', opts));
input.dispatchEvent(new KeyboardEvent('keypress', opts));
input.dispatchEvent(new KeyboardEvent('keyup', opts));
return true;
}, text);
if (!sent) {
await page.fill(sel, text);
await page.keyboard.press('Enter');
}
} catch (e) {
log('Failed to send message: ' + e.message, 'error');
}
}
// ════════════════════════════════════════════════════════════════════════════
// AI RELEVANCE GATE — tentukan apakah AI perlu balas pesan ini
// ════════════════════════════════════════════════════════════════════════════
let _aiLastReplyAt = 0;
// Catatan: status mute disimpan di botState.aiMuteUntil (timestamp ms; 0 = aktif)
// supaya plugin (!ai off/on/sleep) bisa modify lewat ctx.botState.
const AI_DIRECT_COOLDOWN = 0; // Direct mention: NO cooldown — user manggil eksplisit, harus selalu respond
const AI_QUESTION_COOLDOWN = 30000; // 30 detik untuk pertanyaan
const AI_RANDOM_COOLDOWN = 90000; // 90 detik untuk random nimbrung
const AI_RANDOM_CHANCE = 0.05; // 5% (turun dari 15%)
// Ringkasan pesan terakhir untuk deteksi conversation antar-user
const _recentChats = []; // [{ name, text, ts }]
const RECENT_CHAT_WINDOW = 20000; // 20 detik
function recordChat(name, text) {
const now = Date.now();
_recentChats.push({ name, text, ts: now });
while (_recentChats.length && now - _recentChats[0].ts > RECENT_CHAT_WINDOW) {
_recentChats.shift();
}
}
/** Apakah pesan ini terlihat ditujukan ke user lain (bukan ke bot)? */
function isAddressedToOtherUser(text, participants = []) {
const lower = text.toLowerCase();
// 1. Eksplisit @mention (bukan @bot)
const mentionMatch = lower.match(/@([a-z0-9_]+)/);
if (mentionMatch) {
const mentioned = mentionMatch[1];
const isBot = ['bot', 'gicell', 'gicellbot'].some(b => mentioned.includes(b));
if (!isBot) return true;
}
// 2. Sapaan langsung ke nama participant: "bro X", "kak X", "mbak X", "bang X", "sis X", "om X", "tante X"
const addressPrefixes = ['bro ', 'kak ', 'mbak ', 'bang ', 'sis ', 'om ', 'tante ', 'mas ', 'kang '];
for (const p of participants) {
if (!p?.name) continue;
const pname = p.name.toLowerCase();
if (['bot', 'gicell', 'gicellbot'].some(b => pname.includes(b))) continue;
// Match nama participant di pesan dengan prefix sapaan ATAU sebagai standalone token
if (addressPrefixes.some(prefix => lower.includes(prefix + pname))) return true;
// Bare name match (min 4 char buat hindari false positive)
if (pname.length >= 4 && new RegExp(`\\b${pname}\\b`, 'i').test(lower)) return true;
}
return false;
}
/** Apakah ada conversation aktif antara 2+ user lain? */
function hasActiveUserConversation(currentSender) {
const others = _recentChats.filter(c => c.name !== currentSender);
const uniqueNames = new Set(others.map(c => c.name));
// Conversation = ada minimal 1 user lain ngirim chat dlm window terakhir
// dan combined chats >= 2 (saling balas / lanjutan)
return uniqueNames.size >= 1 && others.length >= 2;
}
function checkAIRelevance(text, botName = 'GicellBot', senderName = '', participants = [], muteUntil = 0) {
const lower = text.toLowerCase().trim();
const botLower = botName.toLowerCase();
const now = Date.now();
const sinceReply = now - _aiLastReplyAt;
const isMuted = muteUntil && muteUntil > now;
// ── Tier 1: Direct mention / dipanggil langsung ───────────────────────
// Catatan: 'bot' standalone dihapus karena terlalu generic ("lu bot ya", "kayak bot").
// Tetap ada via prefix "hei bot/hey bot/hai bot" atau via nama bot eksplisit.
// Direct mention BYPASS mute — supaya user bisa unmute via "!ai on" atau dipanggil ulang.
//
// Auto-typo tolerance dari botName:
// "GicellBot" → botLower "gicellbot"
// → strip "bot" suffix → "gicell"
// → dedupe huruf double "ll" → "gicel" (typo umum!)
// Ini supaya user yang ngetik "gicel" / "gicell" / "gicellbot" semua match.
const botRoot = botLower.replace(/bot$/i, ''); // "gicell"
const botRootDedup = botRoot.replace(/(.)\1+/g, '$1'); // "gicel"
const directTriggers = [
botLower,
botRoot,
botRootDedup,
'hei bot', 'hey bot', 'hai bot', 'halo bot', 'oi bot', 'woi bot',
].filter((t, i, a) => t && t.length >= 3 && a.indexOf(t) === i);
const isDirect = directTriggers.some(t => lower.includes(t));
if (isDirect) {
if (sinceReply < AI_DIRECT_COOLDOWN) return { reply: false, reason: 'direct cooldown' };
_aiLastReplyAt = now;
return { reply: true, reason: 'direct mention' };
}
// ── Mute manual: block Tier 2 & Tier 3 ────────────────────────────────
// Direct mention di atas sudah lolos. Sisanya (pertanyaan + random) di-skip.
if (isMuted) {
const remaining = Math.ceil((muteUntil - now) / 1000);
return { reply: false, reason: `ai muted (${remaining}s left)` };
}
// ── Tier 2: Pertanyaan eksplisit ─────────────────────────────────────
// Lebih ketat: harus ada '?' ATAU diawali kata tanya (bukan di tengah kalimat).
// Mid-sentence "apa" / "kenapa" sering false positive ("iya apa", "ya kenapa engga").
const questionStarters = ['apa', 'siapa', 'gimana', 'bagaimana', 'kenapa',
'mengapa', 'kapan', 'dimana', 'berapa', 'what', 'how',
'why', 'when', 'where', 'who', 'which'];
const isQuestion = lower.includes('?') ||
questionStarters.some(w => lower.startsWith(w + ' '));
if (isQuestion) {
// Skip kalau pertanyaan jelas ditujukan ke user lain
if (isAddressedToOtherUser(text, participants)) {
return { reply: false, reason: 'question addressed to other user' };
}
if (sinceReply < AI_QUESTION_COOLDOWN) return { reply: false, reason: 'question — cooldown' };
_aiLastReplyAt = now;
return { reply: true, reason: 'question detected' };
}
// ── Tier 3: Random nimbrung (5% chance, cooldown 90s) ────────────────
if (sinceReply > AI_RANDOM_COOLDOWN && Math.random() < AI_RANDOM_CHANCE) {
// Skip kalau pesan terlalu pendek (<= 5 kata)
if (lower.split(/\s+/).length <= 5) return { reply: false, reason: 'too short for random' };
// Skip kalau ditujukan ke user lain
if (isAddressedToOtherUser(text, participants)) {
return { reply: false, reason: 'random skip — addressed to other' };
}
// Skip kalau conversation antar user lagi rame
if (hasActiveUserConversation(senderName)) {
return { reply: false, reason: 'random skip — user conversation active' };
}
_aiLastReplyAt = now;
return { reply: true, reason: 'random engagement' };
}
return { reply: false, reason: 'not relevant / cooldown' };
}
// ════════════════════════════════════════════════════════════════════════════
// CHAT HANDLER
// ════════════════════════════════════════════════════════════════════════════
async function handleChatMessage(chatData) {
if (!chatData?.text) return;
// Normalisasi: trim leading/trailing whitespace.
// Penting — keyboard mobile sering auto-insert spasi di depan, yang bikin
// `text.startsWith('!')` gagal → command salah deteksi sebagai chat biasa
// → kena cooldown / AI relevance gate → tidak direspons.
chatData.text = String(chatData.text).trim();
if (!chatData.text) return;
// Resolve uid from name if missing, then hydrate name/role from cache
if (!chatData.senderId && chatData.senderName && chatData.senderName !== 'Unknown') {
chatData.senderId =
participantsCache.get(chatData.senderName.toLowerCase()) ||
[...participantsCache.entries()].find(([k]) => k.startsWith(chatData.senderName.toLowerCase()))?.[1] ||
null;
}
// Always resolve clean name + role from participantDetails (overrides DOM noise)
if (chatData.senderId) {
chatData.senderName = nameOf(chatData.senderId);
chatData.senderRole = roleOf(chatData.senderId);
} else {
chatData.senderName = chatData.senderName || 'Unknown';
chatData.senderRole = chatData.senderRole || 'Member';
}
// Dedup
const dedupKey = chatData.msgId ? `id:${chatData.msgId}` : `${chatData.senderName}::${chatData.text}`;
if (msgSeenKeys.has(dedupKey)) return;
msgSeenKeys.add(dedupKey);
setTimeout(() => msgSeenKeys.delete(dedupKey), 30000);
// Skip pesan bot sendiri (cek by UID dulu, fallback ke nama)
if (botMyId && chatData.senderId === botMyId) return;
const senderLower = (chatData.senderName || '').toLowerCase();
if (BOT_OWN_NAMES.some(n => senderLower.includes(n.toLowerCase()))) return;
// Anti-loop fingerprint
const fp = normalizeMsg(chatData.text);
if (sentMessages.has(fp)) { log('[Anti-loop] fingerprint match.', 'warn'); return; }
// Anti-loop cooldown (non-command)
const isCmd = chatData.text.startsWith('!');
if (!isCmd && Date.now() - botLastSentAt < BOT_SEND_COOLDOWN) {
log('[Anti-loop] cooldown active.', 'warn'); return;
}
// Track non-command chat untuk conversation awareness
if (!isCmd) recordChat(chatData.senderName, chatData.text);
const ctx = {
botState, sendMessage, addToQueue, playNext, log, updateStatus, page,
clearPendingSongRequests,
speakTTS, isTTSBusy,
sender: { name: chatData.senderName || 'Unknown', role: chatData.senderRole || 'Member', uid: chatData.senderId || null }
};
if (isCmd) {
log(`[CMD] ${chatData.senderName} (${chatData.senderRole}) uid:${chatData.senderId} → ${chatData.text}`, 'cmd');
await commandHandler(chatData.text, ctx);
const cleanCmd = chatData.text.split(' ')[0].substring(1).toLowerCase();
const isKnown = commandHandler.CORE_COMMANDS?.includes(cleanCmd) ||
commandHandler.getPluginCommands?.()?.has(cleanCmd);
if (!isKnown) {
if (isAIProcessing) return;
isAIProcessing = true;
try {
const reply = await askAI(chatData.text, chatData.senderName, botState);
if (reply) await sendMessage(reply);
} finally { isAIProcessing = false; }
}
} else {
// ── Smart AI relevance gate ───────────────────────────────────────────
// AI hanya balas kalau benar-benar relevan, bukan semua pesan
const shouldReply = checkAIRelevance(
chatData.text,
botState.botName,
chatData.senderName,
botState.participants || [],
botState.aiMuteUntil || 0
);
if (!shouldReply.reply) {
log(`[AI] Skip reply (${shouldReply.reason})`, 'info');
return;
}
log(`[AI] Replying — reason: ${shouldReply.reason}`, 'info');
if (isAIProcessing) { log('[AI mutex] busy.', 'warn'); return; }
isAIProcessing = true;
try {
log(`[CHAT] ${chatData.senderName} (uid:${chatData.senderId}): ${chatData.text}`, 'info');
const reply = await askAI(chatData.text, chatData.senderName, botState);
if (reply) {
const { cleanReply, command } = parseCommandFromAI(reply, chatData.text);
if (cleanReply) await sendMessage(cleanReply);
if (command) {
log(`[AI→CMD] ${command}`, 'cmd');
try { await commandHandler(command, ctx); } catch (_) {}
}
}
} finally { isAIProcessing = false; }
}
}
// ════════════════════════════════════════════════════════════════════════════
// WEBSOCKET INTERCEPTOR — participant cache + optional chat
// ════════════════════════════════════════════════════════════════════════════
const CHAT_EVENT_NAMES = new Set([
'message','chat','chat:message','chat:new','new:message',
'room:message','newMessage','chatMessage','msg','send',
'broadcast','text','userMessage','roomChat','public-message'
]);
function parseChatPayload(eventName, data) {
if (!CHAT_EVENT_NAMES.has(eventName) || !data || typeof data !== 'object') return null;
const text = (data.message ?? data.text ?? data.content ?? data.msg ?? data.body ?? '').toString().trim();
if (!text) return null;
const userObj = data.user ?? data.sender ?? data.from ?? data.author ?? {};
const senderName = (userObj.name ?? userObj.username ?? userObj.displayName ?? data.username ?? '').trim() || 'Unknown';
const senderId = userObj.id ?? userObj._id ?? userObj.uid ?? data.userId ?? null;
return { text, senderName, senderId, senderRole: userObj.role ?? data.role ?? 'Member', msgId: data.id ?? null };
}
function setupWSInterceptor() {
page.on('websocket', ws => {
if (!ws.url().includes('ws.free4talk.com')) return;
ws.on('framereceived', ({ payload }) => {
try {
const raw = Buffer.isBuffer(payload) ? payload.toString('utf8') : String(payload);
if (!raw.startsWith('42')) return;
let jsonPart = raw.slice(2);
if (jsonPart.startsWith('/')) {
const idx = jsonPart.indexOf(',[');
if (idx === -1) return;
jsonPart = jsonPart.slice(idx + 1);
}
let arr; try { arr = JSON.parse(jsonPart); } catch { return; }
if (!Array.isArray(arr) || arr.length < 2) return;
const [evName, evData] = arr;
// Participants event
if (evName.includes(':participants') && evData?.participantMap) {
// Konfirmasi bot sudah beneran di dalam room
if (_resolveWsReady) { _resolveWsReady(); _resolveWsReady = null; }
const keepBot = participantDetails.get(botMyId);
const oldRoles = new Map([...participantDetails.entries()].map(([uid, d]) => [uid, d.role])); // preserve roles
participantDetails.clear();
if (keepBot) participantDetails.set(botMyId, keepBot);
for (const p of Object.values(evData.participantMap)) {
if (!p.name || !p.id) continue;
participantsCache.set(p.name.toLowerCase(), p.id);
const rawRole = p.role || p.level || p.privilege || (p.power != null && p.power > 0 ? 'moderator' : '') || '';
const wsRole = resolveRole(rawRole);
const prevRole = oldRoles.get(p.id) || '';
// Preserve elevated roles — don't reset Owner/Mod set by owner:command or DOM
const finalRole = (prevRole && prevRole !== 'Member') ? prevRole : wsRole;
participantDetails.set(p.id, { name: p.name, role: finalRole });
}
applyStaticRoles();
if (typeof commandHandler.updateUserMap === 'function')
commandHandler.updateUserMap(participantsCache);
if (!botJwk && evData.myself?.jwkKeyPair?.d && evData.myself?.id) {
botJwk = evData.myself.jwkKeyPair;
botMyId = evData.myself.id;
log(`[IDENTITY] JWK from WS ✓ uid=${botMyId}`, 'success');
}
}
// ── Owner transfer: room:[id]:owner:command type:"warning" = transfer, type:"danger" = kick
if (evName.includes(':owner:command') && evData?.system?.client?.id) {
const evType = evData.system.type || '';
const newId = evData.system.client.id;
const newName = evData.system.client.name || nameOf(newId);
participantsCache.set(newName.toLowerCase(), newId);
if (evType === 'warning') { // ownership transfer
for (const [uid, d] of participantDetails.entries()) {
if (d.role === 'Owner') participantDetails.set(uid, { ...d, role: 'Member' });
}
const ex = participantDetails.get(newId) || { name: newName };
participantDetails.set(newId, { ...ex, name: newName, role: 'Owner' });
updateParticipants();
log(`[OWNER-TRANSFER] → ${newName} (${newId})`, 'success');
} else if (evType === 'danger') {
log(`[KICK] ${newName} (${newId}) was kicked`, 'warn');
}
}
// ── modMap roles dari room:settings ───────────────────────────
if (evName.includes(':settings') && evData?.modMap) {
for (const [uid, info] of Object.entries(evData.modMap)) {
if (!info?.role) continue;
const role = resolveRole(info.role);
if (role !== 'Member') {
const ex2 = participantDetails.get(uid) || { name: nameOf(uid) };
participantDetails.set(uid, { ...ex2, role });
}
}
updateParticipants();
}
// WS-based chat (fallback path)
const chatData = parseChatPayload(evName, evData);
if (chatData) handleChatMessage(chatData);
// Detect owner dari creatorId/ownerId field
if (evData && typeof evData === 'object') {
const data = evData?.data || evData?.room || evData?.myself?.settings || evData;
const creatorId = data?.creatorId || data?.ownerId || data?.creator?.id || data?.owner?.id;
if (creatorId && typeof creatorId === 'string') {
const existing = participantDetails.get(creatorId) || { name: nameOf(creatorId) };
if (existing.role !== 'Owner') {
participantDetails.set(creatorId, { ...existing, role: 'Owner' });
log(`[ROOM] Owner from WS uid=${creatorId} (${existing.name})`, 'success');
}
}
if (!evName.includes('transporter') && !evName.includes('signaling')) {
// (verbose WS log dihapus untuk performa)
}
}
} catch (_) {}
});
ws.on('close', () => log(`[WS] Closed → ${ws.url()}`, 'warn'));
});
log('[WS] Participant cache listener active.', 'info');
}
// ── Leave detection: cari nama di page text (tile-only pattern) ───────────────
async function scanRoomParticipants() {
if (!page || botState.status !== 'ONLINE') return;
if (participantDetails.size === 0) return;
try {
const pageText = await page.evaluate(() => (document.body?.innerText || '').toLowerCase());
if (!pageText || pageText.length < 10) return;
let changed = false;
for (const [uid, d] of participantDetails.entries()) {
if (uid === botMyId) continue;
const name = (d.name || '').toLowerCase();
// Cari pola yang HANYA muncul di video tile F4T, bukan di chat history
const inTile = pageText.includes(`select ${name}`) || pageText.includes(`${name} settings`);
if (!inTile) {
participantDetails.delete(uid);
log(`[LEAVE] ${d.name} keluar dari room`, 'warn');
changed = true;
}
}
if (changed) applyStaticRoles();
} catch (_) {}
}
// ════════════════════════════════════════════════════════════════════════════
// MUSIC FUNCTIONS
// ════════════════════════════════════════════════════════════════════════════
// ── Mic toggle helpers ───────────────────────────────────────────────────────
async function unmuteMic() {
if (!page) return;
log('[MIC] Mencoba unmute...', 'info');
try {
await page.bringToFront();
// Cari button dengan text "Turn ON your microphone" (state: muted)
const clicked = await page.evaluate(() => {
const blinds = [...document.querySelectorAll('div.blind, .blind')];
const target = blinds.find(el =>
el.textContent.trim().toLowerCase().includes('turn on your microphone')
);
if (target) {
// Klik ancestor button
let btn = target;
while (btn && btn.tagName !== 'BUTTON') btn = btn.parentElement;
if (btn) { btn.click(); return true; }
}
return false;
});
if (clicked) {
log('[MIC] ✅ Unmuted (klik "Turn ON your microphone")', 'success');
} else {
log('[MIC] Button mic tidak ditemukan di DOM.', 'warn');
}
} catch (e) {
log(`[MIC] unmuteMic error: ${e.message}`, 'warn');
}
}
async function muteMic() {
if (!page) return;
log('[MIC] Mencoba mute...', 'info');
try {
await page.bringToFront();
// Cari button dengan text "Turn OFF your microphone" (state: unmuted)
const clicked = await page.evaluate(() => {
const blinds = [...document.querySelectorAll('div.blind, .blind')];
const target = blinds.find(el =>
el.textContent.trim().toLowerCase().includes('turn off your microphone')
);
if (target) {
let btn = target;
while (btn && btn.tagName !== 'BUTTON') btn = btn.parentElement;
if (btn) { btn.click(); return true; }
}
return false;
});
if (clicked) {
log('[MIC] ✅ Muted (klik "Turn OFF your microphone")', 'success');
} else {
log('[MIC] Button mic aktif tidak ditemukan di DOM.', 'warn');
}
} catch (e) {
log(`[MIC] muteMic error: ${e.message}`, 'warn');
}
}
// ── TTS: server-side wrapper ─────────────────────────────────────────────────
// Generate audio TTS, encode base64, push ke browser supaya diputar lewat
// virtual mic pipeline (window._micDest). Auto-handle mic state (unmute saat
// ngomong, mute lagi setelah selesai kalau sebelumnya muted).
let _ttsBusy = false;
async function speakTTS(text, opts = {}) {
if (!page) throw new Error('Bot belum aktif (no page)');
if (_ttsBusy) throw new Error('TTS sedang ngomong, tunggu selesai');
_ttsBusy = true;
let micWasMuted = false;
try {
log(`[TTS] Generating: "${String(text).slice(0, 60)}${text.length > 60 ? '...' : ''}"`, 'info');
const buf = await generateTTS(text, opts);
const b64 = buf.toString('base64');
log(`[TTS] Buffer ${(buf.length / 1024).toFixed(1)}KB ready, broadcasting...`, 'info');
// Cek apakah mic muted (cari tombol "Turn ON your microphone")
micWasMuted = await page.evaluate(() => {
const blinds = [...document.querySelectorAll('div.blind, .blind')];
return blinds.some(el => el.textContent.trim().toLowerCase().includes('turn on your microphone'));
}).catch(() => false);
if (micWasMuted) {
log('[TTS] Mic muted — auto-unmuting...', 'info');
await unmuteMic();
await new Promise(r => setTimeout(r, 400)); // beri waktu state settle
}
// Putar TTS via pipeline; resolve saat audio.onended.
await page.evaluate(b => window._speakInPipeline(b), b64);
log('[TTS] ✅ Selesai ngomong', 'success');
} finally {
// Restore mic state
if (micWasMuted) {
await new Promise(r => setTimeout(r, 200));
await muteMic().catch(() => {});
}
_ttsBusy = false;
}
}
function isTTSBusy() { return _ttsBusy; }
// ── Music race-condition guards ───────────────────────────────────────────
let _streamToken = 0; // increment setiap startStream baru — cegah stale stream
let _isSearching = false; // mutex: hanya 1 yts+yt-dlp boleh jalan bersamaan
let _pendingSongRequests = [];
let _songRequestGeneration = 0;
function clearPendingSongRequests() {
_songRequestGeneration++;
_pendingSongRequests = [];
}
async function stopAudio() {
if (page) {
await page.evaluate(() => {
if (window._audioElement) {
window._audioElement.pause();
window._audioElement.src = '';
}
}).catch(() => {});
}
}
async function playNext() {
if (botState.isRepeating && botState.currentSong) return startStream(botState.currentSong);
if (botState.queue.length > 0) {
botState.currentSong = botState.queue.shift();
await startStream(botState.currentSong);
} else if (_isSearching || _pendingSongRequests.length > 0) {
_streamToken++;
botState.isPlaying = false;
botState.currentSong = null;
await stopAudio();
await muteMic();
log('Queue kosong, menunggu request lagu yang masih diproses.', 'info');
updateStatus();
} else {
_streamToken++; // invalidate any in-flight fetch
botState.isPlaying = false;
botState.currentSong = null;
await stopAudio();
await muteMic();
log('Queue empty.', 'warn');
updateStatus();
await sendMessage('⏹ Playlist selesai.');
}
}
async function startStream(song) {
_streamToken++;
const myToken = _streamToken;
botState.isPlaying = true;
botState.currentSong = song;
updateStatus();
log(`Preparing stream: ${song.title} (Req: ${song.requestedBy})`, 'info');
await sendMessage(`⏳ Menyiapkan stream: ${song.title}\n👤 Requested by: ${song.requestedBy}`);
try {
log(`[MUSIC] Fetching stream URL...`, 'info');
const [streamUrl] = await Promise.all([
getStreamUrl(song.url),
unmuteMic()
]);
// Token berubah = ada skip/stop/play baru → batalkan ini
if (myToken !== _streamToken) {
log(`[MUSIC] Stream token mismatch (${myToken}≠${_streamToken}) — discarding stale stream.`, 'warn');
return;
}
await page.evaluate(async url => {
if (!window._audioElement) throw new Error('_audioElement not initialized');
const audio = window._audioElement;
audio.pause();
audio.src = '';
audio.volume = window._botVolume || 0.1;
await new Promise((resolve, reject) => {
let settled = false;
const cleanup = () => {
clearTimeout(timer);
audio.removeEventListener('playing', onPlaying);
audio.removeEventListener('error', onError);
};
const finishOk = () => {
if (settled) return;
settled = true;
cleanup();
resolve();
};
const finishErr = (err) => {
if (settled) return;
settled = true;
cleanup();
reject(err);
};
const onPlaying = () => finishOk();
const onError = () => finishErr(new Error('audio playback error'));
const timer = setTimeout(() => finishErr(new Error('audio start timeout')), 15000);
audio.addEventListener('playing', onPlaying, { once: true });
audio.addEventListener('error', onError, { once: true });
audio.src = url;
const playPromise = audio.play();
if (playPromise && typeof playPromise.catch === 'function') {
playPromise.catch(err => finishErr(new Error(err?.message || 'audio play() failed')));
}
});
}, streamUrl);
log(`[MUSIC] Playback started.`, 'success');
log(`Now Playing: ${song.title} (Req: ${song.requestedBy})`, 'success');
await sendMessage(`🎶 Now Playing: ${song.title}\n👤 Requested by: ${song.requestedBy}`);
preFetchNextSong(); // pre-fetch lagu berikutnya di background
} catch (e) {
if (myToken !== _streamToken) return; // already superseded
const detail = e?.stderr || e?.message || e?.toString() || JSON.stringify(e);
log(`Stream Error: ${detail}`, 'error');
await sendMessage(`❌ Gagal memutar: ${song.title}`);
playNext();
}
}
async function processPendingSongRequests() {
if (_isSearching) return;
_isSearching = true;
try {
while (_pendingSongRequests.length > 0) {
const request = _pendingSongRequests.shift();
if (!request || request.generation !== _songRequestGeneration) continue;
await sendMessage(`🔍 Mencari: "${request.query}"...`);
log(`Searching: "${request.query}"...`, 'cmd');
try {
const search = await yts(request.query);
if (request.generation !== _songRequestGeneration) continue;
if (!search.videos.length) {
await sendMessage(`❌ Lagu tidak ditemukan: "${request.query}"`);
continue;
}
const song = {
title: search.videos[0].title,
url: search.videos[0].url,
duration: search.videos[0].timestamp,
requestedBy: request.requesterName
};
if (request.generation !== _songRequestGeneration) continue;
if (botState.isPlaying) {
botState.queue.push(song);
log(`Added to queue: ${song.title}`, 'success');
updateStatus();
await sendMessage(`📝 Ditambahkan ke antrean (#${botState.queue.length}): ${song.title}`);
if (botState.queue.length === 1) getStreamUrl(song.url).catch(() => {});
} else {
await startStream(song);
}
} catch (e) {
if (request.generation !== _songRequestGeneration) continue;
log(`Search Error: ${e.message}`, 'error');
await sendMessage('❌ Terjadi kesalahan saat mencari lagu.');
}
}
} finally {
_isSearching = false;
if (_pendingSongRequests.length > 0) {
processPendingSongRequests().catch(e => log(`Search Queue Error: ${e.message}`, 'error'));
}
}
}
async function addToQueue(query, requesterName = 'Unknown') {
_pendingSongRequests.push({ query, requesterName, generation: _songRequestGeneration });
if (_isSearching) {
const waitCount = _pendingSongRequests.length;
if (waitCount > 1) {
await sendMessage(`📝 Permintaan diterima, masuk antrean proses (#${waitCount}): ${query}`);
} else {
await sendMessage(`📝 Permintaan diterima, menunggu proses lagu sebelumnya: ${query}`);
}
}
await processPendingSongRequests();
}