Reooiq commited on
Commit
bdb3db0
·
verified ·
1 Parent(s): 24d1fd2

Update bot.js

Browse files
Files changed (1) hide show
  1. bot.js +73 -1114
bot.js CHANGED
@@ -1,7 +1,7 @@
1
  /**
2
  * ╔══════════════════════════════════════════════════════════════════════╗
3
- * ║ TikTok Radar Pro - Telegram Bot v6.3 (v2.0+ Fixed) ║
4
- * ║ Based on tiktok-live-connector v2.0+ API ║
5
  * ╚══════════════════════════════════════════════════════════════════════╝
6
  */
7
 
@@ -9,10 +9,7 @@ const { TikTokLiveConnection, WebcastEvent, ControlEvent } = require('tiktok-liv
9
  const axios = require('axios');
10
  const http = require('http');
11
 
12
- // ═══════════════════════════════════════════════════════════════════════
13
- // CONFIGURATION
14
- // ═══════════════════════════════════════════════════════════════════════
15
-
16
  function cleanEnv(val, fallback) {
17
  if (!val) return fallback;
18
  return val.toString().trim().split('\n')[0].trim();
@@ -33,19 +30,7 @@ const CONFIG = {
33
  SPAM_KEYWORDS: ['spam', 'scam', 'fake', 'click here', 'free money', 'earn now', 'www.', '.com'],
34
  };
35
 
36
- // ═══════════════════════════════════════════════════════════════════════
37
- // ACTIVITY TRACKER (تعريف مبكر لتجنب ReferenceError)
38
- // ═══════════════════════════════════════════════════════════════════════
39
-
40
- let lastActivity = Date.now();
41
- function updateActivity() {
42
- lastActivity = Date.now();
43
- }
44
-
45
- // ═══════════════════════════════════════════════════════════════════════
46
- // STATE VARIABLES
47
- // ═══════════════════════════════════════════════════════════════════════
48
-
49
  let isConnected = false;
50
  let isLive = false;
51
  let maxViewers = 0;
@@ -73,6 +58,7 @@ let reportInterval = null;
73
  let lastMessageId = null;
74
  let reconnectAttempt = 0;
75
  let lastReconnectNotify = 0;
 
76
 
77
  const cooldowns = {
78
  chat: new Map(), gift: new Map(), like: new Map(), follow: new Map(),
@@ -80,56 +66,25 @@ const cooldowns = {
80
  };
81
 
82
  let pkActive = false;
83
- let pkInfo = {
84
- opponentName: '', opponentUserId: '', ourScore: 0, theirScore: 0,
85
- startTime: null, pkGifts: {},
86
- };
87
-
88
  let viewerHistory = [];
89
 
90
- // ═══════════════════════════════════════════════════════════════════════
91
- // UTILITY FUNCTIONS
92
- // ═══════════════════════════════════════════════════════════════════════
93
-
94
- function formatK(num) {
95
- if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
96
- if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
97
- return num.toString();
98
  }
99
-
100
- function getBaghdadTime() {
101
- return new Intl.DateTimeFormat('ar-IQ', {
102
- timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true,
103
- }).format(new Date());
104
  }
105
-
106
- function getDateString() {
107
- return new Intl.DateTimeFormat('ar-IQ', {
108
- timeZone: 'Asia/Baghdad', year: 'numeric', month: '2-digit', day: '2-digit',
109
- }).format(new Date());
110
- }
111
-
112
- function formatDuration(startDate) {
113
- if (!startDate) return '00:00:00';
114
- const diff = Math.floor((Date.now() - startDate.getTime()) / 1000);
115
- const h = Math.floor(diff / 3600);
116
- const m = Math.floor((diff % 3600) / 60);
117
- const s = diff % 60;
118
- return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
119
- }
120
-
121
- function generateProgressBar(ourScore, theirScore, length = 10) {
122
- const total = ourScore + theirScore;
123
- if (total === 0) return '⬜'.repeat(length);
124
- const ourPercent = Math.min(Math.max(Math.round((ourScore / total) * length), 0), length);
125
- return '🟦'.repeat(ourPercent) + '🟥'.repeat(length - ourPercent);
126
- }
127
-
128
  function escapeHtml(text) {
129
  if (!text) return '';
130
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
131
  }
132
 
 
133
  function isOnCooldown(type, key, duration) {
134
  const now = Date.now();
135
  const last = cooldowns[type].get(key);
@@ -138,1089 +93,93 @@ function isOnCooldown(type, key, duration) {
138
  return false;
139
  }
140
 
141
- function isSpamMessage(text) {
142
- if (!text) return true;
143
- const lower = text.toLowerCase();
144
- return CONFIG.SPAM_KEYWORDS.some(kw => lower.includes(kw.toLowerCase()));
145
- }
146
-
147
- function cleanChatMessage(text) {
148
- if (!text) return '';
149
- let cleaned = text.replace(/https?:\/\/\S+/gi, '[رابط]');
150
- cleaned = cleaned.replace(/(.)(?=\1{5,})/g, '');
151
- if (cleaned.length > 120) cleaned = cleaned.substring(0, 120) + '...';
152
- return cleaned.trim();
153
- }
154
-
155
- // ═══════════════════════════════════════════════════════════════════════
156
- // TELEGRAM API
157
- // ═══════════════════════════════════════════════════════════════════════
158
-
159
  async function sendTelegram(text, photoUrl = null, buttons = null, parseMode = 'HTML', editMessageId = null, silent = false) {
160
  updateActivity();
161
- if (!CONFIG.TELEGRAM_TOKEN || !CONFIG.TELEGRAM_CHAT_ID) {
162
- console.error('[Telegram] Missing token or chat ID');
163
- return null;
164
- }
165
- const urls = [];
166
- let proxyUrl = CONFIG.PROXY_URL;
167
- if (proxyUrl && proxyUrl.startsWith('http')) urls.push(`${proxyUrl}/bot${CONFIG.TELEGRAM_TOKEN}`);
168
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
169
-
170
- for (const baseUrl of urls) {
171
- try {
172
- let payload = {
173
- chat_id: CONFIG.TELEGRAM_CHAT_ID,
174
- parse_mode: parseMode,
175
- disable_web_page_preview: true,
176
- disable_notification: silent,
177
- };
178
- if (buttons) payload.reply_markup = { inline_keyboard: buttons };
179
-
180
- let response;
181
- if (editMessageId) {
182
- payload.message_id = editMessageId;
183
- payload.text = text;
184
- if (buttons) payload.reply_markup = { inline_keyboard: buttons };
185
- response = await axios.post(`${baseUrl}/editMessageText`, payload, { timeout: 15000 });
186
- } else if (photoUrl) {
187
- payload.photo = photoUrl;
188
- payload.caption = text;
189
- response = await axios.post(`${baseUrl}/sendPhoto`, payload, { timeout: 15000 });
190
- } else {
191
- payload.text = text;
192
- response = await axios.post(`${baseUrl}/sendMessage`, payload, { timeout: 15000 });
193
- }
194
-
195
- if (response.data?.result?.message_id) lastMessageId = response.data.result.message_id;
196
- return response.data;
197
- } catch (e) {
198
- console.error(`[Telegram] ❌ Failed:`, e.message);
199
- }
200
- }
201
- return null;
202
- }
203
-
204
- // ═══════════════════════════════════════════════════════════════════════
205
- // INLINE KEYBOARDS
206
- // ═══════════════════════════════════════════════════════════════════════
207
-
208
- function getMainButtons() {
209
- const liveLink = `https://www.tiktok.com/@${CONFIG.TIKTOK_USERNAME}/live`;
210
- return [
211
- [{ text: '🔴 دخول البث المباشر', url: liveLink }],
212
- [{ text: '📊 تقرير فوري', callback_data: 'report_now' }, { text: '🏆 لوحة الشرف', callback_data: 'top_gifters' }],
213
- [{ text: '💬 أهم التعليقات', callback_data: 'top_chat' }, { text: '👥 المتفاعلين', callback_data: 'top_active' }],
214
- [{ text: '⚔️ حالة PK', callback_data: 'pk_status' }, { text: '📈 إحصائيات', callback_data: 'deep_stats' }],
215
- [{ text: '🎁 الصناديق', callback_data: 'envelopes' }, { text: '💰 العملات', callback_data: 'coin_purse' }],
216
- [{ text: isConnected ? '🔴 قطع الاتصال' : '🟢 الاتصال', callback_data: isConnected ? 'disconnect' : 'connect' }],
217
- ];
218
- }
219
-
220
- function getPKButtons() {
221
- const liveLink = `https://www.tiktok.com/@${CONFIG.TIKTOK_USERNAME}/live`;
222
- return [
223
- [{ text: '🚀 د��م البث الآن', url: liveLink }],
224
- [{ text: '📊 تحديث النتيجة', callback_data: 'pk_update' }, { text: '🏆 داعمين الجولة', callback_data: 'pk_gifters' }],
225
- [{ text: '⬅️ القائمة الرئيسية', callback_data: 'main_menu' }],
226
- ];
227
- }
228
-
229
- function getDisconnectedButtons() {
230
- return [
231
- [{ text: '🔄 إعادة الاتصال', callback_data: 'connect' }],
232
- [{ text: '📊 التقرير النهائي', callback_data: 'final_report' }],
233
- ];
234
- }
235
-
236
- function getStatsButtons() {
237
- return [
238
- [{ text: '🏆 الهدايا', callback_data: 'top_gifters' }, { text: '❤️ الإعجابات', callback_data: 'top_likers' }],
239
- [{ text: '↪️ المشاركات', callback_data: 'top_sharers' }, { text: '➕ المتابعين', callback_data: 'top_followers' }],
240
- [{ text: '💬 الدردشة', callback_data: 'top_chat' }, { text: '👮 المشرفين', callback_data: 'moderators' }],
241
- [{ text: '🎁 الصناديق', callback_data: 'envelopes' }, { text: '💰 العملات', callback_data: 'coin_purse' }],
242
- [{ text: '⬅️ القائمة الرئيسية', callback_data: 'main_menu' }],
243
- ];
244
- }
245
-
246
- // ═══════════════════════════════════════════════════════════════════════
247
- // CALLBACK HANDLER
248
- // ═══════════════════════════════════════════════════════════════════════
249
-
250
- async function handleCallback(callbackData) {
251
- try {
252
- switch (callbackData) {
253
- case 'connect':
254
- if (!isConnected) { await sendTelegram('🔄 جاري الاتصال بالبث...', null, null, 'HTML', null, true); startRadar(); }
255
- else { await sendTelegram('✅ البوت متصل بالفعل!', null, getMainButtons(), 'HTML', null, true); }
256
- break;
257
- case 'disconnect':
258
- if (isConnected) { await sendFinalReport(); disconnectRadar(); await sendTelegram(`🔴 تم قطع الاتصال\n⏰ ${getBaghdadTime()}`, null, getDisconnectedButtons(), 'HTML', null, true); }
259
- break;
260
- case 'report_now':
261
- if (isConnected && isLive) await sendPeriodicReport();
262
- else await sendTelegram('❌ لا يوجد بث نشط حالياً', null, getDisconnectedButtons(), 'HTML', null, true);
263
- break;
264
- case 'top_gifters': await sendTopGiftersReport(); break;
265
- case 'top_likers': await sendTopLikersReport(); break;
266
- case 'top_sharers': await sendTopSharersReport(); break;
267
- case 'top_followers': await sendTopFollowersReport(); break;
268
- case 'top_chat': await sendTopChatReport(); break;
269
- case 'top_active': await sendTopActiveReport(); break;
270
- case 'moderators': await sendModeratorsReport(); break;
271
- case 'deep_stats': await sendDeepStatsReport(); break;
272
- case 'envelopes': await sendEnvelopesReport(); break;
273
- case 'coin_purse': await sendCoinPurseReport(); break;
274
- case 'pk_update':
275
- case 'pk_status':
276
- if (pkActive) await sendPKUpdate();
277
- else await sendTelegram('⚔️ لا يوجد جولة PK نشطة حالياً', null, getMainButtons(), 'HTML', null, true);
278
- break;
279
- case 'pk_gifters': await sendPKGiftersReport(); break;
280
- case 'final_report': await sendFinalReport(); break;
281
- case 'main_menu': await sendTelegram('📡 القائمة الرئيسية', null, getMainButtons(), 'HTML', null, true); break;
282
- default: console.log(`[Callback] Unknown: ${callbackData}`);
283
- }
284
- } catch (err) { console.error('[handleCallback] Error:', err); }
285
- }
286
-
287
- async function pollCallbacks() {
288
- let offset = 0;
289
- const urls = [];
290
- let proxyUrl = CONFIG.PROXY_URL;
291
- if (proxyUrl && proxyUrl.startsWith('http')) urls.push(`${proxyUrl}/bot${CONFIG.TELEGRAM_TOKEN}`);
292
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
293
- let currentUrlIndex = 0;
294
-
295
- while (true) {
296
- try {
297
- const baseUrl = urls[currentUrlIndex];
298
- const res = await axios.get(`${baseUrl}/getUpdates`, { params: { offset, limit: 10, timeout: 30 }, timeout: 35000 });
299
- const updates = res.data?.result || [];
300
- for (const update of updates) {
301
- offset = update.update_id + 1;
302
- updateActivity();
303
- if (update.callback_query) {
304
- const callbackData = update.callback_query.data;
305
- console.log(`[Callback] 📲 ${callbackData}`);
306
- await handleCallback(callbackData);
307
- try { await axios.post(`${baseUrl}/answerCallbackQuery`, { callback_query_id: update.callback_query.id }); } catch (e) {}
308
- }
309
- }
310
- currentUrlIndex = 0;
311
- } catch (e) {
312
- console.error(`[Callback] ❌ Failed:`, e.message);
313
- currentUrlIndex = (currentUrlIndex + 1) % urls.length;
314
- await new Promise(r => setTimeout(r, currentUrlIndex === 0 ? 5000 : 2000));
315
- }
316
- }
317
- }
318
-
319
- // ════���══════════════════════════════════════════════════════════════════
320
- // STATISTICS & FORMATTING
321
- // ═══════════════════════════════════════════════════════════════════════
322
-
323
- function getTopGifters(top = 5) { return Object.values(giftersMap).sort((a, b) => b.coins - a.coins).slice(0, top); }
324
- function getTopLikers(top = 5) { return Object.values(likersMap).sort((a, b) => b.count - a.count).slice(0, top); }
325
- function getTopSharers(top = 5) { return Object.values(sharersMap).sort((a, b) => b.count - a.count).slice(0, top); }
326
- function getTopFollowers(top = 5) { return Object.values(followersMap).sort((a, b) => b.count - a.count).slice(0, top); }
327
- function getTopChatters(top = 5) { return Object.values(chattersMap).sort((a, b) => b.count - a.count).slice(0, top); }
328
- function getModeratorsList() { return Object.values(moderatorsMap).sort((a, b) => b.joinTime - a.joinTime); }
329
- function getTopEnvelopeWinners(top = 5) { return Object.values(envelopeWinnersMap).sort((a, b) => b.count - a.count).slice(0, top); }
330
- function getTopCoinPurseWinners(top = 5) { return Object.values(coinPurseWinnersMap).sort((a, b) => b.coins - a.coins).slice(0, top); }
331
-
332
- function getTopActiveUsers(top = 5) {
333
- const allUsers = {};
334
- [...Object.values(giftersMap), ...Object.values(likersMap), ...Object.values(sharersMap),
335
- ...Object.values(followersMap), ...Object.values(chattersMap)].forEach(u => {
336
- const key = u.id || u.name;
337
- if (!allUsers[key]) allUsers[key] = { name: u.name, score: 0 };
338
- allUsers[key].score += (u.coins || 0) + (u.count || 0) * 10;
339
- });
340
- return Object.values(allUsers).sort((a, b) => b.score - a.score).slice(0, top);
341
- }
342
-
343
- function formatTopGifters(top = 5) {
344
- const list = getTopGifters(top);
345
- if (list.length === 0) return 'لا يوجد داعمين في هذا البث';
346
- const medals = ['🥇', '🥈', '🥉', '🏅', '🎖', '🎗', '🏵', '🎖', '🏅', '🥉'];
347
- return list.map((g, i) => `${medals[i] || '🏅'} ${escapeHtml(g.name)} » ${formatK(g.coins)} 💎`).join('\n');
348
- }
349
-
350
- function formatTopLikers(top = 5) {
351
- const list = getTopLikers(top);
352
- if (list.length === 0) return 'لا يوجد معجبين مسجلين';
353
- const medals = ['🥇', '🥈', '🥉', '🏅', '🎖'];
354
- return list.map((g, i) => `${medals[i] || '❤️'} ${escapeHtml(g.name)} » ${formatK(g.count)} ❤️`).join('\n');
355
- }
356
-
357
- function formatTopSharers(top = 5) {
358
- const list = getTopSharers(top);
359
- if (list.length === 0) return 'لا يوجد مشاركين مسجلين';
360
- return list.map((g, i) => `${i + 1}. ${escapeHtml(g.name)} » ${formatK(g.count)} ↪️`).join('\n');
361
- }
362
-
363
- function formatTopFollowers(top = 5) {
364
- const list = getTopFollowers(top);
365
- if (list.length === 0) return 'لا يوجد متابعين جدد مسجلين';
366
- return list.map((g, i) => `${i + 1}. ${escapeHtml(g.name)} ➕`).join('\n');
367
- }
368
-
369
- function formatTopChatters(top = 5) {
370
- const list = getTopChatters(top);
371
- if (list.length === 0) return 'لا يوجد متفاعلين في الدردشة';
372
- return list.map((g, i) => `${i + 1}. ${escapeHtml(g.name)} » ${formatK(g.count)} 💬`).join('\n');
373
- }
374
-
375
- function formatTopActive(top = 5) {
376
- const list = getTopActiveUsers(top);
377
- if (list.length === 0) return 'لا يوجد متفاعلين بعد';
378
- const medals = ['👑', '🥈', '🥉', '⭐', '✨'];
379
- return list.map((g, i) => `${medals[i] || '🔹'} ${escapeHtml(g.name)} » ${formatK(g.score)} نقطة`).join('\n');
380
- }
381
-
382
- function formatModerators() {
383
- const list = getModeratorsList();
384
- if (list.length === 0) return 'لا يوجد مشرفين دخلوا البث';
385
- return list.map((m, i) => `${i + 1}. 👮 ${escapeHtml(m.name)}${m.isModerator ? ' [مشرف]' : ''}`).join('\n');
386
- }
387
-
388
- function formatTopChatMessages() {
389
- if (topChatMessages.length === 0) return 'لا توجد رسائل بعد';
390
- return topChatMessages.slice(0, CONFIG.TOP_CHAT_LIMIT).map((msg) => `💬 <b>${escapeHtml(msg.name)}:</b> ${escapeHtml(msg.text)}`).join('\n');
391
- }
392
-
393
- function formatPKGifters() {
394
- const list = Object.values(pkInfo.pkGifts || {}).sort((a, b) => b.coins - a.coins).slice(0, 5);
395
- if (list.length === 0) return 'لا يوجد داعمين في الجولة';
396
- return list.map((g, i) => `${i + 1}. ${escapeHtml(g.name)} » ${formatK(g.coins)} 💎`).join('\n');
397
- }
398
-
399
- function formatEnvelopeWinners(top = 10) {
400
- const list = getTopEnvelopeWinners(top);
401
- if (list.length === 0) return 'لا يوجد فائزين بالصناديق بعد';
402
- return list.map((w, i) => `${i + 1}. 🎁 ${escapeHtml(w.name)} » ${formatK(w.count)} صندوق`).join('\n');
403
- }
404
-
405
- function formatCoinPurseWinners(top = 10) {
406
- const list = getTopCoinPurseWinners(top);
407
- if (list.length === 0) return 'لا يوجد فائزين بحقيبة العملات بعد';
408
- return list.map((w, i) => `${i + 1}. 💰 ${escapeHtml(w.name)} » ${formatK(w.coins)} عملة`).join('\n');
409
- }
410
-
411
- // ═══════════════════════════════════════════════════════════════════════
412
- // REPORT FUNCTIONS
413
- // ═══════════════════════════════════════════════════════════════════════
414
-
415
- async function sendPeriodicReport() {
416
- if (!isConnected || !isLive) return;
417
- try {
418
- const duration = formatDuration(startTime);
419
- const topGifterText = formatTopGifters(3);
420
- const topLikerText = formatTopLikers(3);
421
- const currentViewers = viewerHistory.length > 0 ? viewerHistory[viewerHistory.length - 1].viewers : 0;
422
-
423
- const msg = `📊 <b>تقرير البث المباشر</b>\n` +
424
- `━━━━━━━━━━━━━━━━━━━\n` +
425
- `👤 <b>المُضيف:</b> ${CONFIG.TIKTOK_USERNAME}\n` +
426
- `⏰ <b>الوقت:</b> ${getBaghdadTime()}\n` +
427
- `⏱ <b>مدة البث:</b> ${duration}\n\n` +
428
- `👁‍🗨 <b>المشاهدين الحاليين:</b> ${formatK(currentViewers)}\n` +
429
- `🔥 <b>أعلى مشاهدات:</b> ${formatK(maxViewers)}\n` +
430
- `❤️ <b>الإعجابات:</b> ${formatK(totalLikes)}\n` +
431
- `↪️ <b>المشاركات:</b> ${formatK(totalShares)}\n` +
432
- `➕ <b>المتابعين الجدد:</b> ${formatK(totalFollows)}\n` +
433
- `💬 <b>التعليقات:</b> ${formatK(totalComments)}\n` +
434
- `🎁 <b>الهدايا:</b> ${formatK(totalGifts)} 💎\n` +
435
- `📦 <b>الصناديق:</b> ${formatK(totalEnvelopes)}\n` +
436
- `💰 <b>العملات الموزعة:</b> ${formatK(totalCoinsGiven)}\n\n` +
437
- `🏆 <b>أفضل الداعمين:</b>\n${topGifterText}\n\n` +
438
- `❤️ <b>أكثر المعجبين:</b>\n${topLikerText}\n` +
439
- `━━━━━━━━━━━━━━━━━━━`;
440
-
441
- await sendTelegram(msg, null, getMainButtons(), 'HTML', null, true);
442
- lastReportTime = new Date();
443
- } catch (err) { console.error('[sendPeriodicReport] Error:', err); }
444
- }
445
-
446
- async function sendTopGiftersReport() {
447
- try {
448
- const msg = `👑 <b>لوحة الشرف - أفضل الداعمين</b>\n━━━━━━━━━━━━━━━━━━━\n${formatTopGifters(10)}\n━━━━━━━━━━━━━━━━━━━\n💎 إجمالي الهدايا: ${formatK(totalGifts)}`;
449
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
450
- } catch (err) { console.error('[sendTopGiftersReport] Error:', err); }
451
- }
452
-
453
- async function sendTopLikersReport() {
454
- try {
455
- const msg = `❤️ <b>أكثر المعجبين</b>\n━━━━━━━━━━━━━━━━━━━\n${formatTopLikers(10)}\n━━━━━━━━━━━━━━━━━━━\n❤️ إجمالي الإعجابات: ${formatK(totalLikes)}`;
456
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
457
- } catch (err) { console.error('[sendTopLikersReport] Error:', err); }
458
- }
459
-
460
- async function sendTopSharersReport() {
461
- try {
462
- const msg = `↪️ <b>أكثر المشاركين</b>\n━━━━━━━━━━━━━━━━━━━\n${formatTopSharers(10)}\n━━━━━━━━━━━━━━━━━━━\n↪️ إجمالي المشاركات: ${formatK(totalShares)}`;
463
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
464
- } catch (err) { console.error('[sendTopSharersReport] Error:', err); }
465
- }
466
-
467
- async function sendTopFollowersReport() {
468
- try {
469
- const msg = `➕ <b>المتابعين الجدد</b>\n━━━━━━━━━━━━━━━━━━━\n${formatTopFollowers(10)}\n━━━━━━━━━━━━━━━━━━━\n➕ إجمالي المتابعين: ${formatK(totalFollows)}`;
470
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
471
- } catch (err) { console.error('[sendTopFollowersReport] Error:', err); }
472
- }
473
-
474
- async function sendTopChatReport() {
475
- try {
476
- const chatters = formatTopChatters(10);
477
- const messages = formatTopChatMessages();
478
- const msg = `💬 <b>أهم التعليقات والمتفاعلين</b>\n━━━━━━━━━━━━━━━━━━━\n<b>📌 أحدث الرسائل:</b>\n${messages}\n\n<b>👥 أكثر المتفاعلين:</b>\n${chatters}\n━━━━━━━━━━━━━━━━━━━\n💬 إجمالي التعليقات: ${formatK(totalComments)}`;
479
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
480
- } catch (err) { console.error('[sendTopChatReport] Error:', err); }
481
- }
482
-
483
- async function sendTopActiveReport() {
484
- try {
485
- const msg = `🔥 <b>أكثر المتفاعلين شاملاً</b>\n━━━━━━━━━━━━━━━━━━━\n${formatTopActive(10)}\n━━━━━━━━━━━���━━━━━━━\n📊 النقاط = الهدايا + التفاعلات × 10`;
486
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
487
- } catch (err) { console.error('[sendTopActiveReport] Error:', err); }
488
- }
489
-
490
- async function sendModeratorsReport() {
491
- try {
492
- const msg = `👮 <b>المشرفين والأعضاء المميزين</b>\n━━━━━━━━━━━━━━━━━━━\n${formatModerators()}\n━━━━━━━━━━━━━━━━━━━`;
493
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
494
- } catch (err) { console.error('[sendModeratorsReport] Error:', err); }
495
- }
496
-
497
- async function sendDeepStatsReport() {
498
- try {
499
- const duration = formatDuration(startTime);
500
- const currentViewers = viewerHistory.length > 0 ? viewerHistory[viewerHistory.length - 1].viewers : 0;
501
- const avgViewers = viewerHistory.length > 0 ? Math.round(viewerHistory.reduce((a, b) => a + b.viewers, 0) / viewerHistory.length) : 0;
502
-
503
- const msg = `📈 <b>إحصائيات عميقة</b>\n` +
504
- `━━━━━━━━━━━━━━━━━━━\n` +
505
- `⏱ <b>مدة البث:</b> ${duration}\n` +
506
- `👁‍🗨 <b>المشاهدين الحاليين:</b> ${formatK(currentViewers)}\n` +
507
- `🔥 <b>أعلى مشاهدات:</b> ${formatK(maxViewers)}\n` +
508
- `📊 <b>متوسط المشاهدين:</b> ${formatK(avgViewers)}\n\n` +
509
- `❤️ <b>الإعجابات:</b> ${formatK(totalLikes)}\n` +
510
- `↪️ <b>المشاركات:</b> ${formatK(totalShares)}\n` +
511
- `➕ <b>المتابعين:</b> ${formatK(totalFollows)}\n` +
512
- `💬 <b>التعليقات:</b> ${formatK(totalComments)}\n` +
513
- `🎁 <b>الهدايا:</b> ${formatK(totalGifts)} 💎\n` +
514
- `📦 <b>الصناديق:</b> ${formatK(totalEnvelopes)}\n` +
515
- `💰 <b>العملات الموزعة:</b> ${formatK(totalCoinsGiven)}\n\n` +
516
- `👥 <b>عدد الداعمين:</b> ${Object.keys(giftersMap).length}\n` +
517
- `💬 <b>عدد المتفاعلين:</b> ${Object.keys(chattersMap).length}\n` +
518
- `➕ <b>عدد المتابعين الجدد:</b> ${Object.keys(followersMap).length}\n` +
519
- `👮 <b>عدد المشرفين:</b> ${Object.keys(moderatorsMap).length}\n` +
520
- `🎁 <b>فائزين الصناديق:</b> ${Object.keys(envelopeWinnersMap).length}\n` +
521
- `💰 <b>فائزين العملات:</b> ${Object.keys(coinPurseWinnersMap).length}\n` +
522
- `━━━━━━━━━━━━━━━━━━━`;
523
- await sendTelegram(msg, null, getMainButtons(), 'HTML', null, true);
524
- } catch (err) { console.error('[sendDeepStatsReport] Error:', err); }
525
- }
526
-
527
- async function sendPKUpdate() {
528
- if (!pkActive) return;
529
- try {
530
- const bar = generateProgressBar(pkInfo.ourScore, pkInfo.theirScore, 10);
531
- const isWinning = pkInfo.ourScore > pkInfo.theirScore;
532
- const pkGifters = formatPKGifters();
533
- const msg = `⚔️ <b>تحديث PK</b>\n━━━━━━━━━━━━━━━━━━━\n🟦 <b>نحن:</b> ${formatK(pkInfo.ourScore)}\n🟥 <b>${escapeHtml(pkInfo.opponentName)}:</b> ${formatK(pkInfo.theirScore)}\n\n${bar}\n\n${isWinning ? '🏆 نحن في المقدمة!' : pkInfo.ourScore === pkInfo.theirScore ? '🤝 تعادل!' : '😢 المنافس في المقدمة'}\n\n🏆 <b>داعمين الجولة:</b>\n${pkGifters}`;
534
- await sendTelegram(msg, null, getPKButtons(), 'HTML', null, true);
535
- } catch (err) { console.error('[sendPKUpdate] Error:', err); }
536
- }
537
-
538
- async function sendPKGiftersReport() {
539
- if (!pkActive) { await sendTelegram('⚔️ لا يوجد جولة PK نشطة', null, getMainButtons(), 'HTML', null, true); return; }
540
- try {
541
- const msg = `⚔️ <b>داعمين جولة PK</b>\n━━━━━━━━━━━━━━━━━━━\n${formatPKGifters()}\n━━━━━━━━━━━━━━━━━━━`;
542
- await sendTelegram(msg, null, getPKButtons(), 'HTML', null, true);
543
- } catch (err) { console.error('[sendPKGiftersReport] Error:', err); }
544
- }
545
-
546
- async function sendEnvelopesReport() {
547
- try {
548
- const winners = formatEnvelopeWinners(10);
549
- const msg = `🎁📦 <b>صناديق الهدايا - الفائزين</b>\n━━━━━━━━━━━━━━━━━━━\n${winners}\n━━━━━━━━━━━━━━━━━━━\n📦 إجمالي الصناديق: ${formatK(totalEnvelopes)}\n👥 عدد الفائزين: ${Object.keys(envelopeWinnersMap).length}`;
550
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
551
- } catch (err) { console.error('[sendEnvelopesReport] Error:', err); }
552
- }
553
-
554
- async function sendCoinPurseReport() {
555
- try {
556
- const winners = formatCoinPurseWinners(10);
557
- const msg = `💰🎒 <b>حقيبة العملات - الفائزين</b>\n━━━━━━━━━━━━━━━━━━━\n${winners}\n━━━━━━━━━━━━━━━━━━━\n💰 إجمالي العملات الموزعة: ${formatK(totalCoinsGiven)}\n👥 عدد ��لفائزين: ${Object.keys(coinPurseWinnersMap).length}`;
558
- await sendTelegram(msg, null, getStatsButtons(), 'HTML', null, true);
559
- } catch (err) { console.error('[sendCoinPurseReport] Error:', err); }
560
- }
561
-
562
- async function sendFinalReport() {
563
- try {
564
- const duration = formatDuration(startTime);
565
- const topGifterText = formatTopGifters(5);
566
- const topActiveText = formatTopActive(5);
567
- const envelopeWinners = formatEnvelopeWinners(5);
568
- const coinWinners = formatCoinPurseWinners(5);
569
- const avgViewers = viewerHistory.length > 0 ? Math.round(viewerHistory.reduce((a, b) => a + b.viewers, 0) / viewerHistory.length) : 0;
570
-
571
- const msg = `📊 <b>التقرير النهائي للبث</b>\n` +
572
- `━━━━━━━━━━━━━━━━━━━\n` +
573
- `👤 <b>المُضيف:</b> ${CONFIG.TIKTOK_USERNAME}\n` +
574
- `📅 <b>التاريخ:</b> ${getDateString()}\n` +
575
- `⏱ <b>مدة البث:</b> ${duration}\n\n` +
576
- `🔥 <b>أعلى مشاهدات:</b> ${formatK(maxViewers)}\n` +
577
- `📊 <b>متوسط المشاهدين:</b> ${formatK(avgViewers)}\n` +
578
- `❤️ <b>إجمالي الإعجابات:</b> ${formatK(totalLikes)}\n` +
579
- `↪️ <b>إجمالي المشاركات:</b> ${formatK(totalShares)}\n` +
580
- `➕ <b>إجمالي المتابعين:</b> ${formatK(totalFollows)}\n` +
581
- `💬 <b>إجمالي التعليقات:</b> ${formatK(totalComments)}\n` +
582
- `🎁 <b>إجمالي الهدايا:</b> ${formatK(totalGifts)} 💎\n` +
583
- `📦 <b>إجمالي الصناديق:</b> ${formatK(totalEnvelopes)}\n` +
584
- `💰 <b>إجمالي العملات:</b> ${formatK(totalCoinsGiven)}\n\n` +
585
- `🏆 <b>لوحة الشرف (الداعمين):</b>\n${topGifterText}\n\n` +
586
- `🔥 <b>أكثر المتفاعلين:</b>\n${topActiveText}\n\n` +
587
- `🎁 <b>فائزين الصناديق:</b>\n${envelopeWinners}\n\n` +
588
- `💰 <b>فائزين العملات:</b>\n${coinWinners}\n` +
589
- `━━━━━━━━━━━━━━━━━━━\n` +
590
- `💤 البوت في وضع الانتظار...`;
591
- await sendTelegram(msg, null, getDisconnectedButtons(), 'HTML', null, false);
592
- } catch (err) { console.error('[sendFinalReport] Error:', err); }
593
- }
594
-
595
- // ═══════════════════════════════════════════════════════════════════════
596
- // EVENT NOTIFIERS
597
- // ═══════════════════════════════════════════════════════════════════════
598
-
599
- async function notifyLike(nickname, likeCount, userId) {
600
- if (!isLive) return;
601
- if (!likersMap[userId]) likersMap[userId] = { id: userId, name: nickname, count: 0 };
602
- likersMap[userId].count += likeCount;
603
- totalLikes += likeCount;
604
- if (pkActive) pkInfo.ourScore += likeCount;
605
-
606
- if (likeCount >= CONFIG.LIKE_BATCH_THRESHOLD) {
607
- if (isOnCooldown('like', userId, 30000)) return;
608
- await sendTelegram(`❤️🔥 <b>${escapeHtml(nickname)}</b> أرسل <b>${formatK(likeCount)}</b> إعجاب دفعة واحدة!`, null, null, 'HTML', null, true);
609
- }
610
- }
611
-
612
- async function notifyGift(nickname, giftName, diamondCount, repeatCount, totalCost, userId) {
613
- if (!isLive) return;
614
- if (isOnCooldown('gift', userId, CONFIG.GIFT_COOLDOWN_MS)) return;
615
-
616
- if (!giftersMap[userId]) giftersMap[userId] = { id: userId, name: nickname, coins: 0 };
617
- giftersMap[userId].coins += totalCost;
618
- totalGifts += totalCost;
619
-
620
- if (pkActive) {
621
- pkInfo.ourScore += totalCost;
622
- if (!pkInfo.pkGifts[userId]) pkInfo.pkGifts[userId] = { id: userId, name: nickname, coins: 0 };
623
- pkInfo.pkGifts[userId].coins += totalCost;
624
- }
625
-
626
- const isBig = totalCost >= 100;
627
- const isHuge = totalCost >= 500;
628
- const emoji = isHuge ? '🎁💎🔥' : isBig ? '🎁🔥' : '🎁';
629
- const extra = isHuge ? '\n🌟🌟 هدية ضخمة!!! 🌟🌟' : isBig ? '\n🌟 هدية كبيرة!' : '';
630
-
631
- await sendTelegram(`${emoji} <b>${escapeHtml(nickname)}</b> أرسل <b>${escapeHtml(giftName)}</b> ×${repeatCount}\n💎 القيمة: <b>${formatK(totalCost)}</b> 💎${extra}`, null, null, 'HTML', null, true);
632
- }
633
-
634
- async function notifyFollow(nickname, userId) {
635
- if (!isLive) return;
636
- if (isOnCooldown('follow', userId, 10000)) return;
637
- if (!followersMap[userId]) followersMap[userId] = { id: userId, name: nickname, count: 0 };
638
- followersMap[userId].count++;
639
- totalFollows++;
640
- await sendTelegram(`➕✨ <b>${escapeHtml(nickname)}</b> تابع البث!`, null, null, 'HTML', null, true);
641
- }
642
-
643
- async function notifyShare(nickname, userId) {
644
- if (!isLive) return;
645
- if (isOnCooldown('share', userId, 15000)) return;
646
- if (!sharersMap[userId]) sharersMap[userId] = { id: userId, name: nickname, count: 0 };
647
- sharersMap[userId].count++;
648
- totalShares++;
649
- await sendTelegram(`↪️ <b>${escapeHtml(nickname)}</b> شارك البث!`, null, null, 'HTML', null, true);
650
- }
651
-
652
- // ═══════════════════════════════════════════════════════════════════════
653
- // TIKTOK EVENT HANDLERS (مُصحَّحة وفق التوثيق الرسمي v2.0+)
654
- // ═══════════════════════════════════════════════════════════════════════
655
-
656
- function handleChat(data) {
657
- if (!isLive) return;
658
- try {
659
- const user = data.user || {};
660
- const userId = user.userId || user.id || 'unknown';
661
- const nickname = user.nickname || user.displayId || 'مجهول';
662
- const rawText = data.comment || data.message || '';
663
- const text = cleanChatMessage(rawText);
664
-
665
- if (!text || isSpamMessage(text)) return;
666
-
667
- if (!chattersMap[userId]) chattersMap[userId] = { id: userId, name: nickname, count: 0 };
668
- chattersMap[userId].count++;
669
- totalComments++;
670
-
671
- topChatMessages.unshift({ name: nickname, text: text, time: Date.now() });
672
- if (topChatMessages.length > 50) topChatMessages = topChatMessages.slice(0, 50);
673
-
674
- if (isOnCooldown('chat', userId, CONFIG.CHAT_COOLDOWN_MS)) return;
675
-
676
- const importantKeywords = ['سؤال', 'جواب', 'هلا', 'مرحبا', 'تفاعل', 'دعم', 'pk', 'بكج', 'تصويت', 'صندوق', 'عملات'];
677
- const isImportant = text.length > 25 || importantKeywords.some(kw => text.toLowerCase().includes(kw));
678
-
679
- if (isImportant) {
680
- sendTelegram(`💬 <b>${escapeHtml(nickname)}:</b> ${escapeHtml(text)}`, null, null, 'HTML', null, true);
681
- }
682
- } catch (err) { console.error('[handleChat] Error:', err); }
683
- }
684
-
685
- function handleMember(data) {
686
- if (!isLive) return;
687
  try {
688
- const user = data.user || {};
689
- const userId = user.userId || user.id || 'unknown';
690
- const nickname = user.nickname || user.displayId || 'مجهول';
691
- const isMod = user.isModerator || false;
692
- const isSubscriber = user.isSubscriber || false;
693
- const isNewGifter = user.isNewGifter || false;
694
-
695
- if (isMod) {
696
- if (!moderatorsMap[userId]) {
697
- moderatorsMap[userId] = {
698
- id: userId, name: nickname, joinTime: Date.now(),
699
- isModerator: true, isSubscriber: isSubscriber, isNewGifter: isNewGifter,
700
- };
701
- if (!isOnCooldown('moderator', userId, 30000)) {
702
- sendTelegram(`👮✨ <b>${escapeHtml(nickname)}</b> [مشرف] دخل البث!`, null, null, 'HTML', null, true);
703
- }
704
- }
705
- } else if (isSubscriber || isNewGifter) {
706
- if (!moderatorsMap[userId]) {
707
- moderatorsMap[userId] = {
708
- id: userId, name: nickname, joinTime: Date.now(),
709
- isModerator: false, isSubscriber: isSubscriber, isNewGifter: isNewGifter,
710
- };
711
- }
712
- }
713
- } catch (err) { console.error('[handleMember] Error:', err); }
714
  }
715
 
716
- function handleEnvelope(data) {
717
- if (!isLive) return;
718
- try {
719
- const user = data.user || {};
720
- const userId = user.userId || user.id || 'unknown';
721
- const nickname = user.nickname || user.displayId || 'مجهول';
722
- const envelopeId = data.envelopeId || data.msgId || `env-${Date.now()}`;
723
-
724
- totalEnvelopes++;
725
-
726
- if (!envelopeWinnersMap[userId]) envelopeWinnersMap[userId] = { id: userId, name: nickname, count: 0 };
727
- envelopeWinnersMap[userId].count++;
728
-
729
- if (isOnCooldown('envelope', envelopeId, 5000)) return;
730
-
731
- sendTelegram(`🎁📦 <b>${escapeHtml(nickname)}</b> حصل على صندوق هدايا! 🎉`, null, null, 'HTML', null, true);
732
- } catch (err) { console.error('[handleEnvelope] Error:', err); }
733
- }
734
-
735
- function handleCoinPurse(data) {
736
- if (!isLive) return;
737
- try {
738
- const user = data.user || {};
739
- const userId = user.userId || user.id || 'unknown';
740
- const nickname = user.nickname || user.displayId || 'مجهول';
741
- const coins = data.coins || data.diamondCount || 1;
742
- const purseId = data.purseId || data.msgId || `coin-${Date.now()}`;
743
-
744
- totalCoinsGiven += coins;
745
-
746
- if (!coinPurseWinnersMap[userId]) coinPurseWinnersMap[userId] = { id: userId, name: nickname, coins: 0 };
747
- coinPurseWinnersMap[userId].coins += coins;
748
-
749
- if (isOnCooldown('coinPurse', purseId, 5000)) return;
750
-
751
- sendTelegram(`💰🎒 <b>${escapeHtml(nickname)}</b> حصل على <b>${formatK(coins)}</b> عملة من حقيبة العملات! ✨`, null, null, 'HTML', null, true);
752
- } catch (err) { console.error('[handleCoinPurse] Error:', err); }
753
- }
754
-
755
- function handleBattleStart(data) {
756
- try {
757
- const battleItems = data.battleItems || [];
758
- let opponentName = 'مجهول';
759
- let opponentUserId = '';
760
-
761
- if (battleItems.length >= 2) {
762
- const opponent = battleItems.find(b => b.hostUserId !== data.hostUserId) || battleItems[1];
763
- if (opponent && opponent.battleGroups && opponent.battleGroups[0]) {
764
- const firstUser = opponent.battleGroups[0].users?.[0] || {};
765
- opponentName = firstUser.nickname || 'مجهول';
766
- opponentUserId = firstUser.userId || opponent.hostUserId || '';
767
- }
768
- }
769
-
770
- pkActive = true;
771
- pkInfo = {
772
- opponentName: opponentName, opponentUserId: opponentUserId,
773
- ourScore: 0, theirScore: 0, startTime: new Date(), pkGifts: {},
774
- };
775
-
776
- const msg = `🔥⚔️ <b>بدأت جولة PK جديدة!</b>\n━━━━━━━━━━━━━━━━━━━\n🥊 <b>المنافس:</b> ${escapeHtml(opponentName)}\n\nالفوز يحتاج وقفة الأبطال! شدوا الحيل.. 🚀`;
777
- sendTelegram(msg, null, getPKButtons(), 'HTML', null, false);
778
- } catch (err) { console.error('[handleBattleStart] Error:', err); }
779
- }
780
-
781
- function handleBattleEnd(data) {
782
- if (!pkActive) return;
783
- try {
784
- pkActive = false;
785
- const bar = generateProgressBar(pkInfo.ourScore, pkInfo.theirScore, 10);
786
- const winner = data.winnerUserId === CONFIG.TIKTOK_USERNAME ? 'نحن' :
787
- data.winnerUserId === pkInfo.opponentUserId ? pkInfo.opponentName : 'تعادل';
788
- const result = winner === 'تعادل' ? '🤝 تعادل' : winner === 'نحن' ? '🏆 فزنا!' : '😢 خسرنا';
789
- const pkGifters = formatPKGifters();
790
-
791
- const msg = `🏆⚔️ <b>انتهت المواجهة!</b>\n━━━━━━━━━━━━━━━━━━━\n${result}\n\n📊 <b>النتيجة البصرية:</b>\n🟦 نحن: ${formatK(pkInfo.ourScore)} | ${formatK(pkInfo.theirScore)} :المنافس 🟥\n${bar}\n\n🏆 <b>داعمين الجولة:</b>\n${pkGifters}\n\n✨ شكراً لكل من ساهم في هذه الجولة!`;
792
- sendTelegram(msg, null, getMainButtons(), 'HTML', null, false);
793
-
794
- pkInfo = { opponentName: '', opponentUserId: '', ourScore: 0, theirScore: 0, startTime: null, pkGifts: {} };
795
- } catch (err) { console.error('[handleBattleEnd] Error:', err); }
796
- }
797
-
798
- function handleBattleUpdate(data) {
799
- if (!pkActive) return;
800
- try {
801
- const battleItems = data.battleItems || [];
802
- if (battleItems.length > 0) {
803
- const ourBattle = battleItems.find(b => b.hostUserId === data.hostUserId) || battleItems[0];
804
- const opponentBattle = battleItems.find(b => b.hostUserId !== data.hostUserId);
805
-
806
- if (ourBattle && ourBattle.battleGroups) {
807
- let ourScore = 0;
808
- ourBattle.battleGroups.forEach(group => {
809
- group.users?.forEach(u => {
810
- ourScore += u.points || 0;
811
- });
812
- });
813
- pkInfo.ourScore = ourScore;
814
- }
815
-
816
- if (opponentBattle && opponentBattle.battleGroups) {
817
- let theirScore = 0;
818
- opponentBattle.battleGroups.forEach(group => {
819
- group.users?.forEach(u => {
820
- theirScore += u.points || 0;
821
- });
822
- });
823
- pkInfo.theirScore = theirScore;
824
- }
825
- }
826
- } catch (err) { console.error('[handleBattleUpdate] Error:', err); }
827
- }
828
-
829
- async function notifyStreamStart(state) {
830
- isLive = true;
831
- try {
832
- const roomInfo = state?.roomInfo || {};
833
- const owner = roomInfo.owner || {};
834
- const avatarUrl = owner.avatar_large?.url_list?.[0] || owner.avatar_thumb?.url_list?.[0] || '';
835
- const viewerCount = roomInfo.viewerCount || state?.viewerCount || 0;
836
-
837
- const welcomeMsg = `📡✨ <b>رادار البث المباشر | LIVE</b>\n` +
838
- `━━━━━━━━━━━━━━━━━━━\n` +
839
- `👤 <b>المُضيف:</b> ${CONFIG.TIKTOK_USERNAME}\n` +
840
- `⏰ <b>الوقت:</b> ${getBaghdadTime()}\n` +
841
- `👁‍🗨 <b>المشاهدين:</b> ${formatK(viewerCount)}\n\n` +
842
- `🎉 <b>البث بدأ!</b>\n` +
843
- `✨ انضم وكن أول الحاضرين وادعم البث!`;
844
-
845
- await sendTelegram(welcomeMsg, avatarUrl || null, getMainButtons(), 'HTML', null, false);
846
- } catch (err) { console.error('[notifyStreamStart] Error:', err); }
847
- }
848
-
849
- async function notifyStreamEnd() {
850
- isLive = false;
851
- try { await sendFinalReport(); } catch (err) { console.error('[notifyStreamEnd] Error:', err); }
852
- }
853
-
854
- // ════════════════════════════════════════════════════════��══════════════
855
- // CONNECTION SETUP (مُحدَّثة للإصدار 2.0+ مع session.cookie)
856
- // ═══════════════════════════════════════════════════════════════════════
857
-
858
  function createConnection() {
859
- try {
860
- const options = {
861
- processInitialData: true,
862
- enableWebsocketUpgrade: true,
863
- enableExtendedGiftInfo: true,
864
- requestPollingIntervalMs: 2000,
865
- clientParams: { app_language: 'ar-IQ', device_platform: 'web' },
866
- };
867
-
868
- if (CONFIG.SESSION_ID && CONFIG.SESSION_ID.length > 10) {
869
- console.log('[TikTok] Using sessionId with websocket upgrade');
870
- console.log('[TikTok] tt-target-idc:', CONFIG.TT_TARGET_IDC);
871
-
872
- const sessionCookie = {
873
- type: 'cookie',
874
- value: {
875
- sessionId: CONFIG.SESSION_ID,
876
- ttTargetIdc: CONFIG.TT_TARGET_IDC,
877
- }
878
- };
879
-
880
- options.session = { cookie: sessionCookie };
881
- options.authenticateWs = true;
882
- } else {
883
- console.log('[TikTok] No sessionId provided, using request polling only');
884
- options.enableWebsocketUpgrade = false;
885
- }
886
-
887
- console.log('[TikTok] Creating connection for:', CONFIG.TIKTOK_USERNAME);
888
- const conn = new TikTokLiveConnection(CONFIG.TIKTOK_USERNAME, options);
889
- console.log('[TikTok] Connection object created successfully');
890
- return conn;
891
- } catch (err) {
892
- console.error('[TikTok] Failed to create connection:', err);
893
- throw err;
894
  }
 
895
  }
896
 
897
- function setupEvents(connection) {
898
- if (!connection || !connection.on) {
899
- console.error('[TikTok] Invalid connection object');
900
- return;
901
- }
902
-
903
- console.log('[TikTok] Setting up event listeners...');
904
-
905
- connection.on(ControlEvent.CONNECTED, (state) => {
906
- updateActivity();
907
- const viewerCount = state?.roomInfo?.viewerCount || state?.viewerCount || 0;
908
- console.log('[TikTok] ✅ Connected! Room:', state?.roomId, 'Viewers:', viewerCount);
909
- isConnected = true;
910
- isLive = true;
911
- startTime = new Date();
912
- lastReportTime = new Date();
913
- reconnectAttempt = 0;
914
- lastReconnectNotify = 0;
915
- notifyStreamStart(state);
916
- startPeriodicReports();
917
  });
918
 
919
- connection.on(ControlEvent.DISCONNECTED, () => {
920
  updateActivity();
921
- console.log('[TikTok] Disconnected from stream');
922
- isConnected = false;
923
- isLive = false;
924
- if (!reconnectTimer) {
925
- console.log('[TikTok] Scheduling reconnect in 30s...');
926
- reconnectTimer = setTimeout(() => {
927
- reconnectTimer = null;
928
- startRadar();
929
- }, 30000);
930
  }
931
  });
932
 
933
- connection.on(ControlEvent.STREAM_END, ({ action }) => {
934
  updateActivity();
935
- isConnected = false;
936
- isLive = false;
937
- notifyStreamEnd();
938
- console.log('[Stream] Stream ended. Will check again in 60s...');
939
- reconnectTimer = setTimeout(startRadar, 60000);
940
- });
941
-
942
- connection.on(ControlEvent.ERROR, (err) => {
943
- console.error('[TikTok] Error:', err);
944
- if (err && err.message) console.error('[TikTok] Error message:', err.message);
945
- });
946
-
947
- connection.on(WebcastEvent.ROOM_USER, (data) => {
948
- updateActivity();
949
- try {
950
- const viewers = data.viewerCount || 0;
951
- if (viewers > maxViewers) maxViewers = viewers;
952
- viewerHistory.push({ time: Date.now(), viewers });
953
- if (viewerHistory.length > 200) viewerHistory.shift();
954
- } catch (err) { console.error('[roomUser] Error:', err); }
955
- });
956
-
957
- connection.on(WebcastEvent.LIKE, (data) => {
958
- updateActivity();
959
- try {
960
- const user = data.user || {};
961
- const likes = data.likeCount || data.totalLikeCount || 0;
962
- const userId = user.userId || user.id || 'unknown';
963
- const nickname = user.nickname || user.displayId || 'مجهول';
964
- notifyLike(nickname, likes, userId);
965
- } catch (err) { console.error('[like] Error:', err); }
966
- });
967
-
968
- connection.on(WebcastEvent.FOLLOW, (data) => {
969
- updateActivity();
970
- try {
971
- const user = data.user || {};
972
- const userId = user.userId || user.id || 'unknown';
973
- const nickname = user.nickname || user.displayId || 'مجهول';
974
- notifyFollow(nickname, userId);
975
- } catch (err) { console.error('[follow] Error:', err); }
976
- });
977
-
978
- connection.on(WebcastEvent.SHARE, (data) => {
979
- updateActivity();
980
- try {
981
- const user = data.user || {};
982
- const userId = user.userId || user.id || 'unknown';
983
- const nickname = user.nickname || user.displayId || 'مجهول';
984
- notifyShare(nickname, userId);
985
- } catch (err) { console.error('[share] Error:', err); }
986
- });
987
-
988
- connection.on(WebcastEvent.CHAT, (data) => {
989
- updateActivity();
990
- handleChat(data);
991
- });
992
-
993
- connection.on(WebcastEvent.MEMBER, (data) => {
994
- updateActivity();
995
- handleMember(data);
996
- });
997
-
998
- connection.on(WebcastEvent.GIFT, (data) => {
999
- updateActivity();
1000
- try {
1001
- const user = data.user || {};
1002
- const userId = user.userId || user.id || 'unknown';
1003
- const nickname = user.nickname || user.displayId || 'مجهول';
1004
- const giftName = data.giftName || 'Gift';
1005
- const diamondCount = data.diamondCount || 0;
1006
- const repeatCount = data.repeatCount || 1;
1007
- const giftType = data.giftType;
1008
- const repeatEnd = data.repeatEnd;
1009
-
1010
- console.log(`[Gift] name="${giftName}" type=${giftType} repeatEnd=${repeatEnd} diamonds=${diamondCount}×${repeatCount} from=${nickname}`);
1011
-
1012
- if (giftType === 1 && !repeatEnd) {
1013
- console.log('[Gift] Streak in progress, skipping...');
1014
- return;
1015
- }
1016
-
1017
- const totalCost = diamondCount * repeatCount;
1018
- notifyGift(nickname, giftName, diamondCount, repeatCount, totalCost, userId);
1019
- } catch (err) { console.error('[gift] Error:', err); }
1020
- });
1021
-
1022
- connection.on(WebcastEvent.ENVELOPE, (data) => {
1023
- updateActivity();
1024
- console.log('[Envelope] raw event:', JSON.stringify(data).substring(0, 500));
1025
- try {
1026
- const user = data.user || {};
1027
- const userId = user.userId || user.id || 'unknown';
1028
- const nickname = user.nickname || user.displayId || 'مجهول';
1029
- handleEnvelope({
1030
- userId: userId,
1031
- nickname: nickname,
1032
- envelopeId: data.envelopeId || data.msgId || `env-${Date.now()}`,
1033
- });
1034
- } catch (err) { console.error('[envelope event] Error:', err); }
1035
- });
1036
-
1037
- connection.on(WebcastEvent.SUBSCRIBE, (data) => {
1038
- updateActivity();
1039
- console.log('[Subscribe] raw event:', JSON.stringify(data).substring(0, 500));
1040
- try {
1041
- const user = data.user || {};
1042
- const userId = user.userId || user.id || 'unknown';
1043
- const nickname = user.nickname || user.displayId || 'مجهول';
1044
- handleCoinPurse({
1045
- userId: userId,
1046
- nickname: nickname,
1047
- coins: 100,
1048
- purseId: data.msgId || `sub-${Date.now()}`,
1049
- });
1050
- sendTelegram(`⭐ <b>${escapeHtml(nickname)}</b> اشترك في القناة! 🎉`, null, null, 'HTML', null, true);
1051
- } catch (err) { console.error('[subscribe event] Error:', err); }
1052
  });
1053
 
1054
- connection.on(WebcastEvent.LINK_MIC_BATTLE, (data) => {
1055
- updateActivity();
1056
- console.log('[Battle] linkMicBattle:', JSON.stringify(data).substring(0, 300));
1057
- handleBattleStart(data);
1058
  });
1059
 
1060
- connection.on(WebcastEvent.LINK_MIC_ARMIES, (data) => {
1061
- updateActivity();
1062
- console.log('[Battle] linkMicArmies:', JSON.stringify(data).substring(0, 300));
1063
- handleBattleUpdate(data);
1064
- });
1065
  }
1066
 
1067
- // ═══════════════════════════════════════════════════════════════════════
1068
- // MAIN CONTROL
1069
- // ═══════════════════════════════════════════════════════════════════════
1070
-
1071
  async function startRadar() {
1072
- if (isConnected) return;
1073
-
1074
- console.log(`\n[Radar] 🔎 Searching for @${CONFIG.TIKTOK_USERNAME}...`);
1075
- reconnectAttempt++;
1076
-
1077
- if (reconnectAttempt === 1) {
1078
- maxViewers = 0; totalLikes = 0; totalShares = 0; totalGifts = 0;
1079
- totalFollows = 0; totalComments = 0; totalEnvelopes = 0; totalCoinsGiven = 0;
1080
- giftersMap = {}; likersMap = {}; sharersMap = {}; followersMap = {};
1081
- chattersMap = {}; moderatorsMap = {}; envelopeWinnersMap = {}; coinPurseWinnersMap = {};
1082
- topChatMessages = [];
1083
- viewerHistory = [];
1084
- pkActive = false;
1085
- pkInfo = { opponentName: '', opponentUserId: '', ourScore: 0, theirScore: 0, startTime: null, pkGifts: {} };
1086
- cooldowns.chat.clear(); cooldowns.gift.clear(); cooldowns.like.clear();
1087
- cooldowns.follow.clear(); cooldowns.share.clear(); cooldowns.envelope.clear();
1088
- cooldowns.coinPurse.clear(); cooldowns.moderator.clear();
1089
- }
1090
-
1091
  try {
1092
  tiktokConnection = createConnection();
1093
  setupEvents(tiktokConnection);
1094
-
1095
- console.log('[Radar] Connecting to TikTok...');
1096
  await tiktokConnection.connect();
1097
-
1098
  } catch (err) {
1099
- console.error('[Radar] ❌ Connection failed');
1100
- let errorMessage = 'Unknown error';
1101
- if (err) {
1102
- if (typeof err === 'string') errorMessage = err;
1103
- else if (err.message) errorMessage = err.message;
1104
- else if (err.toString) errorMessage = err.toString();
1105
- }
1106
- console.error('[Radar] Error:', errorMessage);
1107
-
1108
- isConnected = false;
1109
- isLive = false;
1110
-
1111
- const now = Date.now();
1112
- const needsSessionId = errorMessage.toLowerCase().includes('session') || errorMessage.toLowerCase().includes('cookie');
1113
- const shouldNotify = reconnectAttempt === 1 || (now - lastReconnectNotify) > 600000;
1114
-
1115
- if (shouldNotify) {
1116
- lastReconnectNotify = now;
1117
- if (needsSessionId) {
1118
- const sessionMsg = `⚠️ <b>مطلوب تحديث الكوكيز</b>\n━━━━━━━━━━━━━━━━━━━\n👤 <b>المُضيف:</b> ${CONFIG.TIKTOK_USERNAME}\n\n❌ خطأ: TikTok يتطلب sessionId + tt-target-idc\n\n📋 <b>كيف تحصل عليهما:</b>\n1️⃣ افتح TikTok في المتصفح (Chrome)\n2️⃣ سجل الدخول بحسابك\n3️⃣ اضغط F12 → Application → Cookies\n4️⃣ انسخ القيم من:\n • sessionid\n • tt-target-idc (مثال: alisg, useast1a)\n5️⃣ أضفهما في Settings → Variables\n\n⏰ سأحاول الاتصال تلقائياً...`;
1119
- await sendTelegram(sessionMsg, null, getDisconnectedButtons(), 'HTML', null, true);
1120
- } else {
1121
- if (reconnectAttempt === 1) {
1122
- const failMsg = `🔎 <b>البحث عن البث...</b>\n━━━━━━━━━━━━━━━━━━━\n👤 <b>المُضيف:</b> ${CONFIG.TIKTOK_USERNAME}\n⏰ <b>الوقت:</b> ${getBaghdadTime()}\n🔄 <b>الحالة:</b> البث غير متاح حالياً\n\nسأراقب البث وأعلمك حال بدئه...`;
1123
- await sendTelegram(failMsg, null, getDisconnectedButtons(), 'HTML', null, true);
1124
- }
1125
- }
1126
- }
1127
-
1128
- reconnectTimer = setTimeout(startRadar, 60000);
1129
  }
1130
  }
1131
 
1132
- function disconnectRadar() {
1133
- isConnected = false;
1134
- isLive = false;
1135
- if (tiktokConnection) {
1136
- try { tiktokConnection.disconnect(); } catch (e) {}
1137
- tiktokConnection = null;
1138
- }
1139
- if (reconnectTimer) clearTimeout(reconnectTimer);
1140
- if (reportInterval) clearInterval(reportInterval);
1141
- }
1142
-
1143
- function startPeriodicReports() {
1144
- if (reportInterval) clearInterval(reportInterval);
1145
- reportInterval = setInterval(() => {
1146
- if (!isConnected || !isLive) {
1147
- clearInterval(reportInterval);
1148
- return;
1149
- }
1150
- const now = new Date();
1151
- const minutesSinceLastReport = (now - lastReportTime) / 60000;
1152
- if (minutesSinceLastReport >= CONFIG.REPORT_INTERVAL_MINUTES) {
1153
- sendPeriodicReport();
1154
- }
1155
- }, 60000);
1156
- }
1157
-
1158
- // ═══════════════════════════════════════════════════════════════════════
1159
- // HTTP SERVER & MAIN ENTRY
1160
- // ═══════════════════════════════════════════════════════════════════════
1161
-
1162
- const server = http.createServer((req, res) => {
1163
- res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
1164
- const status = isLive ? '🔴 LIVE' : isConnected ? '🟡 CONNECTING' : '⚪ WAITING';
1165
- const pkStatus = pkActive ? ' | ⚔️ PK' : '';
1166
- res.end(`TikTok Radar Bot v6.3 | ${status}${pkStatus} | ${getBaghdadTime()} | @${CONFIG.TIKTOK_USERNAME}`);
1167
- });
1168
-
1169
- const PORT = process.env.PORT || 7860;
1170
- server.listen(PORT, '0.0.0.0', () => {
1171
- console.log(`
1172
- ╔══════════════════════════════════════════════════════════════╗
1173
- ║ TikTok Radar Pro - Telegram Bot v6.3 (v2.0+ Fixed) ║
1174
- ║ 📡 TikTok: @${CONFIG.TIKTOK_USERNAME.padEnd(45, ' ')}║
1175
- ║ 📢 Channel: ${CONFIG.TELEGRAM_CHAT_ID.padEnd(44, ' ')}║
1176
- ║ 🌐 Proxy: ${(CONFIG.PROXY_URL || 'Direct API').padEnd(46, ' ')}║
1177
- ║ 🖥 Server: http://0.0.0.0:${PORT.toString().padEnd(35, ' ')}║
1178
- ╚══════════════════════════════════════════════════════════════╝
1179
- `);
1180
-
1181
- pollCallbacks();
1182
- startRadar();
1183
- updateActivity();
1184
- });
1185
-
1186
- // ═══════════════════════════════════════════════════════════════════════
1187
- // ERROR HANDLING & WATCHDOG
1188
- // ═══════════════════════════════════════════════════════════════════════
1189
-
1190
- process.on('uncaughtException', (err) => {
1191
- console.error('[FATAL] Uncaught Exception:', err);
1192
- });
1193
 
1194
- process.on('unhandledRejection', (reason, promise) => {
1195
- console.error('[FATAL] Unhandled Rejection at:', promise, 'reason:', reason);
1196
- });
1197
-
1198
- setInterval(() => {
1199
- const inactiveTime = Date.now() - lastActivity;
1200
- console.log(`[Watchdog] Inactive for ${Math.floor(inactiveTime / 1000)}s | Connected: ${isConnected} | Live: ${isLive}`);
1201
-
1202
- if (!isConnected && inactiveTime > 120000) {
1203
- console.log('[Watchdog] Bot disconnected for too long, reconnecting...');
1204
- disconnectRadar();
1205
- startRadar();
1206
- }
1207
-
1208
- if (isConnected && !isLive && inactiveTime > 180000) {
1209
- console.log('[Watchdog] Connected but stream not live, reconnecting...');
1210
- disconnectRadar();
1211
- startRadar();
1212
- }
1213
- }, 30000);
1214
-
1215
- setInterval(() => {
1216
- http.get(`http://localhost:${PORT}`, (res) => { res.resume(); updateActivity(); }).on('error', () => {});
1217
- }, 60000);
1218
-
1219
- process.on('SIGINT', async () => {
1220
- console.log('\n[Bot] Shutting down gracefully...');
1221
- disconnectRadar();
1222
- try {
1223
- await sendTelegram(`💤 البوت توقف مؤقتاً...\n⏰ ${getBaghdadTime()}`, null, null, 'HTML', null, true);
1224
- } catch (e) {}
1225
- process.exit(0);
1226
- });
 
1
  /**
2
  * ╔══════════════════════════════════════════════════════════════════════╗
3
+ * ║ TikTok Radar Pro - Telegram Bot v6.4 (Fixed for v2.1+) ║
4
+ * ║ Based on tiktok-live-connector v2.1+ API ║
5
  * ╚══════════════════════════════════════════════════════════════════════╝
6
  */
7
 
 
9
  const axios = require('axios');
10
  const http = require('http');
11
 
12
+ // الإعدادات
 
 
 
13
  function cleanEnv(val, fallback) {
14
  if (!val) return fallback;
15
  return val.toString().trim().split('\n')[0].trim();
 
30
  SPAM_KEYWORDS: ['spam', 'scam', 'fake', 'click here', 'free money', 'earn now', 'www.', '.com'],
31
  };
32
 
33
+ // متغيرات الحالة
 
 
 
 
 
 
 
 
 
 
 
 
34
  let isConnected = false;
35
  let isLive = false;
36
  let maxViewers = 0;
 
58
  let lastMessageId = null;
59
  let reconnectAttempt = 0;
60
  let lastReconnectNotify = 0;
61
+ let lastActivity = Date.now();
62
 
63
  const cooldowns = {
64
  chat: new Map(), gift: new Map(), like: new Map(), follow: new Map(),
 
66
  };
67
 
68
  let pkActive = false;
69
+ let pkInfo = { opponentName: '', opponentUserId: '', ourScore: 0, theirScore: 0, startTime: null, pkGifts: {} };
 
 
 
 
70
  let viewerHistory = [];
71
 
72
+ // دالات مساعدة
73
+ function updateActivity() { lastActivity = Date.now(); }
74
+ function formatK(num) {
75
+ if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
76
+ if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
77
+ return num.toString();
 
 
78
  }
79
+ function getBaghdadTime() {
80
+ return new Intl.DateTimeFormat('ar-IQ', { timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true }).format(new Date());
 
 
 
81
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  function escapeHtml(text) {
83
  if (!text) return '';
84
  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
85
  }
86
 
87
+ // دالة التحقق من التبريد (Cooldown) - تم إصلاحها بالكامل
88
  function isOnCooldown(type, key, duration) {
89
  const now = Date.now();
90
  const last = cooldowns[type].get(key);
 
93
  return false;
94
  }
95
 
96
+ // إرسال لتيليجرام
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  async function sendTelegram(text, photoUrl = null, buttons = null, parseMode = 'HTML', editMessageId = null, silent = false) {
98
  updateActivity();
99
+ if (!CONFIG.TELEGRAM_TOKEN || !CONFIG.TELEGRAM_CHAT_ID) return null;
100
+ const baseUrl = `https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  try {
102
+ let payload = { chat_id: CONFIG.TELEGRAM_CHAT_ID, parse_mode: parseMode, disable_web_page_preview: true, disable_notification: silent };
103
+ if (buttons) payload.reply_markup = { inline_keyboard: buttons };
104
+ let response;
105
+ if (editMessageId) { payload.message_id = editMessageId; payload.text = text; response = await axios.post(`${baseUrl}/editMessageText`, payload); }
106
+ else if (photoUrl) { payload.photo = photoUrl; payload.caption = text; response = await axios.post(`${baseUrl}/sendPhoto`, payload); }
107
+ else { payload.text = text; response = await axios.post(`${baseUrl}/sendMessage`, payload); }
108
+ return response.data;
109
+ } catch (e) { console.error(`[Telegram] Error:`, e.message); return null; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  }
111
 
112
+ // إنشاء الاتصال (نسخة 2.1+)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  function createConnection() {
114
+ const options = {
115
+ processInitialData: true,
116
+ enableExtendedGiftInfo: true,
117
+ webClientParams: { app_language: 'ar-IQ', device_platform: 'web' },
118
+ };
119
+ if (CONFIG.SESSION_ID) {
120
+ options.sessionId = CONFIG.SESSION_ID;
121
+ options.ttTargetIdc = CONFIG.TT_TARGET_IDC || 'alisg';
122
+ options.authenticateWs = true;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  }
124
+ return new TikTokLiveConnection(CONFIG.TIKTOK_USERNAME, options);
125
  }
126
 
127
+ // معالجة الأحداث
128
+ function setupEvents(conn) {
129
+ conn.on(ControlEvent.CONNECTED, (state) => {
130
+ console.log('[TikTok] Connected!');
131
+ isConnected = true; isLive = true; startTime = new Date(); lastReportTime = new Date();
132
+ sendTelegram(`📡 البث بدأ! @${CONFIG.TIKTOK_USERNAME}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  });
134
 
135
+ conn.on(WebcastEvent.CHAT, (data) => {
136
  updateActivity();
137
+ const nickname = data.user?.nickname || data.user?.uniqueId || 'مجهول';
138
+ if (!isOnCooldown('chat', data.user?.uniqueId, 4000)) {
139
+ console.log(`[Chat] ${nickname}: ${data.comment}`);
 
 
 
 
 
 
140
  }
141
  });
142
 
143
+ conn.on(WebcastEvent.GIFT, (data) => {
144
  updateActivity();
145
+ if (data.giftType === 1 && !data.repeatEnd) return; // تخطي الهدايا المتتالية حتى تنتهي
146
+ const totalCost = data.diamondCount * data.repeatCount;
147
+ totalGifts++;
148
+ const nickname = data.user?.nickname || data.user?.uniqueId || 'مجهول';
149
+ sendTelegram(`🎁 ${nickname} أرسل ${data.giftName} (x${data.repeatCount}) \n💎 ${totalCost} ماسة`, null, null, 'HTML', null, totalCost < 100);
150
+ });
151
+
152
+ conn.on(WebcastEvent.LIKE, (data) => {
153
+ totalLikes += data.likeCount;
154
+ if (data.likeCount > 50) {
155
+ const nickname = data.user?.nickname || 'مجهول';
156
+ sendTelegram(`❤️ ${nickname} أرسل ${data.likeCount} إعجاب!`, null, null, 'HTML', null, true);
157
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  });
159
 
160
+ conn.on(WebcastEvent.STREAM_END, () => {
161
+ isConnected = false; isLive = false;
162
+ sendTelegram(`🔴 انتهى البث المباشر.`);
 
163
  });
164
 
165
+ conn.on(ControlEvent.ERROR, (err) => console.error('[TikTok Error]', err));
 
 
 
 
166
  }
167
 
 
 
 
 
168
  async function startRadar() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
  try {
170
  tiktokConnection = createConnection();
171
  setupEvents(tiktokConnection);
 
 
172
  await tiktokConnection.connect();
 
173
  } catch (err) {
174
+ console.error('[Radar] Failed:', err.message);
175
+ setTimeout(startRadar, 30000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  }
177
  }
178
 
179
+ // سيرفر بسيط للبقاء حياً
180
+ http.createServer((req, res) => {
181
+ res.writeHead(200);
182
+ res.end(`TikTok Bot Active | @${CONFIG.TIKTOK_USERNAME}`);
183
+ }).listen(process.env.PORT || 7860);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
+ startRadar();