Reooiq commited on
Commit
92be57e
·
verified ·
1 Parent(s): 8f08c77

Delete bot.js

Browse files
Files changed (1) hide show
  1. bot.js +0 -1493
bot.js DELETED
@@ -1,1493 +0,0 @@
1
- /**
2
- * ╔══════════════════════════════════════════════════════════════════════════════╗
3
- * ║ ║
4
- * ║ 🎯 TikTok Radar Ultimate v11.0 - النسخة المحسّنة 🎯 ║
5
- * ║ ║
6
- * ║ ✅ أسماء الهدايا بالعربي • صناديق وحقائب مع الفائزين ║
7
- * ║ ✅ تعليقات مع أغلب الرسائل • حذف تلقائي للرسائل السابقة ║
8
- * ║ ✅ تخزين كل 50 دقيقة • تغيير المذيع من تليكرام • قناة ثانية ║
9
- * ║ ║
10
- * ╚══════════════════════════════════════════════════════════════════════════════╝
11
- */
12
-
13
- const http = require('http');
14
- const axios = require('axios');
15
-
16
- process.env.WHITELIST_AUTHENTICATED_SESSION_ID_HOST = 'tiktok.eulerstream.com';
17
- const PORT = process.env.PORT || 7860;
18
-
19
- // ═══════════════════════ CONFIG ═══════════════════════
20
- const CONFIG = {
21
- TIKTOK_USERNAME: (process.env.TIKTOK_USERNAME || 'a200_89').trim(),
22
- SESSION_ID: (process.env.SESSION_ID || '').trim(),
23
- TT_TARGET_IDC: (process.env.TT_TARGET_IDC || 'alisg').trim(),
24
- TELEGRAM_TOKEN: (process.env.TELEGRAM_TOKEN || '').trim(),
25
- TELEGRAM_CHAT_ID: (process.env.TELEGRAM_CHAT_ID || '').trim(),
26
- TELEGRAM_CHAT_ID_2: (process.env.TELEGRAM_CHAT_ID_2 || '').trim(),
27
- PROXY_URL: (process.env.PROXY_URL || '').trim().replace(/\/$/, ''),
28
- SIGN_API_KEY: (process.env.SIGN_API_KEY || '').trim(),
29
- REPORT_INTERVAL: parseInt(process.env.REPORT_INTERVAL || '10'),
30
- };
31
-
32
- // ═══════════════════════ أسماء الهدايا بالعربي ═══════════════════════
33
- const GIFT_NAMES_AR = {
34
- 'Rose': 'وردة 🌹', 'rose': 'وردة 🌹', 'Finger Heart': 'قلب بالإصبع 🤞',
35
- 'GG': 'جي جي 🎮', 'Ice Cream Cone': 'آيس كريم 🍦', 'Doughnut': 'دونات 🍩',
36
- 'TikTok': 'تيك توك ♪', 'Love you': 'أحبك 💕', 'Confetti': 'قصاصات ملونة 🎊',
37
- 'Hand Heart': 'قلب باليد 💗', 'Heart Me': 'قلبني ❤️', 'Tiny Diny': 'تايني ديني 🐣',
38
- 'Cheer You Up': 'ابتسم 😊', 'Sunglasses': 'نظارات شمسية 😎', 'Hearts': 'قلوب 💕',
39
- 'Butterfly': 'فراشة 🦋', 'Star': 'نجمة ⭐', 'Galaxy': 'مجرة 🌌',
40
- 'Universe': 'كون 🌍', 'Lion': 'أسد 🦁', 'Interstellar': 'بين النجوم ✨',
41
- 'Concert': 'حفلة 🎵', 'Garland': 'إكليل 💐', 'Superstar': 'سوبر ستار ⭐',
42
- 'Drama Queen': 'دراما كوين 👑', 'Cap': 'قبعة 🧢', 'Perfume': 'عطر 💫',
43
- 'Mic': 'مايك 🎤', 'Paper Crane': 'طائر ورقي 🦢', 'Little Crown': 'تاج صغير 👑',
44
- 'Lollipop': 'مصاصة 🍭', 'Lucky Cat': 'قطة الحظ 🐱', 'Love': 'حب ❤️',
45
- 'Horseshoe': 'حدوة حصان 🐴', 'Gift Box': 'صندوق هدية 🎁', 'Roses': 'ورود 🌹',
46
- 'Bear': 'دب 🐻', 'Teddy Bear': 'دبدوب 🧸', 'Wish': 'أمنية 🌠',
47
- 'Finger': 'إصبع ☝️', 'Sending Strength': 'قوة 💪', 'Hot Air Balloon': 'منطاد 🎈',
48
- 'Gold Mine': 'منجم ذهب ⛏️', 'Thumbs Up': 'إعجاب 👍', 'Applause': 'تصفيق 👏',
49
- 'Disco Ball': 'كرة ديسكو 🪩', 'Money Gun': 'مسدس فلوس 💰', 'Gem Gun': 'مسدس ماسات 💎',
50
- 'Race Car': 'سيارة سباق 🏎️', 'Sports Car': 'سيارة رياضية 🚗', 'Gaming Chair': 'كرسي قيمنق 🪑',
51
- 'Jet': 'طائرة ✈️', 'Private Jet': 'طائرة خاصة ✈️', 'Yacht': 'يخت 🛥️',
52
- 'Castle': 'قلعة 🏰', 'Kingdom': 'مملكة 👑', 'Crown': 'تاج 👑',
53
- 'Diamond': 'ماسة 💎', 'Lightning Bolt': 'صاعقة ⚡', 'Phoenix': 'طائر الفينيق 🔥',
54
- 'Dragon': 'تنين 🐉', 'Elephant': 'فيل 🐘', 'Corgi': 'كلب كورجي 🐕',
55
- 'Duck': 'بطة 🦆', 'Cat': 'قطة 🐱', 'Panda': 'باندا 🐼',
56
- 'Penguin': 'بطريق 🐧', 'Whale': 'حوت 🐋', 'Dolphin': 'دلفين 🐬',
57
- 'Shark': 'قرش 🦈', 'Unicorn': 'يونيكورن 🦄', 'Pearl Necklace': 'عقد لؤلؤ 📿',
58
- 'Ring': 'خاتم 💍', 'Couple Ring': 'خاتم زوجين 💍', 'Wedding Ring': 'خاتم زواج 💍',
59
- 'Bracelet': 'سوار ⌚', 'Watch': 'ساع�� ⌚', 'Flower': 'زهرة 🌸',
60
- 'Bouquet': 'باقة ورد 💐', 'Cake': 'كيكة 🎂', 'Pizza': 'بيتزا 🍕',
61
- 'Popcorn': 'فشار 🍿', 'Coffee': 'قهوة ☕', 'Boba Tea': 'شاي بوبا 🧋',
62
- 'Champagne': 'شامبانيا 🥂', 'Cocktail': 'كوكتيل 🍹', 'Fireworks': 'ألعاب نارية 🎆',
63
- 'Rocket': 'صاروخ 🚀', 'UFO': 'طبق طائر 🛸', 'Moon': 'قمر 🌙',
64
- 'Sun': 'شمس ☀️', 'Rainbow': 'قوس قزح 🌈', 'Snowman': 'رجل ثلج ⛄',
65
- 'Cherry Blossom': 'زهر الكرز 🌸', 'Lock & Key': 'قفل ومفتاح 🔐',
66
- 'Money Tree': 'شجرة فلوس 🌳', 'Lucky Box': 'صندوق الحظ 🎁',
67
- 'Treasure Chest': 'صندوق كنز 📦', 'Gold Coin': 'عملة ذهبية 🪙',
68
- 'Coin Bag': 'حقيبة عملات 💰', 'Scepter': 'صولجان 🏆', 'Magic Wand': 'عصا سحرية 🪄',
69
- 'Trophy': 'كأس 🏆', 'Medal': 'ميدالية 🏅', 'Champion': 'بطل 🏆',
70
- 'First Place': 'المركز الأول 🥇', 'Second Place': 'المركز الثاني 🥈',
71
- 'Third Place': 'المركز الثالث 🥉', 'Goat': 'الأفضل 🐐',
72
- 'Guitar': 'جيتار 🎸', 'Piano': 'بيانو 🎹', 'Drum': 'طبل 🥁',
73
- 'Headphones': 'سماعات 🎧', 'Microphone': 'مايكروفون 🎤',
74
- 'Camera': 'كاميرا 📷', 'Movie': 'فلم 🎬', 'Ticket': 'تذكرة 🎟️',
75
- 'Balloon': 'بالون 🎈', 'Party': 'حفلة 🥳', 'Birthday': 'عيد ميلاد 🎂',
76
- 'Graduation': 'تخرج 🎓', 'Coin': 'عملة 🪙', 'Money Bag': 'كيس نقود 💰',
77
- 'Dollar': 'دولار 💵', 'Credit Card': 'بطاقة 💳', 'Gem Stone': 'حجر كريم 💎',
78
- 'Pearl': 'لؤلؤة 🫧', 'Leaf': 'ورقة شجر 🍃', 'Clover': 'برسيم 🍀',
79
- 'Sunflower': 'عباد الشمس 🌻', 'Lotus': 'لوتس 🪷', 'Hug': 'حضن 🤗',
80
- 'Kiss': 'قبلة 💋', 'Clap': 'تصفيق 👏', 'Pray': 'دعاء 🙏',
81
- 'Flex': 'عضلات 💪', 'Peace': 'سلام ✌️', 'OK': 'أوكي 👌',
82
- 'Fist': 'قبضة 👊', 'Handshake': 'مصافحة 🤝', 'Heart Eyes': 'عيون قلب 😍',
83
- };
84
-
85
- function getArabicGiftName(en) {
86
- if (!en) return 'هدية 🎁';
87
- if (GIFT_NAMES_AR[en]) return GIFT_NAMES_AR[en];
88
- const lower = en.toLowerCase();
89
- for (const [k, v] of Object.entries(GIFT_NAMES_AR)) {
90
- if (k.toLowerCase() === lower) return v;
91
- if (lower.includes(k.toLowerCase()) || k.toLowerCase().includes(lower)) return v;
92
- }
93
- return `${en} 🎁`;
94
- }
95
-
96
- // ═══════════════════════ STATE ═══════════════════════
97
- let isConnected = false, tiktokConnection = null;
98
- let totalGifts = 0, totalDiamonds = 0, totalLikes = 0, totalComments = 0;
99
- let totalFollows = 0, totalShares = 0, totalSuperFans = 0, totalQuestions = 0;
100
- let totalEnvelopes = 0, totalEmotes = 0;
101
- let maxViewers = 0, currentViewers = 0;
102
- let startTime = null;
103
-
104
- // Maps - الآن مع تخزين الرسائل والهدايا
105
- let giftersMap = {}; // { uid: { name, username, coins, count, gifts: [] } }
106
- let followersMap = {}; // { uid: { name, username, time } }
107
- let chattersMap = {}; // { uid: { name, username, count, messages: [] } }
108
- let sharersMap = {}; // { uid: { name, username, count } }
109
- let likersMap = {}; // { uid: { name, username, count } }
110
-
111
- // الصناديق والحقائب مع الفائزين
112
- let envelopeWinners = []; // { type, sender, senderUsername, diamonds, peopleCount, winners: [{name, username, coins}], time }
113
-
114
- let questionsArr = [], pinnedMessages = [];
115
- let reconnectTimer = null, reportInterval = null, flushInterval = null;
116
- let roomTitle = '';
117
-
118
- // رسائل مرسلة للحذف
119
- let lastMenuMsgId = null;
120
- let lastReportMsgId = null;
121
- let lastDetailMsgIds = [];
122
-
123
- // PK
124
- let pkActive = false, pkInfo = {
125
- battleId: '', participantDetails: [], ourScore: 0, theirScore: 0,
126
- startTime: null, pkGifts: {},
127
- };
128
-
129
- // ═══════════════════════ UTILS ═══════════════════════
130
- function esc(t) { return t ? String(t).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;') : ''; }
131
- function formatK(n) { n = Number(n) || 0; return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'K' : n.toString(); }
132
- function dur(s) { if (!s) return '00:00:00'; const d = Math.floor((Date.now() - s.getTime()) / 1000); return `${String(Math.floor(d / 3600)).padStart(2, '0')}:${String(Math.floor((d % 3600) / 60)).padStart(2, '0')}:${String(d % 60).padStart(2, '0')}`; }
133
- function getTime() { return new Date().toLocaleString('ar-IQ', { timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit', hour12: true }); }
134
- function getDate() { return new Date().toLocaleString('ar-IQ', { timeZone: 'Asia/Baghdad', year: 'numeric', month: '2-digit', day: '2-digit' }); }
135
- const LIVE = () => `https://www.tiktok.com/@${CONFIG.TIKTOK_USERNAME}/live`;
136
-
137
- const medals = ['🥇', '🥈', '🥉', '🏅', '🎖️', '⭐', '✨', '💫', '🌟', '⚡'];
138
- const ranks = ['الأول', 'الثاني', 'الثالث', 'الرابع', 'الخامس', 'السادس', 'السابع', 'الثامن', 'التاسع', 'العاشر'];
139
-
140
- // ═══════════════════════ ENVELOPE HELPERS ═══════════════════════
141
- function extractWinners(data) {
142
- const winners = [];
143
- if (!data) return winners;
144
-
145
- // البحث في كل المواقع الممكنة للفائزين
146
- const possibleLists = [
147
- data.envelopeGrabUserList,
148
- data.grabUserList,
149
- data.winnerList,
150
- data.winners,
151
- data.envelopeGrabRecordList,
152
- data.grabRecordList,
153
- data.userList,
154
- data.envelopeInfo?.envelopeGrabUserList,
155
- data.envelopeInfo?.grabUserList,
156
- data.envelopeInfo?.winners,
157
- data.treasureBoxData?.winners,
158
- data.goodyBagData?.winners,
159
- ];
160
-
161
- for (const list of possibleLists) {
162
- if (Array.isArray(list) && list.length > 0) {
163
- for (const w of list) {
164
- if (w) {
165
- winners.push({
166
- name: w.nickname || w.nickName || w.userName || w.name || w.uniqueId || w.unique_id || '?',
167
- username: w.uniqueId || w.unique_id || w.userId || '',
168
- coins: w.diamondCount || w.coinCount || w.coins || w.grabDiamond || w.amount || w.value || 0,
169
- });
170
- }
171
- }
172
- break; // توقف عند إيجاد قائمة
173
- }
174
- }
175
-
176
- return winners;
177
- }
178
-
179
- function updateLastEnvelopeWithWinners(winners) {
180
- if (winners.length === 0) return;
181
-
182
- console.log(`[📦 WINNERS FOUND!] ${winners.length} winners:`, winners.map(w => `${w.name}(${w.coins})`).join(', '));
183
-
184
- // تحديث آخر صندوق بالفائزين
185
- if (envelopeWinners.length > 0) {
186
- const lastEnv = envelopeWinners[envelopeWinners.length - 1];
187
- // فقط إذا لم يكن لديه فائزين بالفعل
188
- if (!lastEnv.winners || lastEnv.winners.length === 0) {
189
- lastEnv.winners = winners;
190
-
191
- // إرسال تحديث بالفائزين
192
- const typeIcon = lastEnv.type === 'coinbag' ? '💰' : '📦';
193
- const typeName = lastEnv.type === 'coinbag' ? 'حقيبة العملات' : 'صندوق الكنز';
194
-
195
- const winnerText = winners.map((w, i) =>
196
- ` ${i + 1}. 👤 <b>${esc(w.name)}</b> ${w.username ? `<code>@${w.username}</code>` : ''}\n 🪙 حصل على: <b>${formatK(w.coins)}</b> عملة`
197
- ).join('\n');
198
-
199
- sendBoth(
200
- `🏆✨ <b>فائزين ${typeName}!</b>\n` +
201
- `━━━━━━━━━━━━━━━━━━━\n\n` +
202
- `👤 المرسل: <b>${esc(lastEnv.sender)}</b>\n\n` +
203
- winnerText
204
- );
205
- }
206
- }
207
- }
208
-
209
- // ═══════════════════════ FORMATTERS ═══════════════════════
210
- function fmtList(map, sortKey, emoji, unit, n = 10) {
211
- const items = Object.values(map).sort((a, b) => (b[sortKey] || 0) - (a[sortKey] || 0)).slice(0, n);
212
- if (!items.length) return ' ⏳ لا يوجد بيانات بعد';
213
- return items.map((x, i) => {
214
- const m = medals[i] || `${i + 1}.`;
215
- const rank = ranks[i] || `#${i + 1}`;
216
- const u = x.username ? `\n ┗ <code>@${x.username}</code>` : '';
217
- const val = formatK(x[sortKey] || 0);
218
- return `${m} <b>المركز ${rank}</b>\n ├ 👤 <b>${esc(x.name)}</b>: ${val} ${unit}${u}`;
219
- }).join('\n\n');
220
- }
221
-
222
- // تنسيق المعلقين مع عرض تعليقاتهم
223
- function fmtChatters(n = 10) {
224
- const items = Object.values(chattersMap).sort((a, b) => (b.count || 0) - (a.count || 0)).slice(0, n);
225
- if (!items.length) return ' ⏳ لا يوجد بيانات بعد';
226
- return items.map((x, i) => {
227
- const m = medals[i] || `${i + 1}.`;
228
- const rank = ranks[i] || `#${i + 1}`;
229
- const u = x.username ? `\n ┗ <code>@${x.username}</code>` : '';
230
- const lastMsgs = (x.messages || []).slice(-3).map(msg => ` 💬 <i>"${esc(msg.substring(0, 50))}${msg.length > 50 ? '...' : ''}"</i>`).join('\n');
231
- return `${m} <b>المركز ${rank}</b>\n ├ 👤 <b>${esc(x.name)}</b>: ${x.count} تعليق${u}\n${lastMsgs || ' 💬 <i>لا تعليقات محفوظة</i>'}`;
232
- }).join('\n\n');
233
- }
234
-
235
- // تنسيق الهدايا مع أسماء عربية
236
- function fmtGifters(n = 10) {
237
- const items = Object.values(giftersMap).sort((a, b) => (b.coins || 0) - (a.coins || 0)).slice(0, n);
238
- if (!items.length) return ' ⏳ لا يوجد بيانات بعد';
239
- return items.map((x, i) => {
240
- const m = medals[i] || `${i + 1}.`;
241
- const rank = ranks[i] || `#${i + 1}`;
242
- const u = x.username ? `\n ┗ <code>@${x.username}</code>` : '';
243
- const giftNames = (x.gifts || []).slice(-3).map(g => getArabicGiftName(g)).join(' • ');
244
- return `${m} <b>المركز ${rank}</b>\n ├ 👤 <b>${esc(x.name)}</b>: ${formatK(x.coins)} 💎 (${x.count} هدية)${u}\n └ آخر الهدايا: ${giftNames || 'غير محدد'}`;
245
- }).join('\n\n');
246
- }
247
-
248
- // تنسيق الصناديق والحقائب
249
- function fmtEnvelopes(n = 10) {
250
- if (!envelopeWinners.length) return ' ⏳ لا يوجد صناديق أو حقائب بعد';
251
- return envelopeWinners.slice(-n).reverse().map((env, i) => {
252
- const typeIcon = env.type === 'coinbag' ? '💰' : '📦';
253
- const typeName = env.type === 'coinbag' ? 'حقيبة عملات' : 'صندوق كنز';
254
- const winList = (env.winners || []).map((w, wi) =>
255
- ` ${wi + 1}. 👤 <b>${esc(w.name)}</b> ${w.username ? `<code>@${w.username}</code>` : ''} → 🪙 ${formatK(w.coins)} عملة`
256
- ).join('\n') || ' ⏳ لم يظهر الفائزين بعد';
257
- return `${typeIcon} <b>${typeName}</b> #${envelopeWinners.length - i}\n ├ المرسل: <b>${esc(env.sender)}</b> ${env.senderUsername ? `<code>@${env.senderUsername}</code>` : ''}\n ├ 💎 ${formatK(env.diamonds)} ماسة • 👥 ${env.peopleCount || '?'} شخص\n └ 🏆 الفائزين:\n${winList}`;
258
- }).join('\n\n');
259
- }
260
-
261
- // ═══════════════════════ TELEGRAM ═══════════════════════
262
- async function sendTg(text, silent = false, buttons = null, chatId = null) {
263
- const targetChatId = chatId || CONFIG.TELEGRAM_CHAT_ID;
264
- if (!CONFIG.TELEGRAM_TOKEN || !targetChatId) return null;
265
- const urls = [];
266
- if (CONFIG.PROXY_URL) urls.push(`${CONFIG.PROXY_URL}/bot${CONFIG.TELEGRAM_TOKEN}`);
267
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
268
- for (const base of urls) {
269
- try {
270
- const p = { chat_id: targetChatId, text, parse_mode: 'HTML', disable_notification: silent, disable_web_page_preview: true };
271
- if (buttons) p.reply_markup = { inline_keyboard: buttons };
272
- const r = await axios.post(`${base}/sendMessage`, p, { timeout: 15000 });
273
- if (r.data?.ok) return r.data;
274
- } catch (e) {}
275
- }
276
- return null;
277
- }
278
-
279
- async function deleteTgMsg(chatId, msgId) {
280
- if (!CONFIG.TELEGRAM_TOKEN || !chatId || !msgId) return;
281
- const urls = [];
282
- if (CONFIG.PROXY_URL) urls.push(`${CONFIG.PROXY_URL}/bot${CONFIG.TELEGRAM_TOKEN}`);
283
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
284
- for (const base of urls) {
285
- try {
286
- await axios.post(`${base}/deleteMessage`, { chat_id: chatId, message_id: msgId }, { timeout: 10000 });
287
- return;
288
- } catch (e) {}
289
- }
290
- }
291
-
292
- async function answerCallback(callbackId, text = '') {
293
- const urls = [];
294
- if (CONFIG.PROXY_URL) urls.push(`${CONFIG.PROXY_URL}/bot${CONFIG.TELEGRAM_TOKEN}`);
295
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
296
- for (const base of urls) {
297
- try {
298
- await axios.post(`${base}/answerCallbackQuery`, { callback_query_id: callbackId, text, show_alert: !!text }, { timeout: 10000 });
299
- return;
300
- } catch (e) {}
301
- }
302
- }
303
-
304
- // إرسال للقناتين
305
- async function sendBoth(text, silent = false, buttons = null) {
306
- const result = await sendTg(text, silent, buttons);
307
- if (CONFIG.TELEGRAM_CHAT_ID_2) {
308
- sendTg(text, silent, buttons, CONFIG.TELEGRAM_CHAT_ID_2).catch(() => {});
309
- }
310
- return result;
311
- }
312
-
313
- // إرسال مع حذف السابق
314
- async function sendAndReplace(text, silent, buttons, type) {
315
- // حذف الرسالة السابقة من نفس النوع
316
- if (type === 'menu' && lastMenuMsgId) {
317
- await deleteTgMsg(CONFIG.TELEGRAM_CHAT_ID, lastMenuMsgId);
318
- lastMenuMsgId = null;
319
- } else if (type === 'report' && lastReportMsgId) {
320
- await deleteTgMsg(CONFIG.TELEGRAM_CHAT_ID, lastReportMsgId);
321
- lastReportMsgId = null;
322
- } else if (type === 'detail') {
323
- for (const mid of lastDetailMsgIds) {
324
- await deleteTgMsg(CONFIG.TELEGRAM_CHAT_ID, mid);
325
- }
326
- lastDetailMsgIds = [];
327
- }
328
-
329
- const result = await sendTg(text, silent, buttons);
330
- if (result?.result?.message_id) {
331
- if (type === 'menu') lastMenuMsgId = result.result.message_id;
332
- else if (type === 'report') lastReportMsgId = result.result.message_id;
333
- else if (type === 'detail') lastDetailMsgIds.push(result.result.message_id);
334
- }
335
-
336
- // إرسال للقناة الثانية
337
- if (CONFIG.TELEGRAM_CHAT_ID_2) {
338
- sendTg(text, silent, buttons, CONFIG.TELEGRAM_CHAT_ID_2).catch(() => {});
339
- }
340
- return result;
341
- }
342
-
343
- // ═══════════════════════ TEXT COMMANDS ═══════════════════════
344
- async function handleTextCommand(msg) {
345
- const text = (msg.text || '').trim();
346
- const chatId = String(msg.chat?.id || '');
347
-
348
- // فقط المشرف
349
- if (chatId !== CONFIG.TELEGRAM_CHAT_ID) return;
350
-
351
- // تغيير المذيع: /change username أو /غير username
352
- if (text.startsWith('/change') || text.startsWith('/غير')) {
353
- const parts = text.split(/\s+/);
354
- const newUser = parts[1]?.replace('@', '').trim();
355
- if (newUser) {
356
- const oldUser = CONFIG.TIKTOK_USERNAME;
357
- CONFIG.TIKTOK_USERNAME = newUser;
358
-
359
- // فصل الاتصال الحالي
360
- if (tiktokConnection) {
361
- try { tiktokConnection.disconnect(); } catch (e) {}
362
- }
363
- isConnected = false;
364
-
365
- await sendTg(
366
- `🔄 <b>تم تغيير المذيع!</b>\n` +
367
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
368
- `❌ السابق: <code>@${oldUser}</code>\n` +
369
- `✅ الجديد: <code>@${newUser}</code>\n\n` +
370
- `⏳ جاري الاتصال بالبث الجديد...`
371
- );
372
-
373
- setTimeout(startBot, 3000);
374
- } else {
375
- await sendTg(`❌ استخدم: <code>/change username</code>\nأو: <code>/غير username</code>`);
376
- }
377
- return;
378
- }
379
-
380
- // تعيين قناة ثانية: /channel2 CHAT_ID أو /قناة CHAT_ID
381
- if (text.startsWith('/channel2') || text.startsWith('/قناة')) {
382
- const parts = text.split(/\s+/);
383
- const newChannelId = parts[1]?.trim();
384
- if (newChannelId) {
385
- CONFIG.TELEGRAM_CHAT_ID_2 = newChannelId;
386
- await sendTg(
387
- `📢 <b>تم تعيين القناة الثانية!</b>\n` +
388
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
389
- `✅ معرف القناة: <code>${newChannelId}</code>\n` +
390
- `📤 سيتم إرسال جميع التقارير لهذه القناة أيضاً`
391
- );
392
- } else {
393
- await sendTg(`❌ استخدم: <code>/channel2 CHAT_ID</code>\nأو: <code>/قناة CHAT_ID</code>`);
394
- }
395
- return;
396
- }
397
-
398
- // الحالة: /status أو /حالة
399
- if (text === '/status' || text === '/حالة') {
400
- await sendTg(
401
- `📡 <b>حالة البوت</b>\n` +
402
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
403
- `👤 المذيع: <code>@${CONFIG.TIKTOK_USERNAME}</code>\n` +
404
- `${isConnected ? '🟢 متصل' : '🔴 غير متصل'}\n` +
405
- `⏱ المدة: ${dur(startTime)}\n` +
406
- `📢 القناة الثانية: ${CONFIG.TELEGRAM_CHAT_ID_2 ? `<code>${CONFIG.TELEGRAM_CHAT_ID_2}</code>` : 'غير معيّنة'}\n\n` +
407
- `<b>الأوامر المتاحة:</b>\n` +
408
- `• <code>/change username</code> - تغيير المذيع\n` +
409
- `• <code>/channel2 CHAT_ID</code> - تعيين قناة ثانية\n` +
410
- `• <code>/status</code> - حالة البوت\n` +
411
- `• <code>/clear</code> - مسح الإحصائيات`
412
- );
413
- return;
414
- }
415
-
416
- // مسح الإحصائيات: /clear أو /مسح
417
- if (text === '/clear' || text === '/مسح') {
418
- clearStats();
419
- await sendTg(`✅ تم مسح جميع الإحصائيات`);
420
- return;
421
- }
422
- }
423
-
424
- // ═══════════════════════ CALLBACK HANDLER ═══════════════════════
425
- async function handleCallback(data) {
426
- const cb = data.data;
427
- const cbId = data.id;
428
-
429
- switch (cb) {
430
- case 'gifts':
431
- await sendAndReplace(
432
- `🎁 <b>━━━━ لوحة الهدايا ━━━━</b>\n` +
433
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
434
- `💎 إجمالي الماسات: <b>${formatK(totalDiamonds)}</b>\n` +
435
- `🎁 عدد الهدايا: <b>${totalGifts}</b>\n\n` +
436
- `━━━ 🏆 ترتيب الداعمين ━━━\n\n${fmtGifters(10)}`,
437
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
438
- );
439
- break;
440
-
441
- case 'followers':
442
- await sendAndReplace(
443
- `➕ <b>━━━━ المتابعين الجدد ━━━━</b>\n` +
444
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
445
- `📊 الإجمالي: <b>${totalFollows}</b> متابع جديد\n\n` +
446
- `━━━ 👥 آخر المتابعين ━━━\n\n${fmtList(followersMap, 'time', '➕', '')}`,
447
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
448
- );
449
- break;
450
-
451
- case 'likes':
452
- await sendAndReplace(
453
- `❤️ <b>━━━━ الإعجابات ━━━━</b>\n` +
454
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
455
- `📊 الإجمالي: <b>${formatK(totalLikes)}</b> إعجاب\n\n` +
456
- `━━━ 🔥 أكثر المعجبين ━━━\n\n${fmtList(likersMap, 'count', '❤️', '❤️')}`,
457
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
458
- );
459
- break;
460
-
461
- case 'chatters':
462
- await sendAndReplace(
463
- `💬 <b>━━━━ التعليقات ━━━━</b>\n` +
464
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
465
- `📊 الإجمالي: <b>${formatK(totalComments)}</b> تعليق\n\n` +
466
- `━━━ 🗣️ أنشط المعلقين ━━━\n\n${fmtChatters(10)}`,
467
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
468
- );
469
- break;
470
-
471
- case 'shares':
472
- await sendAndReplace(
473
- `↪️ <b>━━━━ المشاركات ━━━━</b>\n` +
474
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
475
- `📊 الإجمالي: <b>${totalShares}</b> مشاركة\n\n` +
476
- `━━━ 🔄 أكثر المشاركين ━━━\n\n${fmtList(sharersMap, 'count', '↪️', '↪️')}`,
477
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
478
- );
479
- break;
480
-
481
- case 'envelopes':
482
- await sendAndReplace(
483
- `📦💰 <b>━━━━ الصناديق والحقائب ━━━━</b>\n` +
484
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
485
- `📦 إجمالي الصناديق: <b>${totalEnvelopes}</b>\n\n` +
486
- `━━━ 🏆 آخر الصناديق والحقائب ━━━\n\n${fmtEnvelopes(10)}`,
487
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
488
- );
489
- break;
490
-
491
- case 'questions':
492
- const qList = questionsArr.slice(-10).reverse().map((q, i) =>
493
- `${i + 1}. <b>${esc(q.name)}</b>\n ❓ <i>"${esc(q.text)}"</i>`
494
- ).join('\n\n') || ' لا يوجد أسئلة';
495
- await sendAndReplace(
496
- `❓ <b>━━━━ الأسئلة ━━━━</b>\n` +
497
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
498
- `📊 الإجمالي: <b>${totalQuestions}</b> سؤال\n\n${qList}`,
499
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
500
- );
501
- break;
502
-
503
- case 'top_active':
504
- const activeMap = {};
505
- for (const [uid, g] of Object.entries(giftersMap)) {
506
- if (!activeMap[uid]) activeMap[uid] = { name: g.name, username: g.username, score: 0 };
507
- activeMap[uid].score += (g.coins || 0);
508
- }
509
- for (const [uid, c] of Object.entries(chattersMap)) {
510
- if (!activeMap[uid]) activeMap[uid] = { name: c.name, username: c.username, score: 0 };
511
- activeMap[uid].score += (c.count || 0) * 5;
512
- }
513
- for (const [uid, l] of Object.entries(likersMap)) {
514
- if (!activeMap[uid]) activeMap[uid] = { name: l.name, username: l.username, score: 0 };
515
- activeMap[uid].score += (l.count || 0);
516
- }
517
- for (const [uid, s] of Object.entries(sharersMap)) {
518
- if (!activeMap[uid]) activeMap[uid] = { name: s.name, username: s.username, score: 0 };
519
- activeMap[uid].score += (s.count || 0) * 20;
520
- }
521
- await sendAndReplace(
522
- `👑 <b>━━━━ أكثر المتفاعلين ━━━━</b>\n` +
523
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
524
- `<i>🧮 النقاط = ماسات + (تعليقات×5) + (لايكات) + (مشاركات×20)</i>\n\n` +
525
- `${fmtList(activeMap, 'score', '👑', 'نقطة')}`,
526
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
527
- );
528
- break;
529
-
530
- case 'stats':
531
- const avgV = maxViewers > 0 ? Math.round((currentViewers + maxViewers) / 2) : currentViewers;
532
- await sendAndReplace(
533
- `📈 <b>━━━━ إحصائيات مفصلة ━━━━</b>\n` +
534
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
535
- `⏱ المدة: <b>${dur(startTime)}</b>\n` +
536
- `📅 ${getDate()}\n\n` +
537
- `━━━ 👁 المشاهدين ━━━\n` +
538
- `الحاليين: <b>${formatK(currentViewers)}</b>\n` +
539
- `الأعلى: <b>${formatK(maxViewers)}</b>\n` +
540
- `المتوسط: ~<b>${formatK(avgV)}</b>\n\n` +
541
- `━━━ 📊 الأرقام ━━━\n` +
542
- `💎 الماسات: <b>${formatK(totalDiamonds)}</b>\n` +
543
- `🎁 الهدايا: <b>${totalGifts}</b>\n` +
544
- `❤️ الإعجابات: <b>${formatK(totalLikes)}</b>\n` +
545
- `💬 التعليقات: <b>${totalComments}</b>\n` +
546
- `➕ المتابعين: <b>${totalFollows}</b>\n` +
547
- `↪️ المشاركات: <b>${totalShares}</b>\n` +
548
- `⭐ سوبر فان: <b>${totalSuperFans}</b>\n` +
549
- `📦 الصناديق: <b>${totalEnvelopes}</b>\n` +
550
- `❓ الأسئلة: <b>${totalQuestions}</b>\n` +
551
- `😀 الإيموت: <b>${totalEmotes}</b>`,
552
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
553
- );
554
- break;
555
-
556
- case 'pk_status':
557
- if (pkActive) {
558
- const pkG = Object.values(pkInfo.pkGifts).sort((a, b) => b.coins - a.coins).slice(0, 5)
559
- .map((g, i) => `${medals[i]} <b>${esc(g.name)}</b>: ${formatK(g.coins)} 💎`).join('\n') || 'لا يوجد';
560
- await sendAndReplace(
561
- `⚔️ <b>━━━━ حالة PK ━━━━</b>\n` +
562
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
563
- `💎 النتيجة: <b>${formatK(pkInfo.ourScore)}</b>\n` +
564
- `⏱ المدة: ${dur(pkInfo.startTime)}\n\n` +
565
- `🏆 الداعمين:\n${pkG}`,
566
- true, [[{ text: '🔙 القائمة الرئيسية', callback_data: 'menu' }]], 'detail'
567
- );
568
- } else {
569
- await answerCallback(cbId, '⚔️ لا يوجد جولة PK نشطة');
570
- return;
571
- }
572
- break;
573
-
574
- case 'menu':
575
- await sendAndReplace(
576
- `📡 <b>━━━━ لوحة التحكم ━━━━</b>\n` +
577
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
578
- `👤 @${CONFIG.TIKTOK_USERNAME}\n` +
579
- `${isConnected ? `🟢 متصل • ⏱ ${dur(startTime)}` : '🔴 غير متصل'}\n` +
580
- `👁 ${formatK(currentViewers)} مشاهد • 💎 ${formatK(totalDiamonds)} ماسة\n\n` +
581
- `<i>📌 اضغط زر لعرض التفاصيل (الرسالة السابقة تُحذف تلقائياً)</i>`,
582
- true,
583
- [
584
- [{ text: `🎁 الهدايا (${totalGifts})`, callback_data: 'gifts' }, { text: `❤️ الإعجابات (${formatK(totalLikes)})`, callback_data: 'likes' }],
585
- [{ text: `💬 التعليقات (${totalComments})`, callback_data: 'chatters' }, { text: `➕ المتابعين (${totalFollows})`, callback_data: 'followers' }],
586
- [{ text: `↪️ المشاركات (${totalShares})`, callback_data: 'shares' }, { text: `❓ الأسئلة (${totalQuestions})`, callback_data: 'questions' }],
587
- [{ text: `📦💰 الصناديق (${totalEnvelopes})`, callback_data: 'envelopes' }],
588
- [{ text: '👑 أكثر المتفاعلين', callback_data: 'top_active' }],
589
- [{ text: '📈 إحصائيات مفصلة', callback_data: 'stats' }, { text: '⚔️ حالة PK', callback_data: 'pk_status' }],
590
- [{ text: '🔴 دخول البث', url: LIVE() }],
591
- ],
592
- 'menu'
593
- );
594
- break;
595
- }
596
- await answerCallback(cbId);
597
- }
598
-
599
- // ═══════════════════════ CALLBACK POLLING ═══════════════════════
600
- async function pollCallbacks() {
601
- let offset = 0;
602
- const urls = [];
603
- if (CONFIG.PROXY_URL) urls.push(`${CONFIG.PROXY_URL}/bot${CONFIG.TELEGRAM_TOKEN}`);
604
- urls.push(`https://api.telegram.org/bot${CONFIG.TELEGRAM_TOKEN}`);
605
- let idx = 0;
606
-
607
- while (true) {
608
- try {
609
- const base = urls[idx];
610
- const res = await axios.get(`${base}/getUpdates`, {
611
- params: { offset, limit: 10, timeout: 30 }, timeout: 35000
612
- });
613
- const updates = res.data?.result || [];
614
- for (const u of updates) {
615
- offset = u.update_id + 1;
616
- if (u.callback_query) await handleCallback(u.callback_query);
617
- if (u.message?.text) await handleTextCommand(u.message);
618
- }
619
- idx = 0;
620
- } catch (e) {
621
- idx = (idx + 1) % urls.length;
622
- await new Promise(r => setTimeout(r, idx === 0 ? 5000 : 2000));
623
- }
624
- }
625
- }
626
-
627
- // ═══════════════════════ FLUSH & CLEAR ═══════════════════════
628
- function clearStats() {
629
- // تنظيف الذاكرة
630
- for (const uid of Object.keys(chattersMap)) {
631
- if (chattersMap[uid].messages?.length > 30) {
632
- chattersMap[uid].messages = chattersMap[uid].messages.slice(-30);
633
- }
634
- }
635
- for (const uid of Object.keys(giftersMap)) {
636
- if (giftersMap[uid].gifts?.length > 10) {
637
- giftersMap[uid].gifts = giftersMap[uid].gifts.slice(-10);
638
- }
639
- }
640
- if (envelopeWinners.length > 50) {
641
- envelopeWinners = envelopeWinners.slice(-50);
642
- }
643
- if (questionsArr.length > 50) {
644
- questionsArr = questionsArr.slice(-50);
645
- }
646
- }
647
-
648
- // إرسال تقرير شامل
649
- async function sendFullStats() {
650
- if (!isConnected) return;
651
-
652
- const avgV = maxViewers > 0 ? Math.round((currentViewers + maxViewers) / 2) : currentViewers;
653
-
654
- let statsMsg = `📊🔥 <b>━━━ تقرير شامل ━━━</b>\n`;
655
- statsMsg += `━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
656
- statsMsg += `👤 <b>${CONFIG.TIKTOK_USERNAME}</b> • <code>@${CONFIG.TIKTOK_USERNAME}</code>\n`;
657
- statsMsg += `⏱ <b>${dur(startTime)}</b> • 📅 ${getDate()}\n\n`;
658
-
659
- statsMsg += `━━━ 👁 المشاهدين ━━━\n`;
660
- statsMsg += `الحاليين: <b>${formatK(currentViewers)}</b> | الأعلى: <b>${formatK(maxViewers)}</b> | المتوسط: ~<b>${formatK(avgV)}</b>\n\n`;
661
-
662
- statsMsg += `━━━ 📊 الأرقام ━━━\n`;
663
- statsMsg += `💎 الماسات: <b>${formatK(totalDiamonds)}</b>\n`;
664
- statsMsg += `🎁 الهدايا: <b>${totalGifts}</b>\n`;
665
- statsMsg += `❤️ الإعجابات: <b>${formatK(totalLikes)}</b>\n`;
666
- statsMsg += `💬 التعليقات: <b>${totalComments}</b>\n`;
667
- statsMsg += `➕ المتابعين: <b>${totalFollows}</b>\n`;
668
- statsMsg += `↪️ المشاركات: <b>${totalShares}</b>\n`;
669
- statsMsg += `📦 الصناديق: <b>${totalEnvelopes}</b>\n\n`;
670
-
671
- statsMsg += `━━━ 🏆 أفضل الداعمين ━━━\n\n${fmtGifters(5)}\n\n`;
672
- statsMsg += `━━━ 💬 أنشط المعلقين ━━━\n\n${fmtChatters(5)}`;
673
-
674
- await sendAndReplace(statsMsg, false, [
675
- [{ text: `🎁 الهدايا (${totalGifts})`, callback_data: 'gifts' }, { text: `❤️ اللايكات (${formatK(totalLikes)})`, callback_data: 'likes' }],
676
- [{ text: `💬 المعلقين (${totalComments})`, callback_data: 'chatters' }, { text: `👑 المتفاعلين`, callback_data: 'top_active' }],
677
- [{ text: '📦💰 الصناديق والحقائب', callback_data: 'envelopes' }],
678
- [{ text: '📈 تفاصيل كاملة', callback_data: 'stats' }],
679
- [{ text: '🔴 دخول البث', url: LIVE() }],
680
- ], 'report');
681
- }
682
-
683
- // ═══════════════════════ REPORTS ═══════════════════════
684
- function startReports() {
685
- if (reportInterval) clearInterval(reportInterval);
686
- reportInterval = setInterval(() => {
687
- if (!isConnected) return;
688
- sendFullStats();
689
- }, CONFIG.REPORT_INTERVAL * 60000);
690
- }
691
-
692
- // تنظيف كل 50 دقيقة
693
- function startFlushTimer() {
694
- if (flushInterval) clearInterval(flushInterval);
695
- flushInterval = setInterval(() => {
696
- clearStats();
697
- console.log('[Flush] ✅ Memory cleaned');
698
- // إرسال تقرير حتى لو لم يُضغط زر
699
- if (isConnected) {
700
- sendFullStats();
701
- }
702
- }, 50 * 60000);
703
- }
704
-
705
- // ═══════════════════════ HTTP SERVER ═══════════════════════
706
- const server = http.createServer((req, res) => {
707
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
708
- res.end(`<!DOCTYPE html><html dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Radar v11</title>
709
- <style>*{margin:0;padding:0;box-sizing:border-box}body{background:#050510;color:#e2e8f0;font-family:system-ui,sans-serif;min-height:100vh;padding:16px}.w{max-width:600px;margin:0 auto}.h{text-align:center;padding:30px;background:linear-gradient(135deg,#4f46e5,#7c3aed);border-radius:20px;margin-bottom:16px}.s{text-align:center;padding:14px;border-radius:14px;margin-bottom:14px;font-weight:700;background:${isConnected?'linear-gradient(135deg,#059669,#10b981)':'linear-gradient(135deg,#dc2626,#ef4444)'}}.g{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:14px}.g>div{background:#1e1b4b;padding:12px;border-radius:12px;text-align:center;border:1px solid #3730a3}.v{font-size:18px;font-weight:800;color:#a78bfa}.l{font-size:10px;color:#64748b;margin-top:3px}.env{background:#1a1040;border-radius:12px;padding:12px;margin-top:10px;border:1px solid #3730a3}</style></head>
710
- <body><div class="w"><div class="h"><h1>📡 TikTok Radar</h1><p style="opacity:.7">v11.0 - النسخة المحسّنة</p></div>
711
- <div class="s">${isConnected?'🟢 متصل':'🔴 منتظر'} • @${CONFIG.TIKTOK_USERNAME}</div>
712
- ${isConnected?`<div class="g"><div><div class="v">${formatK(currentViewers)}</div><div class="l">👁 المشاهدين</div></div><div><div class="v">${formatK(totalDiamonds)}</div><div class="l">💎 الماسات</div></div><div><div class="v">${totalGifts}</div><div class="l">🎁 الهدايا</div></div><div><div class="v">${formatK(totalLikes)}</div><div class="l">❤️ لايكات</div></div><div><div class="v">${totalComments}</div><div class="l">💬 تعليقات</div></div><div><div class="v">${totalFollows}</div><div class="l">➕ متابعين</div></div></div>
713
- <div class="env"><b>📦 الصناديق والحقائب:</b> ${totalEnvelopes}<br><b>⏱ المدة:</b> ${dur(startTime)}</div>`:''}
714
- <div style="margin-top:20px;text-align:center;font-size:12px;color:#666">
715
- <b>الأوامر:</b><br>
716
- /change username - تغيير المذيع<br>
717
- /channel2 CHAT_ID - قناة ثانية<br>
718
- /status - الحالة
719
- </div>
720
- </div></body></html>`);
721
- });
722
-
723
- server.listen(PORT, '0.0.0.0', () => {
724
- console.log(`\n🎯 TikTok Radar v11.0 | Port ${PORT} | @${CONFIG.TIKTOK_USERNAME}\n`);
725
- pollCallbacks();
726
- setTimeout(startBot, 2000);
727
- });
728
-
729
- // ═══════════════════════ MAIN BOT ═══════════════════════
730
- async function startBot() {
731
- console.log(`[Bot] 🔎 @${CONFIG.TIKTOK_USERNAME}...`);
732
- let TikTokLiveConnection, WebcastEvent, ControlEvent;
733
- try {
734
- const lib = require('tiktok-live-connector');
735
- TikTokLiveConnection = lib.TikTokLiveConnection;
736
- WebcastEvent = lib.WebcastEvent;
737
- ControlEvent = lib.ControlEvent;
738
- } catch (e) { console.error('[Bot] ❌', e.message); setTimeout(startBot, 30000); return; }
739
-
740
- try {
741
- const opts = {
742
- processInitialData: true,
743
- enableExtendedGiftInfo: true,
744
- fetchRoomInfoOnConnect: true
745
- };
746
-
747
- // Sign API Key
748
- if (CONFIG.SIGN_API_KEY) {
749
- opts.signApiKey = CONFIG.SIGN_API_KEY;
750
- console.log('[Bot] ✅ Sign API Key configured');
751
- }
752
-
753
- // Session للمصادقة الكاملة
754
- const mobileCookies = (process.env.MOBILE_COOKIES || '').trim();
755
-
756
- if (mobileCookies && CONFIG.SIGN_API_KEY) {
757
- // ✅ وضع الهاتف مع الكوكيز
758
- // نمرر الكوكيز للـ Sign Server عبر headers + session cookie
759
- // إضافة tt-target-idc للكوكيز إذا ما موجود
760
- let fullCookies = mobileCookies;
761
- if (!fullCookies.includes('tt-target-idc')) {
762
- fullCookies += `; tt-target-idc=${CONFIG.TT_TARGET_IDC}`;
763
- }
764
-
765
- try {
766
- const { SignConfig } = require('tiktok-live-connector');
767
- SignConfig.baseOptions = SignConfig.baseOptions || {};
768
- SignConfig.baseOptions.headers = {
769
- ...(SignConfig.baseOptions.headers || {}),
770
- 'x-cookie-header': fullCookies
771
- };
772
- console.log('[Bot] ✅ Set x-cookie-header with tt-target-idc');
773
- } catch (e) {
774
- console.log('[Bot] ⚠️ Could not set SignConfig headers:', e.message);
775
- }
776
-
777
- // استخراج sessionId من الكوكيز
778
- const sidMatch = mobileCookies.match(/sessionid=([^;]+)/);
779
- const sessionId = sidMatch ? sidMatch[1] : CONFIG.SESSION_ID;
780
-
781
- opts.session = {
782
- cookie: {
783
- type: 'cookie',
784
- value: {
785
- sessionId: sessionId,
786
- ttTargetIdc: CONFIG.TT_TARGET_IDC
787
- }
788
- }
789
- };
790
- opts.authenticateWs = true;
791
- opts.useMobile = true;
792
- console.log(`[Bot] ✅ Mobile mode enabled (sessionId: ${sessionId.substring(0, 8)}...)`);
793
- } else if (CONFIG.SESSION_ID && CONFIG.SESSION_ID.length > 10) {
794
- // وضع الويب العادي
795
- opts.session = {
796
- cookie: {
797
- type: 'cookie',
798
- value: {
799
- sessionId: CONFIG.SESSION_ID,
800
- ttTargetIdc: CONFIG.TT_TARGET_IDC
801
- }
802
- }
803
- };
804
- opts.authenticateWs = true;
805
- console.log('[Bot] ✅ Web mode with session cookie');
806
- }
807
-
808
- tiktokConnection = new TikTokLiveConnection(CONFIG.TIKTOK_USERNAME, opts);
809
-
810
- console.log('[Bot] 📋 Connection options:', JSON.stringify({
811
- hasSignApiKey: !!CONFIG.SIGN_API_KEY,
812
- hasSession: !!(CONFIG.SESSION_ID && CONFIG.SESSION_ID.length > 10),
813
- authenticateWs: opts.authenticateWs || false,
814
- ttTargetIdc: CONFIG.TT_TARGET_IDC || 'not set'
815
- }));
816
-
817
- // ══════════ ✅ CONNECTED ══════════
818
- tiktokConnection.on(ControlEvent.CONNECTED, (state) => {
819
- isConnected = true; startTime = new Date();
820
- totalGifts=0;totalDiamonds=0;totalLikes=0;totalComments=0;totalFollows=0;
821
- totalShares=0;totalSuperFans=0;totalQuestions=0;totalEnvelopes=0;totalEmotes=0;
822
- maxViewers=0;currentViewers=0;
823
- giftersMap={};followersMap={};chattersMap={};sharersMap={};likersMap={};
824
- envelopeWinners=[];
825
- questionsArr=[];pinnedMessages=[];pkActive=false;
826
- roomTitle = state.roomInfo?.title || '';
827
-
828
- console.log(`[Bot] ✅ Room: ${state.roomId}`);
829
- sendBoth(
830
- `📡✨ <b>البث المباشر بدأ!</b>\n` +
831
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
832
- `👤 <b>${CONFIG.TIKTOK_USERNAME}</b>\n` +
833
- `🔗 <code>@${CONFIG.TIKTOK_USERNAME}</code>\n` +
834
- (roomTitle ? `📝 ${esc(roomTitle)}\n` : '') +
835
- `⏰ ${getTime()} • 📅 ${getDate()}\n\n` +
836
- `━━━━━━━━━━━━━━━━━━━━━━━\n` +
837
- `🎉 <b>البث بدأ! انضم الآن!</b>`,
838
- false,
839
- [
840
- [{ text: '🔴 دخول البث المباشر', url: LIVE() }],
841
- [{ text: '📊 لوحة التحكم', callback_data: 'menu' }]
842
- ]
843
- );
844
- startReports();
845
- startFlushTimer();
846
- });
847
-
848
- tiktokConnection.on(ControlEvent.DISCONNECTED, () => {
849
- isConnected = false;
850
- if (reportInterval) clearInterval(reportInterval);
851
- if (flushInterval) clearInterval(flushInterval);
852
- scheduleReconnect(30000);
853
- });
854
-
855
- tiktokConnection.on(ControlEvent.ERROR, (err) => console.error('[Bot] ⚠️', err?.info || err?.message || err));
856
-
857
- // ══════════ 🔴 STREAM END ══════════
858
- tiktokConnection.on(WebcastEvent.STREAM_END, () => {
859
- isConnected = false;
860
- if (reportInterval) clearInterval(reportInterval);
861
- if (flushInterval) clearInterval(flushInterval);
862
- sendBoth(
863
- `🔴 <b>انتهى البث!</b>\n` +
864
- `━━━━━━━━━━━━━━━━━━━━━━━\n\n` +
865
- `👤 <b>${CONFIG.TIKTOK_USERNAME}</b>\n` +
866
- `⏱ المدة: <b>${dur(startTime)}</b>\n` +
867
- `📅 ${getDate()}\n\n` +
868
- `━━━ 📊 الملخص النهائي ━━━\n` +
869
- `💎 الماسات: <b>${formatK(totalDiamonds)}</b>\n` +
870
- `🎁 الهدايا: <b>${totalGifts}</b>\n` +
871
- `❤️ الإعجابات: <b>${formatK(totalLikes)}</b>\n` +
872
- `💬 التعليقات: <b>${totalComments}</b>\n` +
873
- `➕ المتابعين: <b>${totalFollows}</b>\n` +
874
- `↪️ المشاركات: <b>${totalShares}</b>\n` +
875
- `📦 الصناديق: <b>${totalEnvelopes}</b>\n\n` +
876
- `━━━ 🏆 أفضل الداعمين ━━━\n\n${fmtGifters(5)}\n\n` +
877
- `━━━ 💬 أنشط المعلقين ━━━\n\n${fmtChatters(5)}\n\n` +
878
- `✨ <b>شكراً للجميع!</b>`
879
- );
880
- scheduleReconnect(60000);
881
- });
882
-
883
- // ══════════ 💬 CHAT ══════════
884
- tiktokConnection.on(WebcastEvent.CHAT, (data) => {
885
- totalComments++;
886
- const uid = data.user?.userId || data.user?.uniqueId || 'x';
887
- const name = data.user?.nickname || data.user?.uniqueId || '?';
888
- const uname = data.user?.uniqueId || '';
889
- const comment = data.comment || '';
890
- if (!chattersMap[uid]) chattersMap[uid] = { name, username: uname, count: 0, messages: [] };
891
- chattersMap[uid].count++;
892
- if (comment) {
893
- chattersMap[uid].messages.push(comment);
894
- if (chattersMap[uid].messages.length > 20) {
895
- chattersMap[uid].messages = chattersMap[uid].messages.slice(-20);
896
- }
897
- }
898
- });
899
-
900
- // ══════════ 🎁 GIFT ══════════
901
- tiktokConnection.on(WebcastEvent.GIFT, (data) => {
902
- const uid = data.user?.userId || data.user?.uniqueId || 'x';
903
- const name = data.user?.nickname || data.user?.uniqueId || '?';
904
- const uname = data.user?.uniqueId || '';
905
- const gn = data.giftName || data.extendedGiftInfo?.name || 'Gift';
906
- const gnAr = getArabicGiftName(gn);
907
- const gt = data.giftType ?? 0;
908
- const rc = data.repeatCount ?? 1;
909
- const re = data.repeatEnd ?? true;
910
- let dc = data.diamondCount || data.extendedGiftInfo?.diamondCount || data.extendedGiftInfo?.diamond_count || data.gift?.diamond_count || data.giftDetails?.diamondCount || 0;
911
- if (gt === 1 && re === false) return;
912
- const cost = dc * rc;
913
- totalGifts++; totalDiamonds += cost;
914
- if (!giftersMap[uid]) giftersMap[uid] = { name, username: uname, coins: 0, count: 0, gifts: [] };
915
- giftersMap[uid].coins += cost; giftersMap[uid].count++;
916
- giftersMap[uid].gifts.push(gn);
917
- if (giftersMap[uid].gifts.length > 10) {
918
- giftersMap[uid].gifts = giftersMap[uid].gifts.slice(-10);
919
- }
920
- if (pkActive) {
921
- if (!pkInfo.pkGifts[uid]) pkInfo.pkGifts[uid] = { name, username: uname, coins: 0 };
922
- pkInfo.pkGifts[uid].coins += cost;
923
- }
924
- console.log(`[🎁] ${name}: ${gnAr} = ${cost}💎`);
925
- });
926
-
927
- // ══════════ ❤️ LIKE ══════════
928
- tiktokConnection.on(WebcastEvent.LIKE, (data) => {
929
- const likes = data.likeCount || 1;
930
- totalLikes += likes;
931
- const uid = data.user?.userId || data.user?.uniqueId || 'x';
932
- const name = data.user?.nickname || data.user?.uniqueId || '?';
933
- const uname = data.user?.uniqueId || '';
934
- if (!likersMap[uid]) likersMap[uid] = { name, username: uname, count: 0 };
935
- likersMap[uid].count += likes;
936
- });
937
-
938
- // ══════════ ➕ FOLLOW ══════════
939
- tiktokConnection.on(WebcastEvent.FOLLOW, (data) => {
940
- totalFollows++;
941
- const uid = data.user?.userId || data.user?.uniqueId || Date.now();
942
- const name = data.user?.nickname || data.user?.uniqueId || '?';
943
- const uname = data.user?.uniqueId || '';
944
- followersMap[uid] = { name, username: uname, time: Date.now() };
945
- });
946
-
947
- // ══════════ ↪️ SHARE ══════════
948
- tiktokConnection.on(WebcastEvent.SHARE, (data) => {
949
- totalShares++;
950
- const uid = data.user?.uniqueId || 'x';
951
- const name = data.user?.nickname || data.user?.uniqueId || '?';
952
- if (!sharersMap[uid]) sharersMap[uid] = { name, username: uid, count: 0 };
953
- sharersMap[uid].count++;
954
- });
955
-
956
- // ══════════ 👁 VIEWERS ══════════
957
- tiktokConnection.on(WebcastEvent.ROOM_USER, (data) => {
958
- currentViewers = data.viewerCount || 0;
959
- if (currentViewers > maxViewers) maxViewers = currentViewers;
960
- });
961
-
962
- tiktokConnection.on(WebcastEvent.MEMBER, () => {});
963
- tiktokConnection.on(WebcastEvent.EMOTE, () => { totalEmotes++; });
964
-
965
- // ══════════ 📦 ENVELOPE - صندوق / حقيبة عملات ══════════
966
- tiktokConnection.on(WebcastEvent.ENVELOPE, (data) => {
967
- totalEnvelopes++;
968
-
969
- // طباعة كل البيانات لفحصها
970
- console.log('[📦 ENVELOPE RAW]', JSON.stringify(data, null, 2));
971
-
972
- const env = data.envelopeInfo || data;
973
- if (env) {
974
- // محاولة استخراج البيانات من مختلف المواقع الممكنة
975
- const senderName = env.sendUserName || env.senderNickname || data.user?.nickname || '?';
976
- const senderUsername = env.sendUserUniqueId || env.senderUniqueId || data.user?.uniqueId || '';
977
- const diamonds = env.diamondCount || env.coins || data.diamonds || 0;
978
- const peopleCount = env.peopleCount || env.maxUserCount || 0;
979
- const envelopeId = env.envelopeId || env.id || '';
980
-
981
- // تحديد النوع بشكل أفضل
982
- let envType = 'chest';
983
- if (env.envelopeType === 2 || env.envelopeBusinessType === 2) {
984
- envType = 'coinbag';
985
- } else if (String(env.description || '').toLowerCase().includes('coin') ||
986
- String(env.description || '').toLowerCase().includes('حقيبة') ||
987
- String(env.title || '').toLowerCase().includes('coin') ||
988
- String(data.common?.describe || '').toLowerCase().includes('coin')) {
989
- envType = 'coinbag';
990
- }
991
-
992
- const typeIcon = envType === 'coinbag' ? '💰' : '📦';
993
- const typeName = envType === 'coinbag' ? 'حقيبة عملات' : 'صندوق كنز';
994
-
995
- // استخراج الفائزين من مختلف المصادر الممكنة
996
- const winners = [];
997
-
998
- // المصدر 1: envelopeGrabUserList
999
- const grabList = env.envelopeGrabUserList || env.grabUserList || env.winnerList || env.winners || [];
1000
- for (const w of grabList) {
1001
- winners.push({
1002
- name: w.nickname || w.nickName || w.uniqueId || w.userName || '?',
1003
- username: w.uniqueId || w.unique_id || '',
1004
- coins: w.diamondCount || w.coinCount || w.coins || w.amount || 0,
1005
- });
1006
- }
1007
-
1008
- // المصدر 2: envelopeGrabRecordList
1009
- const recordList = env.envelopeGrabRecordList || [];
1010
- for (const r of recordList) {
1011
- const user = r.user || r;
1012
- winners.push({
1013
- name: user.nickname || user.nickName || user.uniqueId || '?',
1014
- username: user.uniqueId || '',
1015
- coins: r.diamondCount || r.coinCount || r.grabDiamond || 0,
1016
- });
1017
- }
1018
-
1019
- console.log(`[📦] ${typeName} من ${senderName}: ${diamonds}💎 للـ ${peopleCount} شخص | الفائزين: ${winners.length}`);
1020
-
1021
- envelopeWinners.push({
1022
- type: envType,
1023
- sender: senderName,
1024
- senderUsername,
1025
- diamonds,
1026
- peopleCount,
1027
- winners,
1028
- envelopeId,
1029
- time: new Date()
1030
- });
1031
-
1032
- let winnerText = '';
1033
- if (winners.length) {
1034
- winnerText = `\n\n🏆 <b>الفائزين:</b>\n` + winners.map((w, i) =>
1035
- ` ${i + 1}. 👤 <b>${esc(w.name)}</b> ${w.username ? `<code>@${w.username}</code>` : ''}\n 🪙 حصل على: <b>${formatK(w.coins)}</b> عملة`
1036
- ).join('\n');
1037
- } else {
1038
- winnerText = `\n\n⏳ <i>الفائزين سيظهرون بعد انتهاء الصندوق...</i>`;
1039
- }
1040
-
1041
- sendBoth(
1042
- `${typeIcon}✨ <b>${typeName}!</b>\n` +
1043
- `━━━━━━━━━━━━━━━━━━━\n\n` +
1044
- `🆔 رقم: <code>${envelopeId}</code>\n` +
1045
- `👤 المرسل: <b>${esc(senderName)}</b> ${senderUsername ? `<code>@${senderUsername}</code>` : ''}\n` +
1046
- `💎 <b>${formatK(diamonds)}</b> ماسة • 👥 <b>${peopleCount}</b> شخص` +
1047
- winnerText
1048
- );
1049
- }
1050
- });
1051
-
1052
- // ══════════ 📦 محاولة التقاط أحداث أخرى للصناديق ══════════
1053
- const envelopeEvents = [
1054
- 'envelopeGrab', 'envelopeResult', 'envelopeOpen', 'envelopePortal',
1055
- 'treasureBox', 'treasureChest', 'goodyBag', 'goody_bag', 'goodieBag',
1056
- 'coinBag', 'coin_bag', 'luckyBag', 'lucky_bag',
1057
- 'WebcastGoodyBagMessage', 'goody', 'goodie', 'portal',
1058
- ];
1059
-
1060
- for (const evtName of envelopeEvents) {
1061
- try {
1062
- tiktokConnection.on(evtName, (data) => {
1063
- console.log(`[📦 ${evtName.toUpperCase()}]`, JSON.stringify(data, null, 2));
1064
-
1065
- // محاولة استخراج الفائزين
1066
- const winners = extractWinners(data);
1067
- if (winners.length > 0) {
1068
- updateLastEnvelopeWithWinners(winners);
1069
- }
1070
- });
1071
- } catch (e) {}
1072
- }
1073
-
1074
- // الاستماع لـ BARRAGE قد يحتوي على معلومات الصناديق
1075
- try {
1076
- tiktokConnection.on(WebcastEvent.BARRAGE, (data) => {
1077
- const content = JSON.stringify(data).toLowerCase();
1078
- if (content.includes('envelope') || content.includes('treasure') ||
1079
- content.includes('chest') || content.includes('grab') ||
1080
- content.includes('coin') || content.includes('winner')) {
1081
- console.log('[📦 BARRAGE - Envelope Related]', JSON.stringify(data, null, 2));
1082
-
1083
- const winners = extractWinners(data);
1084
- if (winners.length > 0) {
1085
- updateLastEnvelopeWithWinners(winners);
1086
- }
1087
- }
1088
- });
1089
- } catch (e) {}
1090
-
1091
- // ══════════ ❓ QUESTION ══════════
1092
- try { tiktokConnection.on(WebcastEvent.QUESTION_NEW, (data) => {
1093
- totalQuestions++;
1094
- const q = data.details?.questionText || '';
1095
- const name = data.details?.user?.nickname || '?';
1096
- if (q) questionsArr.push({ name, text: q, time: Date.now() });
1097
- }); } catch (e) {}
1098
-
1099
- // ══════════ ⭐ SUPER FAN ══════════
1100
- try { tiktokConnection.on(WebcastEvent.SUPER_FAN, (data) => {
1101
- totalSuperFans++;
1102
- const msg = data.content?.defaultPattern || data.commonBarrageContent?.defaultPattern || '';
1103
- sendBoth(`⭐🌟 <b>سوبر فان جديد!</b>\n━━━━━━━━━━━━━━━━━━━\n\n${esc(msg) || '👑 مستخدم أصبح سوبر فان!'}`);
1104
- }); } catch (e) {}
1105
-
1106
- try { tiktokConnection.on(WebcastEvent.SUPER_FAN_JOIN, () => {}); } catch (e) {}
1107
- try { tiktokConnection.on(WebcastEvent.SUPER_FAN_BOX, (data) => {
1108
- if (data.envelopeInfo) sendBoth(`⭐📦 <b>صندوق سوبر فان!</b>`);
1109
- }); } catch (e) {}
1110
-
1111
- // ══════════ 📌 PIN ══════════
1112
- try { tiktokConnection.on(WebcastEvent.ROOM_PIN, (data) => {
1113
- const by = data.operator?.nickname || '?';
1114
- const chat = data.chatMessage?.comment || '';
1115
- if (chat) sendBoth(`📌 <b>رسالة مثبتة</b>\n━━━━━━━━━━━━━━━━━━━\n\n👤 <b>${esc(by)}</b>\n💬 <i>"${esc(chat)}"</i>`, true);
1116
- }); } catch (e) {}
1117
-
1118
- // ══════════ ⚔️ PK ══════════
1119
- tiktokConnection.on(WebcastEvent.LINK_MIC_BATTLE, (data) => {
1120
- pkActive = true;
1121
- pkInfo = { battleId: data.battleId || '', participantDetails: [], ourScore: 0, theirScore: 0, startTime: new Date(), pkGifts: {} };
1122
- const details = [];
1123
- for (const [k, info] of Object.entries(data.anchorInfo || {})) {
1124
- const u = info.user || info || {};
1125
- const did = u.displayId || u.uniqueId || '';
1126
- const nn = u.nickName || u.nickname || did || 'مجهول';
1127
- if (did || nn !== 'مجهول') details.push({ name: nn, username: did });
1128
- }
1129
- pkInfo.participantDetails = details;
1130
- const opp = details.find(p => p.username !== CONFIG.TIKTOK_USERNAME && p.name !== CONFIG.TIKTOK_USERNAME) || details[1] || null;
1131
-
1132
- let msg = `⚔️🔥 <b>جولة PK جديدة!</b>\n━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
1133
- msg += `🏠 <b>${esc(CONFIG.TIKTOK_USERNAME)}</b>\n <code>@${CONFIG.TIKTOK_USERNAME}</code>\n\n 🆚\n\n`;
1134
- if (opp) msg += `🥊 <b>${esc(opp.name)}</b>\n <code>@${opp.username || '?'}</code>\n\n`;
1135
- else msg += `🥊 ⏳ جاري التحميل...\n\n`;
1136
- msg += `━━━━━━━━━━━━━━━━━━━━━━━\n🚀 <b>ادعموا البث!</b>`;
1137
- sendBoth(msg, false, [
1138
- [{ text: '🔴 ادخل وادعم!', url: LIVE() }],
1139
- [{ text: '⚔️ نتيجة PK', callback_data: 'pk_status' }]
1140
- ]);
1141
- });
1142
-
1143
- tiktokConnection.on(WebcastEvent.LINK_MIC_ARMIES, (data) => {
1144
- if (pkActive && data.totalDiamondCount) pkInfo.ourScore = data.totalDiamondCount;
1145
- });
1146
-
1147
- try { tiktokConnection.on(WebcastEvent.LINK_MIC_BATTLE_PUNISH_FINISH, () => {
1148
- pkActive = false;
1149
- const pkG = Object.values(pkInfo.pkGifts).sort((a, b) => b.coins - a.coins).slice(0, 5)
1150
- .map((g, i) => `${medals[i]} <b>${esc(g.name)}</b>: ${formatK(g.coins)} 💎`).join('\n') || 'لا يوجد';
1151
- sendBoth(`🏆 <b>انتهت PK!</b>\n━━━━━━━━━━━━━━━━━━━━━━━\n\n💎 <b>${formatK(pkInfo.ourScore)}</b> • ⏱ ${dur(pkInfo.startTime)}\n\n🏆 الداعمين:\n${pkG}\n\n✨ <b>شكراً للجميع!</b>`);
1152
- }); } catch (e) {}
1153
-
1154
- // ══════════ 🎯 GOAL ══════════
1155
- try { tiktokConnection.on(WebcastEvent.GOAL_UPDATE, (data) => {
1156
- const d = data.goal?.description || '';
1157
- if (d) sendBoth(`🎯 <b>تحديث الهدف!</b>\n━━━━━━━━━━━━━━━\n📋 ${esc(d)}`, true);
1158
- }); } catch (e) {}
1159
-
1160
- // ══════════ 🗳️ POLL ══════════
1161
- try { tiktokConnection.on(WebcastEvent.POLL_MESSAGE, (data) => {
1162
- const t = data.pollBasicInfo?.title || '';
1163
- if (t) sendBoth(`🗳️ <b>تصويت!</b>\n━━━━━━━━━━━━━━━\n📋 <b>${esc(t)}</b>`, true);
1164
- }); } catch (e) {}
1165
-
1166
- // ══════════ 🛒 SHOPPING ══════════
1167
- try { tiktokConnection.on(WebcastEvent.OEC_LIVE_SHOPPING, (data) => {
1168
- const s = data.shopData;
1169
- if (s?.title) sendBoth(`🛒 <b>منتج!</b>\n📦 ${esc(s.title)}${s.priceString ? `\n💰 ${esc(s.priceString)}` : ''}`, true);
1170
- }); } catch (e) {}
1171
-
1172
- try { tiktokConnection.on(WebcastEvent.RANK_UPDATE, () => {}); } catch (e) {}
1173
- try { tiktokConnection.on(WebcastEvent.RANK_TEXT, (data) => {
1174
- if (data.ownerIdxAfterUpdate && data.ownerIdxBeforeUpdate && data.ownerIdxAfterUpdate < data.ownerIdxBeforeUpdate)
1175
- sendBoth(`🏆📈 ارتفع الترتيب! #${data.ownerIdxBeforeUpdate} → #${data.ownerIdxAfterUpdate} 🔥`, true);
1176
- }); } catch (e) {}
1177
- tiktokConnection.on(WebcastEvent.LIVE_INTRO, () => {});
1178
- try { tiktokConnection.on(WebcastEvent.ROOM_MESSAGE, () => {}); } catch (e) {}
1179
- try { tiktokConnection.on(WebcastEvent.CAPTION_MESSAGE, () => {}); } catch (e) {}
1180
-
1181
- // ══════════ 📊 تسجيل كل الأحداث بدون استثناء ══════════
1182
- // لا نتجاهل أي شي - نسجل كل حدث بأول 200 حرف
1183
- const knownSkipEvents = new Set([
1184
- // فقط الأحداث الكثيرة جداً اللي تملأ الـ Logs
1185
- 'WebcastChatMessage', 'WebcastLikeMessage',
1186
- 'WebcastRoomUserSeqMessage',
1187
- ]);
1188
-
1189
- // عداد لتسجيل كل أنواع الأحداث والرسائل الخام
1190
- const seenEventTypes = new Set();
1191
- const seenRawTypes = new Set();
1192
-
1193
- tiktokConnection.on(ControlEvent.DECODED_DATA, (eventType, decodedData, binary) => {
1194
- const lowerType = (eventType || '').toLowerCase();
1195
-
1196
- // ✅ تسجيل كل نوع حدث يمر مرة وحدة
1197
- if (!seenEventTypes.has(eventType)) {
1198
- seenEventTypes.add(eventType);
1199
- console.log(`[🆕 NEW EVENT TYPE SEEN: ${eventType}] ← أول مرة يظهر هالنوع!`);
1200
- }
1201
-
1202
- // ✅ تسجيل كل حدث غير معروف
1203
- if (!knownSkipEvents.has(eventType)) {
1204
- const dataStr = JSON.stringify(decodedData || {});
1205
- // سجل اسم الحدث + أول 300 حرف بس
1206
- console.log(`[📡 ${eventType}] ${dataStr.substring(0, 300)}`);
1207
-
1208
- // إذا متعلق بصندوق سجل كامل
1209
- if (lowerType.includes('envelope') || lowerType.includes('treasure') ||
1210
- lowerType.includes('chest') || lowerType.includes('grab') ||
1211
- lowerType.includes('goody') || lowerType.includes('portal') ||
1212
- lowerType.includes('lucky') || lowerType.includes('coin') ||
1213
- lowerType.includes('bag') || lowerType.includes('box')) {
1214
- console.log(`[📦 FULL ${eventType}]`, JSON.stringify(decodedData, null, 2));
1215
-
1216
- const winners = extractWinners(decodedData);
1217
- if (winners.length > 0) {
1218
- updateLastEnvelopeWithWinners(winners);
1219
- }
1220
- }
1221
-
1222
- // حتى لو ما نعرف اسم الحدث، نفحص المحتوى
1223
- if (dataStr.toLowerCase().includes('envelope') ||
1224
- dataStr.toLowerCase().includes('diamond') ||
1225
- dataStr.toLowerCase().includes('grab')) {
1226
- console.log(`[📦 DATA-MATCH ${eventType}]`, JSON.stringify(decodedData, null, 2));
1227
-
1228
- // محاولة معالجة كأنه صندوق
1229
- try {
1230
- const env = decodedData?.envelopeInfo || decodedData;
1231
- if (env && (env.diamondCount || env.sendUserName || env.envelopeId)) {
1232
- totalEnvelopes++;
1233
- const senderName = env.sendUserName || env.senderNickname || '?';
1234
- const senderUsername = env.sendUserUniqueId || env.senderUniqueId || '';
1235
- const diamonds = env.diamondCount || env.coins || 0;
1236
- const peopleCount = env.peopleCount || env.maxUserCount || 0;
1237
- const envelopeId = env.envelopeId || env.id || '';
1238
-
1239
- let envType = 'chest';
1240
- if (env.envelopeType === 2 || env.envelopeBusinessType === 2) envType = 'coinbag';
1241
-
1242
- const typeIcon = envType === 'coinbag' ? '💰' : '📦';
1243
- const typeName = envType === 'coinbag' ? 'حقيبة عملات' : 'صندوق كنز';
1244
-
1245
- const winners = extractWinners(decodedData);
1246
-
1247
- envelopeWinners.push({
1248
- type: envType, sender: senderName, senderUsername,
1249
- diamonds, peopleCount, winners, envelopeId, time: new Date()
1250
- });
1251
-
1252
- let winnerText = '';
1253
- if (winners.length) {
1254
- winnerText = `\n\n🏆 <b>الفائزين:</b>\n` + winners.map((w, i) =>
1255
- ` ${i + 1}. 👤 <b>${esc(w.name)}</b> ${w.username ? `<code>@${w.username}</code>` : ''}\n 🪙 حصل على: <b>${formatK(w.coins)}</b> عملة`
1256
- ).join('\n');
1257
- } else {
1258
- winnerText = `\n\n⏳ <i>الفائزين سيظهرون لاحقاً...</i>`;
1259
- }
1260
-
1261
- sendBoth(
1262
- `${typeIcon}✨ <b>${typeName}!</b>\n` +
1263
- `━━━━━━━━━━━━━━━━━━━\n\n` +
1264
- `🆔 رقم: <code>${envelopeId}</code>\n` +
1265
- `👤 المرسل: <b>${esc(senderName)}</b> ${senderUsername ? `<code>@${senderUsername}</code>` : ''}\n` +
1266
- `💎 <b>${formatK(diamonds)}</b> ماسة • 👥 <b>${peopleCount}</b> شخص` +
1267
- winnerText
1268
- );
1269
-
1270
- console.log(`[📦 ✅ CAUGHT FROM DECODED] ${typeName} من ${senderName}: ${diamonds}💎`);
1271
- }
1272
- } catch (e) {
1273
- console.log('[📦 Parse Error]', e.message);
1274
- }
1275
- }
1276
- }
1277
- });
1278
-
1279
- // ══════════ 📋 عرض كل الأحداث المتوفرة ══════════
1280
- console.log('[Bot] 📋 Available WebcastEvents:', Object.keys(WebcastEvent).join(', '));
1281
- console.log('[Bot] 📋 Available ControlEvents:', Object.keys(ControlEvent).join(', '));
1282
-
1283
- // ══════════ 📡 RAW DATA - التقاط كل رسالة خام وفحصها ══════════
1284
- tiktokConnection.on(ControlEvent.RAW_DATA, (messageTypeName, binary) => {
1285
- const lowerName = (messageTypeName || '').toLowerCase();
1286
-
1287
- // ✅ تسجيل كل نوع رسالة خام يمر (أول مرة فقط)
1288
- if (!seenRawTypes.has(messageTypeName)) {
1289
- seenRawTypes.add(messageTypeName);
1290
- console.log(`[🔵 RAW TYPE: ${messageTypeName}] size: ${binary?.length || 0} bytes ← أول مرة!`);
1291
-
1292
- // إذا مو من الأنواع المعروفة، نسجله بالكامل
1293
- const knownRaw = new Set([
1294
- 'WebcastChatMessage', 'WebcastMemberMessage', 'WebcastLikeMessage',
1295
- 'WebcastRoomUserSeqMessage', 'WebcastGiftMessage', 'WebcastSocialMessage',
1296
- 'WebcastLiveIntroMessage', 'WebcastControlMessage', 'WebcastImDeleteMessage',
1297
- 'WebcastEmoteChatMessage', 'WebcastMsgDetectMessage', 'WebcastCaptionMessage',
1298
- 'WebcastRoomMessage', 'WebcastInRoomBannerMessage', 'WebcastLinkMicArmies',
1299
- 'WebcastLinkMicBattle', 'WebcastLinkMicFanTicketMethod', 'WebcastLinkLayerMessage',
1300
- 'WebcastLinkMessage', 'WebcastLinkMicMethod', 'WebcastLinkmicBattleTaskMessage',
1301
- 'WebcastRankUpdateMessage', 'WebcastRankTextMessage', 'WebcastHourlyRankMessage',
1302
- 'WebcastBarrageMessage', 'WebcastLinkMicBattlePunishFinish',
1303
- ]);
1304
- if (!knownRaw.has(messageTypeName)) {
1305
- console.log(`[⚠️ UNKNOWN RAW: ${messageTypeName}] ← هذا نوع جديد غير معروف! size: ${binary?.length || 0}`);
1306
-
1307
- // محاولة فك protobuf يدوياً
1308
- try {
1309
- const protobuf = require('protobufjs');
1310
- const root = new protobuf.Root();
1311
-
1312
- // تعريف GoodyBag proto
1313
- const GoodyBagUserInfo = new protobuf.Type("GoodyBagUserInfo")
1314
- .add(new protobuf.Field("user_id", 1, "string"))
1315
- .add(new protobuf.Field("nickname", 2, "string"))
1316
- .add(new protobuf.Field("display_id", 3, "string"));
1317
-
1318
- const GoodyBagWinnerInfo = new protobuf.Type("GoodyBagWinnerInfo")
1319
- .add(new protobuf.Field("user_info", 1, "GoodyBagUserInfo"))
1320
- .add(new protobuf.Field("coins", 2, "int32"));
1321
-
1322
- const GoodyBagCoinDetail = new protobuf.Type("GoodyBagCoinDetail")
1323
- .add(new protobuf.Field("total_coin", 1, "int32"));
1324
-
1325
- const GoodyBagCommonDetail = new protobuf.Type("GoodyBagCommonDetail")
1326
- .add(new protobuf.Field("winner_headcount", 1, "int32"))
1327
- .add(new protobuf.Field("joined_headcount", 2, "int32"))
1328
- .add(new protobuf.Field("participate_method", 3, "int32"))
1329
- .add(new protobuf.Field("participate_method_content", 4, "string"))
1330
- .add(new protobuf.Field("open_at", 5, "int32"))
1331
- .add(new protobuf.Field("count_down_minutes", 6, "int32"));
1332
-
1333
- const GoodyBagBaseInfo = new protobuf.Type("GoodyBagBaseInfo")
1334
- .add(new protobuf.Field("goody_bag_id", 1, "string"))
1335
- .add(new protobuf.Field("biz", 2, "int32"))
1336
- .add(new protobuf.Field("room_id", 3, "string"))
1337
- .add(new protobuf.Field("common_detail", 4, "GoodyBagCommonDetail"))
1338
- .add(new protobuf.Field("coin_detail", 5, "GoodyBagCoinDetail"));
1339
-
1340
- const WebcastGoodyBagMessage = new protobuf.Type("WebcastGoodyBagMessage")
1341
- .add(new protobuf.Field("base_info", 2, "GoodyBagBaseInfo"))
1342
- .add(new protobuf.Field("winners", 3, "GoodyBagWinnerInfo", "repeated"))
1343
- .add(new protobuf.Field("type", 4, "int32"));
1344
-
1345
- root.add(GoodyBagUserInfo);
1346
- root.add(GoodyBagWinnerInfo);
1347
- root.add(GoodyBagCoinDetail);
1348
- root.add(GoodyBagCommonDetail);
1349
- root.add(GoodyBagBaseInfo);
1350
- root.add(WebcastGoodyBagMessage);
1351
-
1352
- const decoded = WebcastGoodyBagMessage.decode(Buffer.from(binary));
1353
- const obj = WebcastGoodyBagMessage.toObject(decoded);
1354
- console.log(`[🟣 DECODED GOODY BAG!]`, JSON.stringify(obj, null, 2));
1355
-
1356
- // معالجة البيانات
1357
- totalEnvelopes++;
1358
- const baseInfo = obj.base_info || {};
1359
- const coinDetail = baseInfo.coin_detail || {};
1360
- const commonDetail = baseInfo.common_detail || {};
1361
- const winners = (obj.winners || []).map(w => ({
1362
- name: w.user_info?.nickname || w.user_info?.display_id || '?',
1363
- username: w.user_info?.display_id || '',
1364
- coins: w.coins || 0,
1365
- }));
1366
-
1367
- envelopeWinners.push({
1368
- type: 'goody_bag', sender: CONFIG.TIKTOK_USERNAME, senderUsername: CONFIG.TIKTOK_USERNAME,
1369
- diamonds: coinDetail.total_coin || 0, peopleCount: commonDetail.winner_headcount || 0,
1370
- winners, envelopeId: baseInfo.goody_bag_id || '', time: new Date()
1371
- });
1372
-
1373
- let winnerText = '';
1374
- if (winners.length) {
1375
- winnerText = `\n\n🏆 <b>الفائزين:</b>\n` + winners.map((w, i) =>
1376
- ` ${i + 1}. 👤 <b>${esc(w.name)}</b> ${w.username ? `<code>@${w.username}</code>` : ''}\n 🪙 حصل على: <b>${formatK(w.coins)}</b> عملة`
1377
- ).join('\n');
1378
- }
1379
-
1380
- sendBoth(
1381
- `🟣✨ <b>بوابة هدايا (Goody Bag)!</b>\n` +
1382
- `━━━━━━━━━━━━━━━━━━━\n\n` +
1383
- `🪙 العملات: <b>${formatK(coinDetail.total_coin || 0)}</b>\n` +
1384
- `👥 عدد الفائزين: <b>${commonDetail.winner_headcount || '?'}</b>\n` +
1385
- `👤 المشاركين: <b>${commonDetail.joined_headcount || '?'}</b>\n` +
1386
- `📋 الشرط: ${commonDetail.participate_method_content || 'غير محدد'}` +
1387
- winnerText
1388
- );
1389
- } catch (e) {
1390
- console.log(`[🟣 PROTO DECODE FAILED: ${e.message}] - trying generic decode...`);
1391
-
1392
- // محاولة فك عام
1393
- try {
1394
- const protobuf = require('protobufjs');
1395
- const reader = protobuf.Reader.create(Buffer.from(binary));
1396
- const fields = {};
1397
- while (reader.pos < reader.len) {
1398
- const tag = reader.uint32();
1399
- const fieldNum = tag >>> 3;
1400
- const wireType = tag & 7;
1401
- try {
1402
- if (wireType === 2) fields[`field_${fieldNum}`] = reader.string();
1403
- else if (wireType === 0) fields[`field_${fieldNum}`] = reader.uint64().toString();
1404
- else reader.skipType(wireType);
1405
- } catch { reader.skipType(wireType); }
1406
- }
1407
- console.log(`[🟣 GENERIC DECODE ${messageTypeName}]`, JSON.stringify(fields));
1408
-
1409
- totalEnvelopes++;
1410
- sendBoth(
1411
- `🟣✨ <b>حدث غير معروف: ${messageTypeName}!</b>\n` +
1412
- `━━━━━━━━━━━━━━━━━━━\n\n` +
1413
- `📦 البيانات: <code>${JSON.stringify(fields).substring(0, 500)}</code>`
1414
- );
1415
- } catch (e2) {
1416
- console.log(`[🟣 GENERIC FAILED TOO]`, e2.message);
1417
- }
1418
- }
1419
- }
1420
- }
1421
-
1422
- // التقاط أي رسالة متعلقة بالصناديق بالاسم
1423
- if (lowerName.includes('goody') || lowerName.includes('goodie') ||
1424
- lowerName.includes('envelope') || lowerName.includes('portal') ||
1425
- lowerName.includes('treasure') || lowerName.includes('bag') ||
1426
- lowerName.includes('box') || lowerName.includes('grab') ||
1427
- lowerName.includes('lucky') || lowerName.includes('reward') ||
1428
- lowerName.includes('coin') || lowerName.includes('asset')) {
1429
- console.log(`[🔴 RAW_DATA: ${messageTypeName}] binary size: ${binary?.length || 0} bytes`);
1430
- }
1431
- });
1432
-
1433
- // محاولة الاستماع لكل الأحداث المتوفرة في المكتبة
1434
- const allWebcastEvents = Object.values(WebcastEvent);
1435
- for (const evt of allWebcastEvents) {
1436
- const evtLower = (evt || '').toLowerCase();
1437
- // الأحداث اللي ما سجلناها يدوياً
1438
- if (evtLower.includes('envelope') || evtLower.includes('treasure') ||
1439
- evtLower.includes('goody') || evtLower.includes('portal') ||
1440
- evtLower.includes('bag') || evtLower.includes('box') ||
1441
- evtLower.includes('capsule') || evtLower.includes('boost') ||
1442
- evtLower.includes('toast') || evtLower.includes('notice') ||
1443
- evtLower.includes('bottom') || evtLower.includes('gift_broadcast')) {
1444
- try {
1445
- tiktokConnection.on(evt, (data) => {
1446
- console.log(`[🎯 AUTO-LISTEN ${evt}]`, JSON.stringify(data, null, 2));
1447
-
1448
- // محاولة معالجة كصندوق
1449
- const winners = extractWinners(data);
1450
- if (data?.envelopeInfo || data?.diamondCount || data?.sendUserName) {
1451
- totalEnvelopes++;
1452
- const env = data.envelopeInfo || data;
1453
- const senderName = env.sendUserName || '?';
1454
- const diamonds = env.diamondCount || 0;
1455
- const peopleCount = env.peopleCount || 0;
1456
-
1457
- envelopeWinners.push({
1458
- type: 'chest', sender: senderName, senderUsername: '',
1459
- diamonds, peopleCount, winners, envelopeId: '', time: new Date()
1460
- });
1461
-
1462
- sendBoth(
1463
- `📦✨ <b>صندوق/بوابة!</b> (via ${evt})\n━━━━━━━━━━━━━━━━━━━\n\n` +
1464
- `👤 <b>${esc(senderName)}</b>\n💎 <b>${formatK(diamonds)}</b> ماسة`
1465
- );
1466
- }
1467
- if (winners.length > 0) {
1468
- updateLastEnvelopeWithWinners(winners);
1469
- }
1470
- });
1471
- console.log(`[Bot] 👂 Auto-listening: ${evt}`);
1472
- } catch (e) {}
1473
- }
1474
- }
1475
-
1476
- console.log('[Bot] 🔌 Connecting...');
1477
- await tiktokConnection.connect();
1478
- } catch (err) {
1479
- console.error('[Bot] ❌', err.message || err);
1480
- isConnected = false;
1481
- scheduleReconnect(60000);
1482
- }
1483
- }
1484
-
1485
- function scheduleReconnect(d) {
1486
- if (reconnectTimer) clearTimeout(reconnectTimer);
1487
- console.log(`[Bot] 🔄 ${d / 1000}s...`);
1488
- reconnectTimer = setTimeout(() => { reconnectTimer = null; if (!isConnected) startBot(); }, d);
1489
- }
1490
-
1491
- process.on('uncaughtException', e => console.error('[!]', e.message));
1492
- process.on('unhandledRejection', r => console.error('[!]', r));
1493
- setInterval(() => { http.get(`http://localhost:${PORT}`, r => r.resume()).on('error', () => {}); }, 60000);