Reooiq commited on
Commit
d36df1d
·
verified ·
1 Parent(s): f83afd5

Update index.js

Browse files
Files changed (1) hide show
  1. index.js +53 -333
index.js CHANGED
@@ -10,15 +10,12 @@ const TIKTOK_USERNAME = process.env.TIKTOK_USERNAME;
10
  const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
11
  const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
12
  const SESSION_ID = process.env.SESSION_ID;
13
-
14
- // رابط الجسر الخاص بك في Cloudflare
15
  const MY_PROXY_URL = "https://tg-proxy.dr-toktok00.workers.dev";
16
 
17
  dns.setServers(['8.8.8.8']);
18
 
19
  // --- قاموس الدول بالأعلام ---
20
  const COUNTRY_FLAGS = {
21
- // الدول العربية
22
  'SA': { name: 'المملكة العربية السعودية', flag: '🇸🇦' },
23
  'EG': { name: 'مصر', flag: '🇪🇬' },
24
  'AE': { name: 'الإمارات العربية المتحدة', flag: '🇦🇪' },
@@ -39,9 +36,7 @@ const COUNTRY_FLAGS = {
39
  'SO': { name: 'الصومال', flag: '🇸🇴' },
40
  'DJ': { name: 'جيبوتي', flag: '🇩🇯' },
41
  'MR': { name: 'موريتانيا', flag: '🇲🇷' },
42
-
43
- // دول عالمية أخرى
44
- 'US': { name: 'الولايات المتحدة الأمريكية', flag: '🇺🇸' },
45
  'GB': { name: 'المملكة المتحدة', flag: '🇬🇧' },
46
  'TR': { name: 'تركيا', flag: '🇹🇷' },
47
  'FR': { name: 'فرنسا', flag: '🇫🇷' },
@@ -49,7 +44,6 @@ const COUNTRY_FLAGS = {
49
  'IT': { name: 'إيطاليا', flag: '🇮🇹' },
50
  'ES': { name: 'إسبانيا', flag: '🇪🇸' },
51
  'BR': { name: 'البرازيل', flag: '🇧🇷' },
52
- 'PT': { name: 'البرتغال', flag: '🇵🇹' },
53
  'RU': { name: 'روسيا', flag: '🇷🇺' },
54
  'CN': { name: 'الصين', flag: '🇨🇳' },
55
  'JP': { name: 'اليابان', flag: '🇯🇵' },
@@ -64,7 +58,6 @@ const COUNTRY_FLAGS = {
64
  'PK': { name: 'باكستان', flag: '🇵🇰' },
65
  'BD': { name: 'بنغلاديش', flag: '🇧🇩' },
66
  'IR': { name: 'إيران', flag: '🇮🇷' },
67
- 'AF': { name: 'أفغانستان', flag: '🇦🇫' },
68
  'AR': { name: 'الأرجنتين', flag: '🇦🇷' },
69
  'MX': { name: 'المكسيك', flag: '🇲🇽' },
70
  'CO': { name: 'كولومبيا', flag: '🇨🇴' },
@@ -75,18 +68,6 @@ const COUNTRY_FLAGS = {
75
  'NZ': { name: 'نيوزيلندا', flag: '🇳🇿' },
76
  'ZA': { name: 'جنوب أفريقيا', flag: '🇿🇦' },
77
  'NG': { name: 'نيجيريا', flag: '🇳🇬' },
78
- 'KE': { name: 'كينيا', flag: '🇰🇪' },
79
- 'GH': { name: 'غانا', flag: '🇬🇭' },
80
-
81
- // دول آسيوية أخرى
82
- 'TW': { name: 'تايوان', flag: '🇹🇼' },
83
- 'HK': { name: 'هونغ كونغ', flag: '🇭🇰' },
84
- 'MM': { name: 'ميانمار', flag: '🇲🇲' },
85
- 'NP': { name: 'نيبال', flag: '🇳🇵' },
86
- 'LK': { name: 'سريلانكا', flag: '🇱🇰' },
87
- 'MV': { name: 'جزر المالديف', flag: '🇲🇻' },
88
-
89
- // دول أوروبية
90
  'NL': { name: 'هولندا', flag: '🇳🇱' },
91
  'BE': { name: 'بلجيكا', flag: '🇧🇪' },
92
  'CH': { name: 'سويسرا', flag: '🇨🇭' },
@@ -97,68 +78,24 @@ const COUNTRY_FLAGS = {
97
  'DK': { name: 'الدنمارك', flag: '🇩🇰' },
98
  'FI': { name: 'فنلندا', flag: '🇫🇮' },
99
  'GR': { name: 'اليونان', flag: '🇬🇷' },
100
- 'CZ': { name: 'التشيك', flag: '🇨🇿' },
101
- 'HU': { name: 'المجر', flag: '🇭🇺' },
102
- 'RO': { name: 'رومانيا', flag: '🇷🇴' },
103
- 'UA': { name: 'أوكرانيا', flag: '🇺🇦' },
104
  'IE': { name: 'أيرلندا', flag: '🇮🇪' },
105
-
106
- // أمريكا الجنوبية والكاريبي
107
- 'VE': { name: 'فنزويلا', flag: '🇻🇪' },
108
- 'EC': { name: 'الإكوادور', flag: '🇪🇨' },
109
- 'UY': { name: 'الأوروغواي', flag: '🇺🇾' },
110
- 'PA': { name: 'بنما', flag: '🇵🇦' },
111
- 'CR': { name: 'كوستاريكا', flag: '🇨🇷' },
112
- 'CU': { name: 'كوبا', flag: '🇨🇺' },
113
- 'DO': { name: 'الدومينيكان', flag: '🇩🇴' },
114
- 'PR': { name: 'بورتوريكو', flag: '🇵🇷' },
115
- 'JM': { name: 'جامايكا', flag: '🇯🇲' },
116
- 'TT': { name: 'ترinidad Tobago', flag: '🇹🇹' },
117
-
118
- // دول أخرى
119
  'IL': { name: 'إسرائيل', flag: '🇮🇱' },
120
  'PS': { name: 'فلسطين', flag: '🇵🇸' },
121
- 'RS': { name: 'صربيا', flag: '🇷🇸' },
122
- 'HR': { name: 'كرواتيا', flag: '🇭🇷' },
123
- 'BG': { name: 'بلغاريا', flag: '🇧🇬' },
124
- 'AL': { name: 'ألبانيا', flag: '🇦🇱' },
125
- 'MK': { name: 'مقدونيا', flag: '🇲🇰' },
126
- 'ME': { name: 'الجبل الأسود', flag: '🇲🇪' },
127
- 'BA': { name: 'البوسنة والهرسك', flag: '🇧🇦' },
128
- 'SK': { name: 'سلوفاكيا', flag: '🇸🇰' },
129
- 'SI': { name: 'سلوفينيا', flag: '🇸🇮' },
130
- 'LT': { name: 'ليتوانيا', flag: '🇱🇹' },
131
- 'LV': { name: 'لاتفيا', flag: '🇱🇻' },
132
- 'EE': { name: 'إستونيا', flag: '🇪🇪' },
133
- 'UZ': { name: 'أوزبكستان', flag: '🇺🇿' },
134
- 'KZ': { name: 'كازاخستان', flag: '���🇿' },
135
- 'AZ': { name: 'أذربيجان', flag: '🇦🇿' },
136
- 'GE': { name: 'جورجيا', flag: '🇬🇪' },
137
- 'AM': { name: 'أرمينيا', flag: '🇦🇲' },
138
- 'KG': { name: 'قرغيزستان', flag: '🇰🇬' },
139
- 'TJ': { name: 'طاجيكستان', flag: '🇹🇯' },
140
- 'TM': { name: 'تركمانستان', flag: '🇹🇲' },
141
- 'MN': { name: 'منغوليا', flag: '🇲🇳' },
142
- 'LA': { name: 'لاوس', flag: '🇱🇦' },
143
- 'KH': { name: 'كمبوديا', flag: '🇰🇭' },
144
- 'BN': { name: 'بروناي', flag: '🇧🇳' },
145
  };
146
 
147
- // --- دالة الحصول على معلومات الدولة ---
148
  function getCountryInfo(code) {
149
  if (!code) return { name: 'غير محدد', flag: '🌍' };
150
  const upperCode = code.toUpperCase();
151
  return COUNTRY_FLAGS[upperCode] || { name: code, flag: '🌍' };
152
  }
153
 
154
- // --- تنسيق الرقم ---
155
  function formatK(num) {
156
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
157
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
158
  return num.toString();
159
  }
160
 
161
- // --- الوقت بتوقيت بغداد ---
162
  function getBaghdadTime() {
163
  return new Intl.DateTimeFormat('ar-IQ', {
164
  timeZone: 'Asia/Baghdad',
@@ -169,7 +106,6 @@ function getBaghdadTime() {
169
  }).format(new Date());
170
  }
171
 
172
- // --- شريط التقدم ---
173
  function generateProgressBar(ourScore, theirScore, length = 10) {
174
  const total = ourScore + theirScore;
175
  if (total === 0) return "⬜".repeat(length);
@@ -177,199 +113,119 @@ function generateProgressBar(ourScore, theirScore, length = 10) {
177
  return "🟦".repeat(ourPercent) + "🟥".repeat(length - ourPercent);
178
  }
179
 
180
- // --- دالة HTTP GET باستخدام native http/https ---
181
  function httpGet(url, headers = {}, timeout = 15000) {
182
  return new Promise((resolve, reject) => {
183
  const urlObj = new URL(url);
184
  const protocol = urlObj.protocol === 'https:' ? https : http;
185
-
186
  const options = {
187
  hostname: urlObj.hostname,
188
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
189
  path: urlObj.pathname + urlObj.search,
190
  method: 'GET',
191
  headers: {
192
- 'User-Agent': 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36',
193
- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
194
  'Accept-Language': 'en-US,en;q=0.9',
195
  ...headers
196
  },
197
  timeout: timeout
198
  };
199
-
200
  const req = protocol.request(options, (res) => {
201
  let data = '';
202
  res.on('data', chunk => data += chunk);
203
  res.on('end', () => resolve({ statusCode: res.statusCode, data }));
204
  });
205
-
206
  req.on('error', reject);
207
- req.on('timeout', () => {
208
- req.destroy();
209
- reject(new Error('Request timeout'));
210
- });
211
-
212
  req.end();
213
  });
214
  }
215
 
216
- // --- دالة HTTP POST باستخدام native http/https ---
217
- function httpPost(url, payload, headers = {}, timeout = 15000) {
218
  return new Promise((resolve, reject) => {
219
  const urlObj = new URL(url);
220
  const protocol = urlObj.protocol === 'https:' ? https : http;
221
  const data = JSON.stringify(payload);
222
-
223
  const options = {
224
  hostname: urlObj.hostname,
225
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
226
  path: urlObj.pathname + urlObj.search,
227
  method: 'POST',
228
- headers: {
229
- 'Content-Type': 'application/json',
230
- 'Content-Length': Buffer.byteLength(data),
231
- ...headers
232
- },
233
  timeout: timeout
234
  };
235
-
236
  const req = protocol.request(options, (res) => {
237
  let responseData = '';
238
  res.on('data', chunk => responseData += chunk);
239
  res.on('end', () => resolve({ statusCode: res.statusCode, data: responseData }));
240
  });
241
-
242
  req.on('error', reject);
243
- req.on('timeout', () => {
244
- req.destroy();
245
- reject(new Error('Request timeout'));
246
- });
247
-
248
  req.write(data);
249
  req.end();
250
  });
251
  }
252
 
253
- // --- الحصول على بيانات المستخدم مع البلد ---
254
  async function getUserDataWithRegion(username) {
255
- const url = `https://www.tiktok.com/@${username}`;
256
-
257
  try {
258
- const response = await httpGet(url);
259
  if (response.statusCode === 200) {
260
  const $ = cheerio.load(response.data);
261
  const scripts = $('script').map((i, el) => $(el).html()).get();
262
-
263
  for (const script of scripts) {
264
  if (script && script.includes('webapp.user-detail')) {
265
  const match = script.match(/window\['__DEFAULT_SCOPE__'\]\s*=\s*({.*?});/s);
266
  if (match) {
267
- try {
268
- const data = JSON.parse(match[1]);
269
- const userInfo = data?.['__DEFAULT_SCOPE__']?.['webapp.user-detail']?.['userInfo'] || {};
270
- const user = userInfo['user'] || {};
271
-
272
- return {
273
- region: user['region'] || null,
274
- nickname: user['nickname'] || username,
275
- followers: userInfo['stats']?.['followerCount'] || 0,
276
- verified: user['verified'] || false
277
- };
278
- } catch (e) {
279
- console.log("⚠️ خطأ في تحليل JSON:", e.message);
280
- }
281
  }
282
  }
283
  }
284
  }
285
- } catch (e) {
286
- console.log("⚠️ خطأ في جلب بيانات المستخدم:", e.message);
287
- }
288
  return null;
289
  }
290
 
291
- // --- المتغيرات العامة ---
292
- let highestHundred = 0;
293
- let maxViewers = 0;
294
- let totalLikes = 0;
295
- let totalShares = 0;
296
- let giftersMap = {};
297
- let startTime = null;
298
- let streamerRegion = null;
299
-
300
- // --- PK System ---
301
- let pkActive = false;
302
- let pkInfo = {
303
- opponentName: "",
304
- ourLikes: 0,
305
- theirLikes: 0,
306
- ourTopGifter: { name: "لا أحد", coins: 0 }
307
- };
308
 
309
- // --- إرسال رسالة تيليجرام ---
310
  async function sendToTelegram(text, photoUrl = null, buttons = null) {
311
  try {
312
- const baseUrl = `${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}`;
313
-
314
- const payload = {
315
- chat_id: TELEGRAM_CHAT_ID,
316
- parse_mode: 'HTML',
317
- disable_web_page_preview: true
318
- };
319
-
320
  if (buttons) payload.reply_markup = JSON.stringify({ inline_keyboard: buttons });
321
-
322
- if (photoUrl) {
323
- payload.photo = photoUrl;
324
- payload.caption = text;
325
- await httpPost(`${baseUrl}/sendPhoto`, payload);
326
- } else {
327
- payload.text = text;
328
- await httpPost(`${baseUrl}/sendMessage`, payload);
329
- }
330
- } catch (e) {
331
- console.log("⚠️ فشل الإرسال عبر الجسر:", e.message);
332
- }
333
  }
334
 
335
- // --- أفضل الداعمين ---
336
- function getTopGifters(map, top = 5) {
337
- return Object.values(map).sort((a, b) => b.coins - a.coins).slice(0, top);
338
- }
339
 
340
- // --- إعداد اتصال تيك توك ---
341
  let tiktokConnection = new WebcastPushConnection(TIKTOK_USERNAME, {
342
- processInitialData: true,
343
- enableWebsocketUpgrade: true,
344
- sessionId: SESSION_ID,
345
  clientParams: { app_language: "ar-IQ", device_platform: "web" }
346
  });
347
 
348
- // --- بدء الرادار ---
349
  async function startRadar() {
350
  console.log(`⏳ جاري البحث: ${TIKTOK_USERNAME}...`);
351
-
352
- // جلب بلد المُستضيف
353
  const userData = await getUserDataWithRegion(TIKTOK_USERNAME);
354
- streamerRegion = userData?.region;
355
- const countryInfo = getCountryInfo(streamerRegion);
356
-
357
  tiktokConnection.connect().then(state => {
358
- maxViewers = 0; totalLikes = 0; totalShares = 0; giftersMap = {};
359
- pkActive = false;
360
  const liveLink = `https://www.tiktok.com/@${TIKTOK_USERNAME}/live`;
361
- const userImage = state.roomInfo?.owner?.avatar_large?.url_list?.[0] || "";
362
- const nickname = userData?.nickname || TIKTOK_USERNAME;
363
- const verifiedBadge = userData?.verified ? ' ✅' : '';
364
-
365
- // رسالة الإشعارات الفاخرة مع البلد
366
  const msg = `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
367
 
368
  🎬 <b>صـآ🎬ر الـبثّ ༒️!</b>
369
 
370
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
371
 
372
- 👤 <b>${nickname}${verifiedBadge}</b>
373
  🔗 @${TIKTOK_USERNAME}
374
 
375
  ${countryInfo.flag} <b>البلد:</b> ${countryInfo.name}
@@ -378,185 +234,49 @@ ${countryInfo.flag} <b>البلد:</b> ${countryInfo.name}
378
 
379
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
380
 
381
- 🌟 <i>انضم الآن وكن أول الحاضرين!</i>
382
-
383
- ✨ <i>ادعم البث بكل طاقتك</i> ✨`;
384
-
385
- const buttons = [[{ text: "📺 دخول البث المباشر", url: liveLink }]];
386
- sendToTelegram(msg, userImage, buttons);
387
- console.log(`✅ متصل بنجاح! البلد: ${countryInfo.name} ${countryInfo.flag}`);
388
- }).catch(err => {
389
- console.log(`🔎 مغلق: ${err.message}`);
390
- setTimeout(startRadar, 60000);
391
- });
392
  }
393
 
394
- // --- أحداث البث ---
395
-
396
- // المشاهدين
397
- tiktokConnection.on('roomUser', (data) => {
398
- const viewers = data.viewerCount || 0;
399
- if (viewers > maxViewers) maxViewers = viewers;
400
- });
401
-
402
- // الإعجابات
403
- tiktokConnection.on('like', (data) => {
404
- totalLikes += data?.likeCount || 0;
405
- if (pkActive) pkInfo.ourLikes += data?.likeCount || 0;
406
- });
407
-
408
- // المشاركات
409
  tiktokConnection.on('share', () => totalShares++);
410
 
411
- // الهدايا مع البلد
412
- tiktokConnection.on('gift', (data) => {
413
  if (data.giftType === 1 && !data.repeatEnd) return;
414
-
415
  const giftCost = (data.diamondCount || 0) * (data.repeatCount || 1);
416
- if (!giftersMap[data.userId]) {
417
- giftersMap[data.userId] = {
418
- name: data.nickname,
419
- coins: 0,
420
- region: data.country || null
421
- };
422
- }
423
  giftersMap[data.userId].coins += giftCost;
424
-
425
- // إشعار فوري للهدية الكبيرة
426
  if (giftCost >= 100) {
427
- const gifterCountry = getCountryInfo(giftersMap[data.userId].region);
428
- const giftMsg = `🎁 <b>هدية جديدة!</b>
429
-
430
- ${gifterCountry.flag} <b>${data.nickname}</b>
431
- 💰 <b>${formatK(giftCost)}</b> 🪙
432
- 🌍 <b>البلد:</b> ${gifterCountry.name}
433
-
434
- 🎁 <b>${data.giftName || 'هدية'}</b> x${data.repeatCount || 1}`;
435
- sendToTelegram(giftMsg);
436
  }
437
  });
438
 
439
- // --- PK System ---
440
- tiktokConnection.on('pkStart', (data) => {
441
- pkActive = true;
442
- pkInfo = { opponentName: data.opponentNickname, ourLikes: 0, theirLikes: 0 };
443
- const liveLink = `https://www.tiktok.com/@${TIKTOK_USERNAME}/live`;
444
-
445
- const msg = `🔥 <b>جولة PK جديدة!</b>
446
-
447
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
448
-
449
- 🥊 <b>المنافس:</b> ${data.opponentNickname}
450
-
451
- 🌟 <i>الآن يحتاج الجميع للتحلي بالروح الرياضية!</i>
452
-
453
- 🚀 <i>شدوا الحيل وادعموا!</i>`;
454
-
455
- sendToTelegram(msg, null, [[{ text: "🚀 دعم البث الآن", url: liveLink }]]);
456
  });
 
457
 
458
- tiktokConnection.on('pkUpdate', (data) => {
459
- pkInfo.ourLikes = data.ourLikes || 0;
460
- pkInfo.theirLikes = data.theirLikes || 0;
461
- });
462
-
463
- tiktokConnection.on('pkEnd', (data) => {
464
  pkActive = false;
465
- const winner = data.winnerNickname || "تعادل";
466
  const bar = generateProgressBar(pkInfo.ourLikes, pkInfo.theirLikes);
467
-
468
- const msg = `🏆 <b>انتهت المواجهة!</b>
469
-
470
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
471
-
472
- 🥇 <b>الفائز:</b> ${winner}
473
-
474
- 📊 <b>النتيجة البصرية:</b>
475
- 🟦 نحن: ${formatK(pkInfo.ourLikes)} | ${formatK(pkInfo.theirLikes)} :المنافس 🟥
476
-
477
- ${bar}
478
-
479
- ✨ <i>شكراً لكل من ساهم في هذه الجولة!</i>`;
480
-
481
- sendToTelegram(msg);
482
  });
483
 
484
- // --- التقرير النهائي الفاخر ---
485
  tiktokConnection.on('streamEnd', () => {
486
- const topGifters = getTopGifters(giftersMap, 5);
487
  const medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
488
-
489
- let topGifterText = topGifters.map((g, i) => {
490
- const gifterCountry = getCountryInfo(g.region);
491
- return `${medals[i]} <b>${g.name}</b> ${gifterCountry.flag}
492
- 💰 <code>${formatK(g.coins)}</code> 🪙 | ${gifterCountry.name}`;
493
- }).join("\n") || "\n> لا يوجد داعمين في هذا البث";
494
-
495
- // إحصائيات البلد
496
  const countryStats = {};
497
- Object.values(giftersMap).forEach(gifter => {
498
- const reg = gifter.region || 'XX';
499
- if (!countryStats[reg]) countryStats[reg] = 0;
500
- countryStats[reg] += gifter.coins;
501
- });
502
-
503
- let countryRanking = '';
504
- const sortedCountries = Object.entries(countryStats)
505
- .sort((a, b) => b[1] - a[1])
506
- .slice(0, 3);
507
-
508
- if (sortedCountries.length > 0) {
509
- const crownEmojis = ['👑', '🥈', '🥉'];
510
- countryRanking = sortedCountries.map(([reg, coins], i) => {
511
- const ci = getCountryInfo(reg);
512
- return `${crownEmojis[i] || '🌍'} <b>${ci.name}</b> ${ci.flag}: ${formatK(coins)} 🪙`;
513
- }).join("\n");
514
- }
515
-
516
- const summaryMsg = `📊 <b>التقرير النهائي للبث</b>
517
-
518
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
519
-
520
- 📈 <b>أعلى مشاهدات:</b> ${formatK(maxViewers)}
521
- ❤️ <b>إجمالي الإعجابات:</b> ${formatK(totalLikes)}
522
- ↪️ <b>إجمالي المشاركات:</b> ${formatK(totalShares)}
523
- 🎁 <b>إجمالي الهدايا:</b> ${formatK(Object.values(giftersMap).reduce((a, g) => a + g.coins, 0))} 🪙
524
-
525
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
526
-
527
- 🏆 <b>لـوحـة الـشـرف (الداعمين):</b>
528
- ${topGifterText}
529
-
530
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
531
-
532
- 🌍 <b>توزيع الهدايا حسب البلد:</b>
533
- ${countryRanking || '> لا توجد بيانات'}
534
-
535
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
536
-
537
- 💤 <i>الرادار في وضع الانتظار...</i>
538
-
539
- 🔄 <i>سيتم إعادة الاتصال تلقائياً</i>`;
540
-
541
- sendToTelegram(summaryMsg);
542
  setTimeout(startRadar, 60000);
543
  });
544
 
545
- // --- Server & Self-Ping ---
546
- const server = http.createServer((req, res) => {
547
- res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
548
- res.end('رادار تيك توك الاحترافي الفاخر يعمل! 🚀✨');
549
- });
550
-
551
- server.listen(7860, '0.0.0.0', () => {
552
- console.log("✅ خادم النبض نشط");
553
-
554
- // نظام نبض داخلي
555
- setInterval(() => {
556
- http.get('http://localhost:7860', (res) => {
557
- res.resume();
558
- }).on('error', () => {});
559
- }, 120000);
560
-
561
- startRadar();
562
- });
 
10
  const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
11
  const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
12
  const SESSION_ID = process.env.SESSION_ID;
 
 
13
  const MY_PROXY_URL = "https://tg-proxy.dr-toktok00.workers.dev";
14
 
15
  dns.setServers(['8.8.8.8']);
16
 
17
  // --- قاموس الدول بالأعلام ---
18
  const COUNTRY_FLAGS = {
 
19
  'SA': { name: 'المملكة العربية السعودية', flag: '🇸🇦' },
20
  'EG': { name: 'مصر', flag: '🇪🇬' },
21
  'AE': { name: 'الإمارات العربية المتحدة', flag: '🇦🇪' },
 
36
  'SO': { name: 'الصومال', flag: '🇸🇴' },
37
  'DJ': { name: 'جيبوتي', flag: '🇩🇯' },
38
  'MR': { name: 'موريتانيا', flag: '🇲🇷' },
39
+ 'US': { name: 'الولايات المتحدة', flag: '🇺🇸' },
 
 
40
  'GB': { name: 'المملكة المتحدة', flag: '🇬🇧' },
41
  'TR': { name: 'تركيا', flag: '🇹🇷' },
42
  'FR': { name: 'فرنسا', flag: '🇫🇷' },
 
44
  'IT': { name: 'إيطاليا', flag: '🇮🇹' },
45
  'ES': { name: 'إسبانيا', flag: '🇪🇸' },
46
  'BR': { name: 'البرازيل', flag: '🇧🇷' },
 
47
  'RU': { name: 'روسيا', flag: '🇷🇺' },
48
  'CN': { name: 'الصين', flag: '🇨🇳' },
49
  'JP': { name: 'اليابان', flag: '🇯🇵' },
 
58
  'PK': { name: 'باكستان', flag: '🇵🇰' },
59
  'BD': { name: 'بنغلاديش', flag: '🇧🇩' },
60
  'IR': { name: 'إيران', flag: '🇮🇷' },
 
61
  'AR': { name: 'الأرجنتين', flag: '🇦🇷' },
62
  'MX': { name: 'المكسيك', flag: '🇲🇽' },
63
  'CO': { name: 'كولومبيا', flag: '🇨🇴' },
 
68
  'NZ': { name: 'نيوزيلندا', flag: '🇳🇿' },
69
  'ZA': { name: 'جنوب أفريقيا', flag: '🇿🇦' },
70
  'NG': { name: 'نيجيريا', flag: '🇳🇬' },
 
 
 
 
 
 
 
 
 
 
 
 
71
  'NL': { name: 'هولندا', flag: '🇳🇱' },
72
  'BE': { name: 'بلجيكا', flag: '🇧🇪' },
73
  'CH': { name: 'سويسرا', flag: '🇨🇭' },
 
78
  'DK': { name: 'الدنمارك', flag: '🇩🇰' },
79
  'FI': { name: 'فنلندا', flag: '🇫🇮' },
80
  'GR': { name: 'اليونان', flag: '🇬🇷' },
81
+ 'PT': { name: 'البرتغال', flag: '🇵🇹' },
 
 
 
82
  'IE': { name: 'أيرلندا', flag: '🇮🇪' },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  'IL': { name: 'إسرائيل', flag: '🇮🇱' },
84
  'PS': { name: 'فلسطين', flag: '🇵🇸' },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  };
86
 
 
87
  function getCountryInfo(code) {
88
  if (!code) return { name: 'غير محدد', flag: '🌍' };
89
  const upperCode = code.toUpperCase();
90
  return COUNTRY_FLAGS[upperCode] || { name: code, flag: '🌍' };
91
  }
92
 
 
93
  function formatK(num) {
94
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
95
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
96
  return num.toString();
97
  }
98
 
 
99
  function getBaghdadTime() {
100
  return new Intl.DateTimeFormat('ar-IQ', {
101
  timeZone: 'Asia/Baghdad',
 
106
  }).format(new Date());
107
  }
108
 
 
109
  function generateProgressBar(ourScore, theirScore, length = 10) {
110
  const total = ourScore + theirScore;
111
  if (total === 0) return "⬜".repeat(length);
 
113
  return "🟦".repeat(ourPercent) + "🟥".repeat(length - ourPercent);
114
  }
115
 
 
116
  function httpGet(url, headers = {}, timeout = 15000) {
117
  return new Promise((resolve, reject) => {
118
  const urlObj = new URL(url);
119
  const protocol = urlObj.protocol === 'https:' ? https : http;
 
120
  const options = {
121
  hostname: urlObj.hostname,
122
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
123
  path: urlObj.pathname + urlObj.search,
124
  method: 'GET',
125
  headers: {
126
+ 'User-Agent': 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 Chrome/112.0.0.0 Safari/537.36',
127
+ 'Accept': 'text/html,application/xhtml+xml',
128
  'Accept-Language': 'en-US,en;q=0.9',
129
  ...headers
130
  },
131
  timeout: timeout
132
  };
 
133
  const req = protocol.request(options, (res) => {
134
  let data = '';
135
  res.on('data', chunk => data += chunk);
136
  res.on('end', () => resolve({ statusCode: res.statusCode, data }));
137
  });
 
138
  req.on('error', reject);
139
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
 
 
 
 
140
  req.end();
141
  });
142
  }
143
 
144
+ function httpPost(url, payload, timeout = 15000) {
 
145
  return new Promise((resolve, reject) => {
146
  const urlObj = new URL(url);
147
  const protocol = urlObj.protocol === 'https:' ? https : http;
148
  const data = JSON.stringify(payload);
 
149
  const options = {
150
  hostname: urlObj.hostname,
151
  port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
152
  path: urlObj.pathname + urlObj.search,
153
  method: 'POST',
154
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) },
 
 
 
 
155
  timeout: timeout
156
  };
 
157
  const req = protocol.request(options, (res) => {
158
  let responseData = '';
159
  res.on('data', chunk => responseData += chunk);
160
  res.on('end', () => resolve({ statusCode: res.statusCode, data: responseData }));
161
  });
 
162
  req.on('error', reject);
163
+ req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
 
 
 
 
164
  req.write(data);
165
  req.end();
166
  });
167
  }
168
 
 
169
  async function getUserDataWithRegion(username) {
 
 
170
  try {
171
+ const response = await httpGet(`https://www.tiktok.com/@${username}`);
172
  if (response.statusCode === 200) {
173
  const $ = cheerio.load(response.data);
174
  const scripts = $('script').map((i, el) => $(el).html()).get();
 
175
  for (const script of scripts) {
176
  if (script && script.includes('webapp.user-detail')) {
177
  const match = script.match(/window\['__DEFAULT_SCOPE__'\]\s*=\s*({.*?});/s);
178
  if (match) {
179
+ const data = JSON.parse(match[1]);
180
+ const userInfo = data?.['__DEFAULT_SCOPE__']?.['webapp.user-detail']?.['userInfo'] || {};
181
+ const user = userInfo['user'] || {};
182
+ return {
183
+ region: user['region'] || null,
184
+ nickname: user['nickname'] || username,
185
+ verified: user['verified'] || false
186
+ };
 
 
 
 
 
 
187
  }
188
  }
189
  }
190
  }
191
+ } catch (e) { console.log("⚠️ خطأ:", e.message); }
 
 
192
  return null;
193
  }
194
 
195
+ let maxViewers = 0, totalLikes = 0, totalShares = 0, giftersMap = {};
196
+ let pkActive = false, pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
 
198
  async function sendToTelegram(text, photoUrl = null, buttons = null) {
199
  try {
200
+ const payload = { chat_id: TELEGRAM_CHAT_ID, parse_mode: 'HTML', disable_web_page_preview: true };
 
 
 
 
 
 
 
201
  if (buttons) payload.reply_markup = JSON.stringify({ inline_keyboard: buttons });
202
+ if (photoUrl) { payload.photo = photoUrl; payload.caption = text; await httpPost(`${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}/sendPhoto`, payload); }
203
+ else { payload.text = text; await httpPost(`${MY_PROXY_URL}/bot${TELEGRAM_TOKEN}/sendMessage`, payload); }
204
+ } catch (e) { console.log("⚠️ فشل الإرسال:", e.message); }
 
 
 
 
 
 
 
 
 
205
  }
206
 
207
+ function getTopGifters(map, top = 5) { return Object.values(map).sort((a, b) => b.coins - a.coins).slice(0, top); }
 
 
 
208
 
 
209
  let tiktokConnection = new WebcastPushConnection(TIKTOK_USERNAME, {
210
+ processInitialData: true, enableWebsocketUpgrade: true, sessionId: SESSION_ID,
 
 
211
  clientParams: { app_language: "ar-IQ", device_platform: "web" }
212
  });
213
 
 
214
  async function startRadar() {
215
  console.log(`⏳ جاري البحث: ${TIKTOK_USERNAME}...`);
 
 
216
  const userData = await getUserDataWithRegion(TIKTOK_USERNAME);
217
+ const countryInfo = getCountryInfo(userData?.region);
218
+
 
219
  tiktokConnection.connect().then(state => {
220
+ maxViewers = 0; totalLikes = 0; totalShares = 0; giftersMap = {}; pkActive = false;
 
221
  const liveLink = `https://www.tiktok.com/@${TIKTOK_USERNAME}/live`;
 
 
 
 
 
222
  const msg = `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
223
 
224
  🎬 <b>صـآ🎬ر الـبثّ ༒️!</b>
225
 
226
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
227
 
228
+ 👤 <b>${userData?.nickname || TIKTOK_USERNAME}${userData?.verified ? ' ✅' : ''}</b>
229
  🔗 @${TIKTOK_USERNAME}
230
 
231
  ${countryInfo.flag} <b>البلد:</b> ${countryInfo.name}
 
234
 
235
  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
236
 
237
+ 🌟 <i>انضم الآن وكن أول الحاضرين!</i>`;
238
+ sendToTelegram(msg, state.roomInfo?.owner?.avatar_large?.url_list?.[0] || "", [[{ text: "📺 دخول البث المباشر", url: liveLink }]]);
239
+ console.log(`✅ متصل! البلد: ${countryInfo.name}`);
240
+ }).catch(err => { console.log(`🔎 مغلق: ${err.message}`); setTimeout(startRadar, 60000); });
 
 
 
 
 
 
 
241
  }
242
 
243
+ tiktokConnection.on('roomUser', data => { if (data.viewerCount > maxViewers) maxViewers = data.viewerCount; });
244
+ tiktokConnection.on('like', data => { totalLikes += data?.likeCount || 0; if (pkActive) pkInfo.ourLikes += data?.likeCount || 0; });
 
 
 
 
 
 
 
 
 
 
 
 
 
245
  tiktokConnection.on('share', () => totalShares++);
246
 
247
+ tiktokConnection.on('gift', data => {
 
248
  if (data.giftType === 1 && !data.repeatEnd) return;
 
249
  const giftCost = (data.diamondCount || 0) * (data.repeatCount || 1);
250
+ if (!giftersMap[data.userId]) giftersMap[data.userId] = { name: data.nickname, coins: 0, region: data.country || null };
 
 
 
 
 
 
251
  giftersMap[data.userId].coins += giftCost;
 
 
252
  if (giftCost >= 100) {
253
+ const gc = getCountryInfo(giftersMap[data.userId].region);
254
+ sendToTelegram(`🎁 <b>هدية جديدة!</b>\n\n${gc.flag} <b>${data.nickname}</b>\n💰 <b>${formatK(giftCost)}</b> 🪙\n🌍 ${gc.name}`);
 
 
 
 
 
 
 
255
  }
256
  });
257
 
258
+ tiktokConnection.on('pkStart', data => {
259
+ pkActive = true; pkInfo = { opponentName: data.opponentNickname, ourLikes: 0, theirLikes: 0 };
260
+ sendToTelegram(`🔥 <b>جولة PK!</b>\n\n🥊 المنافس: ${data.opponentNickname}\n\nشدوا الحيل!`, null, [[{ text: "🚀 دعم البث", url: `https://www.tiktok.com/@${TIKTOK_USERNAME}/live` }]]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  });
262
+ tiktokConnection.on('pkUpdate', data => { pkInfo.ourLikes = data.ourLikes || 0; pkInfo.theirLikes = data.theirLikes || 0; });
263
 
264
+ tiktokConnection.on('pkEnd', data => {
 
 
 
 
 
265
  pkActive = false;
 
266
  const bar = generateProgressBar(pkInfo.ourLikes, pkInfo.theirLikes);
267
+ sendToTelegram(`🏆 <b>انتهت المواجهة!</b>\n\n🥇 الفائز: ${data.winnerNickname || 'تعادل'}\n\n📊 النتيجة:\n🟦 نحن: ${formatK(pkInfo.ourLikes)} | ${formatK(pkInfo.theirLikes)} :المنافس 🟥\n\n${bar}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
  });
269
 
 
270
  tiktokConnection.on('streamEnd', () => {
271
+ const top = getTopGifters(giftersMap, 5);
272
  const medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
273
+ let topText = top.map((g, i) => `${medals[i]} ${getCountryInfo(g.region).flag} <b>${g.name}</b>: ${formatK(g.coins)} 🪙`).join("\n") || "> لا داعمين";
 
 
 
 
 
 
 
274
  const countryStats = {};
275
+ Object.values(giftersMap).forEach(g => { const r = g.region || 'XX'; countryStats[r] = (countryStats[r] || 0) + g.coins; });
276
+ let countryRanking = Object.entries(countryStats).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([r, c], i) => `${['👑', '🥈', '🥉'][i]} ${getCountryInfo(r).flag} ${getCountryInfo(r).name}: ${formatK(c)} 🪙`).join("\n") || '> لا بيانات';
277
+ sendToTelegram(`📊 <b>التقرير النهائي</b>\n\n━━━━━━━━━━━━━━━━\n📈 أعلى مشاهدات: ${formatK(maxViewers)}\n❤️ إعجابات: ${formatK(totalLikes)}\n↪️ مشاركات: ${formatK(totalShares)}\n\n🏆 <b>الداعمين:</b>\n${topText}\n\n🌍 <b>توزيع حسب البلد:</b>\n${countryRanking}\n\n💤 انتظار...`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  setTimeout(startRadar, 60000);
279
  });
280
 
281
+ const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('OK'); });
282
+ server.listen(7860, '0.0.0.0', () => { console.log("✅ جاهز"); setInterval(() => { http.get('http://localhost:7860', r => r.resume()).on('error', () => {}); }, 120000); startRadar(); });