Reooiq commited on
Commit
aaf2061
·
verified ·
1 Parent(s): 8fa7655

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +75 -212
index.js CHANGED
@@ -4,18 +4,14 @@ const http = require('http');
4
  const dns = require('dns');
5
  const { URL } = require('url');
6
 
 
7
  const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
8
  const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
9
  const SESSION_ID = process.env.SESSION_ID || undefined;
10
  const MY_PROXY_URL = "https://tg-proxy.dr-toktok00.workers.dev";
11
 
12
- // ✅ دعم مذيعين أو أكثر
13
- const RAW = process.env.TIKTOK_USERNAMES || process.env.TIKTOK_USERNAME || '';
14
- const STREAMERS = RAW.split(',').map(s => s.trim()).filter(s => s.length > 0);
15
-
16
  dns.setServers(['8.8.8.8']);
17
 
18
- // ====== قاموس الدول ======
19
  const COUNTRY_FLAGS = {
20
  'SA': { name: 'السعودية', flag: '🇸🇦' },
21
  'EG': { name: 'مصر', flag: '🇪🇬' },
@@ -112,12 +108,12 @@ const GIFT_ARABIC = {
112
  'trophy':'كأس','medal':'وسام','flag':'علم',
113
  'wizard':'ساحر','ninja':'نينجا','pirate':'قراصنة',
114
  'santa':'سانتا','flower':'زهرة','crown prince':'ولي عهد',
115
- 'neon heart':'قلب نيون','golden heart':'قلب ذهبي',
116
- 'silver heart':'قلب فضي','black heart':'قلب أسود',
117
- 'broken heart':'قلب مكسور','fire heart':'قلب محترق',
118
- 'sparkling heart':'قلب لامع','yellow heart':'قلب أصفر',
119
- 'green heart':'قلب أخضر','money':'مال','cash':'كاش',
120
- 'money rain':'مطر مال','viking':'فايكنغ','pharaoh':'فرعون',
121
  'thumbs up':'إبهام','smile':'ابتسامة','love':'حب',
122
  'kiss':'قبلة','bandage':'ضماد','ghost':'شبح','skull':'جمجمة',
123
  'sun':'شمس','moon':'قمر','comet':'مذنب','planet':'كوكب',
@@ -126,7 +122,7 @@ const GIFT_ARABIC = {
126
  'diamond crown':'تاج ماسي','diamond heart':'قلب ماسي',
127
  'super star':'نجمة خارقة','mega star':'نجمة عملاقة',
128
  'legend':'أسطوري','epic':'ملحمي',
129
- 'halo':'هالة','wings':'أجنحة','bow':'قوس','arrow':'سهم',
130
  'cherry':'كرز','apple':'تفاحة','grape':'عنب',
131
  'watermelon':'بطيخ','strawberry':'فراولة',
132
  'banana':'موز','peach':'خوخ','cupcake':'كعكة صغيرة',
@@ -137,6 +133,7 @@ const GIFT_ARABIC = {
137
  'flower garden':'حديقة زهور','treasure':'كنز',
138
  'crystal ball':'كرة بلورية','tropical island':'جزيرة استوائية',
139
  'royal carriage':'عربة ملكية','treasure chest':'كنز',
 
140
  };
141
 
142
  const GIFT_VALUES = {
@@ -192,7 +189,6 @@ const GIFT_VALUES = {
192
  7859:1000000, 7858:1000000,
193
  };
194
 
195
- // ====== دوال ======
196
  function getCountryInfo(code) {
197
  if (!code) return { name: 'غير محدد', flag: '🌍' };
198
  return COUNTRY_FLAGS[code.toUpperCase()] || { name: code, flag: '🌍' };
@@ -354,56 +350,33 @@ async function sendToTelegram(text, photoUrl = null, buttons = null) {
354
  }
355
  }
356
 
357
- // ====== كاش المستخدمين ======
358
  const regionCache = {};
359
 
360
  async function fetchUserRegion(username) {
361
  if (!username) return null;
362
  if (regionCache[username]) return regionCache[username];
363
  const result = await getRegionFromPage(username);
364
- if (result) {
365
- regionCache[username] = result;
366
- }
367
  return result;
368
  }
369
 
370
- // ====== فحص هل المستخدم لايف ======
371
- async function checkIfLive(username) {
372
- const checkConn = new TikTokLiveConnection(username, {
373
- processInitialData: false,
374
- enableExtendedGiftInfo: false,
375
- fetchRoomInfoOnConnect: true,
376
- clientParams: { app_language: "en-US", device_platform: "web" }
377
- });
378
- try {
379
- const state = await checkConn.connect();
380
- checkConn.disconnect();
381
- return { live: true, state };
382
- } catch (e) {
383
- return { live: false, error: e.message || e };
384
- }
385
- }
386
-
387
  // ====== متغيرات ======
388
  let maxViewers = 0, totalLikes = 0, totalShares = 0;
389
  let streamStartTime = null;
390
  let giftersMap = {};
391
  let pkActive = false;
392
  let pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
393
- let isMonitoring = false;
394
- let monitoringUsername = null;
395
- let activeConn = null;
396
- let liveQueue = [];
397
 
398
  function getTopGifters(map, top = 5) {
399
  return Object.values(map).sort((a, b) => b.coins - a.coins).slice(0, top);
400
  }
401
 
402
  // ====== إرسال إشعار بداية البث ======
403
- async function sendStartNotification(username, state) {
404
- const userRegion = await getRegionFromPage(username);
405
  const countryInfo = getCountryInfo(userRegion?.region || null);
406
- const liveLink = 'https://www.tiktok.com/@' + username + '/live';
407
 
408
  let avatarUrl = '';
409
  const owner = state.roomInfo?.owner || null;
@@ -422,19 +395,20 @@ async function sendStartNotification(username, state) {
422
  avatarUrl = state.roomInfo?.sharedCover || state.roomInfo?.coverUrl || '';
423
  }
424
 
425
- const displayName = userRegion?.nickname || username;
426
  const verifiedBadge = userRegion?.verified ? ' ✅' : '';
427
 
428
  const msg = '🔴 ' + displayName + verifiedBadge + '\n\n' +
429
- '🌐 @' + username + '\n' +
430
  countryInfo.flag + ' ' + countryInfo.name + '\n' +
431
  '⏰ ' + getBaghdadTime();
432
 
433
  sendToTelegram(msg, avatarUrl || undefined, [[{ text: "📺 دخول البث المباشر", url: liveLink }]]);
 
434
  }
435
 
436
- // ====== ربط أحداث المراقبة ======
437
- function attachEvents(conn, username) {
438
  conn.on(WebcastEvent.ROOM_USER, data => {
439
  if (data.viewerCount > maxViewers) maxViewers = data.viewerCount;
440
  });
@@ -499,7 +473,7 @@ function attachEvents(conn, username) {
499
 
500
  sendToTelegram(msg, null, [[
501
  { text: "👤 حسابه", url: 'https://www.tiktok.com/@' + gifterUsername },
502
- { text: "📺 دخول البث", url: 'https://www.tiktok.com/@' + username + '/live' }
503
  ]]);
504
  });
505
 
@@ -521,7 +495,7 @@ function attachEvents(conn, username) {
521
  conn.on('pkStart', data => {
522
  pkActive = true;
523
  pkInfo = { opponentName: data.opponentNickname || 'منافس', ourLikes: 0, theirLikes: 0 };
524
- sendToTelegram('⚔️ ' + pkInfo.opponentName, null, [[{ text: "🚀 دعم البث", url: 'https://www.tiktok.com/@' + username + '/live' }]]);
525
  });
526
 
527
  conn.on('pkUpdate', data => {
@@ -535,16 +509,10 @@ function attachEvents(conn, username) {
535
  '🟦 نحن: ' + formatK(pkInfo.ourLikes) + ' | ' + formatK(pkInfo.theirLikes) + ' 🟥\n\n' +
536
  generateProgressBar(pkInfo.ourLikes, pkInfo.theirLikes));
537
  });
538
-
539
- conn.on(WebcastEvent.DISCONNECTED, () => onStreamEnd(username));
540
- conn.on('streamEnd', () => onStreamEnd(username));
541
  }
542
 
543
  // ====== نهاية البث ======
544
- function onStreamEnd(username) {
545
- if (!isMonitoring || monitoringUsername !== username) return;
546
- console.log('📴 انتهى: ' + username);
547
-
548
  const duration = streamStartTime ? formatDuration(Math.floor((Date.now() - streamStartTime) / 1000)) : 'غير معروف';
549
  const top = getTopGifters(giftersMap, 5);
550
  const medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
@@ -563,7 +531,7 @@ function onStreamEnd(username) {
563
  ['👑', '🥈', '🥉'][i] + ' ' + getCountryInfo(r).flag + ' ' + getCountryInfo(r).name + ' → ' + formatK(c) + ' 💎'
564
  ).join('\n') || 'لا بيانات';
565
 
566
- sendToTelegram('📊 التقرير النهائي - @' + username + '\n\n' +
567
  '⏱️ مدة البث: ' + duration + '\n' +
568
  '👥 أعلى مشاهدات: ' + formatK(maxViewers) + '\n' +
569
  '❤️ إعجابات: ' + formatK(totalLikes) + '\n' +
@@ -572,183 +540,78 @@ function onStreamEnd(username) {
572
  '🏆 أقوى داعمين:\n\n' + topText + '\n\n' +
573
  '🌍 توزيع حسب الدولة:\n' + countryRanking + '\n\n💤 بانتظار البث القادم...');
574
 
575
- stopMonitoring();
576
  }
577
 
578
- // ====== بدء المراقبة ======
579
- async function startMonitoring(username, state) {
580
- if (isMonitoring) return;
581
- isMonitoring = true;
582
- monitoringUsername = username;
583
- giftersMap = {};
584
- regionCache = {};
585
- maxViewers = 0;
586
- totalLikes = 0;
587
- totalShares = 0;
588
- pkActive = false;
589
- pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
590
- streamStartTime = Date.now();
591
-
592
- console.log('🎬 بداية بث: @' + username);
593
-
594
- await sendStartNotification(username, state);
595
-
596
- activeConn = new TikTokLiveConnection(username, {
597
- processInitialData: true,
598
- enableExtendedGiftInfo: true,
599
- clientParams: { app_language: "ar-IQ", device_platform: "web" }
600
- });
601
-
602
- attachEvents(activeConn, username);
603
-
604
- try {
605
- await activeConn.connect();
606
- console.log('🎯 متصل: ' + username);
607
- } catch (e) {
608
- console.log('⚠️ فشل: ' + (e.message || e));
609
- stopMonitoring();
610
- setTimeout(() => scanAll(), 10000);
611
- }
612
- }
613
 
614
- function stopMonitoring() {
 
615
  if (activeConn) {
616
  try { activeConn.disconnect(); } catch (e) {}
617
  activeConn = null;
618
  }
619
- isMonitoring = false;
620
- monitoringUsername = null;
621
- }
622
 
623
- // ====== إرسال أزرار اختيار ======
624
- async function sendChooseMessage(liveList) {
625
- let text = '🔴 أكثر من مذيع لايف الآن!\n\nاختر من تبي تراقب:\n\n';
626
- text += liveList.map((s, i) => (i + 1) + ') @' + s.username).join('\n');
627
-
628
- const buttons = [];
629
- let row = [];
630
- liveList.forEach((s, i) => {
631
- // ✅ callback_data قصيرة جداً (أقل من 64 حرف)
632
- row.push({ text: (i + 1) + '️⃣ @' + s.username, callback_data: 'p' + i });
633
- if (row.length === 2) { buttons.push(row); row = []; }
634
- });
635
- if (row.length > 0) buttons.push(row);
636
- buttons.push([{ text: '🔄 تحديث', callback_data: 'r' }]);
637
 
638
- sendToTelegram(text, null, buttons);
639
- }
 
 
 
640
 
641
- // ====== الفحص الدوري ======
642
- async function scanAll() {
643
- if (isMonitoring) {
644
- console.log('👀 يراقب: @' + monitoringUsername);
645
- return;
646
- }
 
 
 
 
 
 
647
 
648
- console.log('🔍 فحص ' + STREAMERS.length + ' مذيع...');
649
- const liveList = [];
650
-
651
- for (const name of STREAMERS) {
652
- try {
653
- const result = await checkIfLive(name);
654
- if (result.live) {
655
- liveList.push({ username: name, state: result.state });
656
- console.log('🟢 @' + name + ' - لايف!');
657
- } else {
658
- console.log('🔴 @' + name + ' - مغلق');
659
- }
660
- } catch (e) {
661
- console.log('⚠️ خطأ: @' + name + ': ' + (e.message || e));
662
- }
663
- }
664
 
665
- if (liveList.length === 0) {
666
- console.log('😴 الكل مغلق');
667
- } else if (liveList.length === 1) {
668
- console.log('✅ واحد: @' + liveList[0].username);
669
- await startMonitoring(liveList[0].username, liveList[0].state);
670
- } else {
671
- console.log('⚠️ ' + liveList.length + ' لايف - أزرار اختيار');
672
- liveQueue = liveList; // ✅ نحفظ القائمة
673
- await sendChooseMessage(liveList);
674
- }
675
- }
676
 
677
- // ====== استقبال ردود الأزرار ======
678
- async function pollTelegram() {
679
- try {
680
- const offsetUrl = `${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}/getUpdates?timeout=10&offset=${global.lastUpdateId || 0}`;
681
- const response = await httpGet(offsetUrl);
682
- const result = JSON.parse(response.data);
683
-
684
- if (result.ok && result.result) {
685
- for (const update of result.result) {
686
- if (update.update_id) global.lastUpdateId = update.update_id + 1;
687
-
688
- if (update.callback_query) {
689
- const cq = update.callback_query;
690
- const cb = cq.data || '';
691
- const chatId = cq.message?.chat?.id || TELEGRAM_CHAT_ID;
692
-
693
- // ✅ اختيار مذيع
694
- if (cb.startsWith('p') && liveQueue.length > 0) {
695
- const idx = parseInt(cb.replace('p', ''));
696
- if (!isNaN(idx) && idx < liveQueue.length) {
697
- const chosen = liveQueue[idx].username;
698
- console.log('👆 اختار: @' + chosen);
699
-
700
- await httpPost(`${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}/answerCallbackQuery`, {
701
- callback_query_id: cq.id, text: '✅ اخترت @' + chosen
702
- });
703
-
704
- const check = await checkIfLive(chosen);
705
- if (check.live) {
706
- await startMonitoring(chosen, check.state);
707
- liveQueue = [];
708
- } else {
709
- sendToTelegram('@' + chosen + ' ما فاتح الآن! 🔍');
710
- liveQueue = [];
711
- await scanAll();
712
- }
713
- }
714
- }
715
- // ✅ تحديث
716
- else if (cb === 'r') {
717
- await httpPost(`${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}/answerCallbackQuery`, {
718
- callback_query_id: cq.id, text: '🔄 جاري الفحص...'
719
- });
720
- liveQueue = [];
721
- await scanAll();
722
- }
723
- }
724
-
725
- // ✅ رسالة نصية (رقم)
726
- if (update.message && update.message.text) {
727
- const num = parseInt(update.message.text.trim());
728
- if (!isNaN(num) && num >= 1 && liveQueue.length > 0 && num <= liveQueue.length) {
729
- const chosen = liveQueue[num - 1].username;
730
- console.log('👆 اختار برقم: @' + chosen);
731
- const check = await checkIfLive(chosen);
732
- if (check.live) {
733
- await startMonitoring(chosen, check.state);
734
- liveQueue = [];
735
- }
736
- }
737
- }
738
- }
739
- }
740
  } catch (e) {
741
- // تجاهل أخطاء polling
 
 
 
 
 
 
 
 
742
  }
743
  }
744
 
745
  // ====== التشغيل ======
746
- console.log('✅ جاهز | مذيعون: ' + STREAMERS.join(', '));
747
 
748
- setTimeout(scanAll, 3000);
749
- setInterval(scanAll, 30000);
750
- setInterval(pollTelegram, 3000);
751
 
 
752
  const server = http.createServer((req, res) => {
753
  res.writeHead(200, { 'Content-Type': 'text/plain' });
754
  res.end('OK');
 
4
  const dns = require('dns');
5
  const { URL } = require('url');
6
 
7
+ const TIKTOK_USERNAME = process.env.TIKTOK_USERNAME || process.env.TIKTOK_USERNAMES?.split(',')[0]?.trim() || '';
8
  const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
9
  const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
10
  const SESSION_ID = process.env.SESSION_ID || undefined;
11
  const MY_PROXY_URL = "https://tg-proxy.dr-toktok00.workers.dev";
12
 
 
 
 
 
13
  dns.setServers(['8.8.8.8']);
14
 
 
15
  const COUNTRY_FLAGS = {
16
  'SA': { name: 'السعودية', flag: '🇸🇦' },
17
  'EG': { name: 'مصر', flag: '🇪🇬' },
 
108
  'trophy':'كأس','medal':'وسام','flag':'علم',
109
  'wizard':'ساحر','ninja':'نينجا','pirate':'قراصنة',
110
  'santa':'سانتا','flower':'زهرة','crown prince':'ولي عهد',
111
+ 'neon heart':'قلب نيون','silver heart':'قلب فضي',
112
+ 'black heart':'قلب أسود','broken heart':'قلب مكسور',
113
+ 'fire heart':'قلب محترق','sparkling heart':'قلب لامع',
114
+ 'yellow heart':'قلب أصفر','green heart':'قلب أخضر',
115
+ 'money':'مال','cash':'كاش','money rain':'مطر مال',
116
+ 'viking':'فايكنغ','pharaoh':'فرعون',
117
  'thumbs up':'إبهام','smile':'ابتسامة','love':'حب',
118
  'kiss':'قبلة','bandage':'ضماد','ghost':'شبح','skull':'جمجمة',
119
  'sun':'شمس','moon':'قمر','comet':'مذنب','planet':'كوكب',
 
122
  'diamond crown':'تاج ماسي','diamond heart':'قلب ماسي',
123
  'super star':'نجمة خارقة','mega star':'نجمة عملاقة',
124
  'legend':'أسطوري','epic':'ملحمي',
125
+ 'bow':'قوس','arrow':'سهم',
126
  'cherry':'كرز','apple':'تفاحة','grape':'عنب',
127
  'watermelon':'بطيخ','strawberry':'فراولة',
128
  'banana':'موز','peach':'خوخ','cupcake':'كعكة صغيرة',
 
133
  'flower garden':'حديقة زهور','treasure':'كنز',
134
  'crystal ball':'كرة بلورية','tropical island':'جزيرة استوائية',
135
  'royal carriage':'عربة ملكية','treasure chest':'كنز',
136
+ '100':'100',
137
  };
138
 
139
  const GIFT_VALUES = {
 
189
  7859:1000000, 7858:1000000,
190
  };
191
 
 
192
  function getCountryInfo(code) {
193
  if (!code) return { name: 'غير محدد', flag: '🌍' };
194
  return COUNTRY_FLAGS[code.toUpperCase()] || { name: code, flag: '🌍' };
 
350
  }
351
  }
352
 
353
+ // ====== كاش ======
354
  const regionCache = {};
355
 
356
  async function fetchUserRegion(username) {
357
  if (!username) return null;
358
  if (regionCache[username]) return regionCache[username];
359
  const result = await getRegionFromPage(username);
360
+ if (result) regionCache[username] = result;
 
 
361
  return result;
362
  }
363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  // ====== متغيرات ======
365
  let maxViewers = 0, totalLikes = 0, totalShares = 0;
366
  let streamStartTime = null;
367
  let giftersMap = {};
368
  let pkActive = false;
369
  let pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
 
 
 
 
370
 
371
  function getTopGifters(map, top = 5) {
372
  return Object.values(map).sort((a, b) => b.coins - a.coins).slice(0, top);
373
  }
374
 
375
  // ====== إرسال إشعار بداية البث ======
376
+ async function sendStartNotification(state) {
377
+ const userRegion = await getRegionFromPage(TIKTOK_USERNAME);
378
  const countryInfo = getCountryInfo(userRegion?.region || null);
379
+ const liveLink = 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live';
380
 
381
  let avatarUrl = '';
382
  const owner = state.roomInfo?.owner || null;
 
395
  avatarUrl = state.roomInfo?.sharedCover || state.roomInfo?.coverUrl || '';
396
  }
397
 
398
+ const displayName = userRegion?.nickname || TIKTOK_USERNAME;
399
  const verifiedBadge = userRegion?.verified ? ' ✅' : '';
400
 
401
  const msg = '🔴 ' + displayName + verifiedBadge + '\n\n' +
402
+ '🌐 @' + TIKTOK_USERNAME + '\n' +
403
  countryInfo.flag + ' ' + countryInfo.name + '\n' +
404
  '⏰ ' + getBaghdadTime();
405
 
406
  sendToTelegram(msg, avatarUrl || undefined, [[{ text: "📺 دخول البث المباشر", url: liveLink }]]);
407
+ console.log('📸 صورة: ' + (avatarUrl ? '✅ متوفرة' : '❌ غير متوفرة'));
408
  }
409
 
410
+ // ====== ربط الأحداث ======
411
+ function attachEvents(conn) {
412
  conn.on(WebcastEvent.ROOM_USER, data => {
413
  if (data.viewerCount > maxViewers) maxViewers = data.viewerCount;
414
  });
 
473
 
474
  sendToTelegram(msg, null, [[
475
  { text: "👤 حسابه", url: 'https://www.tiktok.com/@' + gifterUsername },
476
+ { text: "📺 دخول البث", url: 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live' }
477
  ]]);
478
  });
479
 
 
495
  conn.on('pkStart', data => {
496
  pkActive = true;
497
  pkInfo = { opponentName: data.opponentNickname || 'منافس', ourLikes: 0, theirLikes: 0 };
498
+ sendToTelegram('⚔️ ' + pkInfo.opponentName, null, [[{ text: "🚀 دعم البث", url: 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live' }]]);
499
  });
500
 
501
  conn.on('pkUpdate', data => {
 
509
  '🟦 نحن: ' + formatK(pkInfo.ourLikes) + ' | ' + formatK(pkInfo.theirLikes) + ' 🟥\n\n' +
510
  generateProgressBar(pkInfo.ourLikes, pkInfo.theirLikes));
511
  });
 
 
 
512
  }
513
 
514
  // ====== نهاية البث ======
515
+ function onStreamEnd() {
 
 
 
516
  const duration = streamStartTime ? formatDuration(Math.floor((Date.now() - streamStartTime) / 1000)) : 'غير معروف';
517
  const top = getTopGifters(giftersMap, 5);
518
  const medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
 
531
  ['👑', '🥈', '🥉'][i] + ' ' + getCountryInfo(r).flag + ' ' + getCountryInfo(r).name + ' → ' + formatK(c) + ' 💎'
532
  ).join('\n') || 'لا بيانات';
533
 
534
+ sendToTelegram('📊 التقرير النهائي\n\n' +
535
  '⏱️ مدة البث: ' + duration + '\n' +
536
  '👥 أعلى مشاهدات: ' + formatK(maxViewers) + '\n' +
537
  '❤️ إعجابات: ' + formatK(totalLikes) + '\n' +
 
540
  '🏆 أقوى داعمين:\n\n' + topText + '\n\n' +
541
  '🌍 توزيع حسب الدولة:\n' + countryRanking + '\n\n💤 بانتظار البث القادم...');
542
 
543
+ console.log('📴 انتهى البث - انتظار...');
544
  }
545
 
546
+ // ====== ✅ الاتصال المباشر بدون فحص ======
547
+ let activeConn = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
 
549
+ async function tryConnect() {
550
+ // ✅ نغلق أي اتصال سابق
551
  if (activeConn) {
552
  try { activeConn.disconnect(); } catch (e) {}
553
  activeConn = null;
554
  }
 
 
 
555
 
556
+ console.log('⏳ محاولة الاتصال: @' + TIKTOK_USERNAME);
 
 
 
 
 
 
 
 
 
 
 
 
 
557
 
558
+ activeConn = new TikTokLiveConnection(TIKTOK_USERNAME, {
559
+ processInitialData: true,
560
+ enableExtendedGiftInfo: true,
561
+ clientParams: { app_language: "ar-IQ", device_platform: "web" }
562
+ });
563
 
564
+ // ✅ نربط الأحداث قبل الاتصال
565
+ attachEvents(activeConn);
566
+ activeConn.on(WebcastEvent.DISCONNECTED, () => {
567
+ console.log('❌ قطع الاتصال');
568
+ onStreamEnd();
569
+ setTimeout(tryConnect, 30000);
570
+ });
571
+ activeConn.on('streamEnd', () => {
572
+ console.log('📴 انتهى البث');
573
+ onStreamEnd();
574
+ setTimeout(tryConnect, 30000);
575
+ });
576
 
577
+ try {
578
+ const state = await activeConn.connect();
579
+ console.log('✅ متصل بالغرفة!');
580
+ console.log('📡 Room ID:', state.roomId);
581
+
582
+ // ✅ إعادة ضبط المتغيرات
583
+ maxViewers = 0;
584
+ totalLikes = 0;
585
+ totalShares = 0;
586
+ giftersMap = {};
587
+ regionCache = {};
588
+ pkActive = false;
589
+ pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
590
+ streamStartTime = Date.now();
 
 
591
 
592
+ // ✅ إرسال إشعار بداية البث
593
+ await sendStartNotification(state);
 
 
 
 
 
 
 
 
 
594
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
595
  } catch (e) {
596
+ let errMsg = '';
597
+ if (e && typeof e === 'object') {
598
+ errMsg = e.message || e.name || String(e);
599
+ } else {
600
+ errMsg = String(e);
601
+ }
602
+ console.log('🔎 غير متاح: ' + errMsg);
603
+ console.log('⏰ إعادة المحاولة بعد 60 ثانية...');
604
+ setTimeout(tryConnect, 60000);
605
  }
606
  }
607
 
608
  // ====== التشغيل ======
609
+ console.log('✅ جاهز | @' + TIKTOK_USERNAME);
610
 
611
+ // ✅ محاولة الاتصال مباشرة
612
+ setTimeout(tryConnect, 2000);
 
613
 
614
+ // الخادم
615
  const server = http.createServer((req, res) => {
616
  res.writeHead(200, { 'Content-Type': 'text/plain' });
617
  res.end('OK');