Alluser / index.js
Reooiq's picture
chore: remove proxy/tunnel configurations and switch to direct API
4df4635
Raw History Blame Contribute Delete
25.8 kB
const { TikTokLiveConnection, WebcastEvent } = require('tiktok-live-connector');
const https = require('https');
const http = require('http');
const dns = require('dns');
const { URL } = require('url');
const TIKTOK_USERNAME = process.env.TIKTOK_USERNAME || process.env.TIKTOK_USERNAMES?.split(',')[0]?.trim() || '';
const TELEGRAM_TOKEN = process.env.TELEGRAM_TOKEN;
const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;
const SESSION_ID = process.env.SESSION_ID || undefined;
const TELEGRAM_API_URL = "https://api.telegram.org";
dns.setServers(['8.8.8.8']);
// ====== قاموس الدول ======
const COUNTRY_FLAGS = {
'SA': { name: 'السعودية', flag: '🇸🇦' }, 'EG': { name: 'مصر', flag: '🇪🇬' },
'AE': { name: 'الإمارات', flag: '🇦🇪' }, 'KW': { name: 'الكويت', flag: '🇰🇼' },
'QA': { name: 'قطر', flag: '🇶🇦' }, 'BH': { name: 'البحرين', flag: '🇧🇭' },
'OM': { name: 'عُمان', flag: '🇴🇲' }, 'JO': { name: 'الأردن', flag: '🇯🇴' },
'LB': { name: 'لبنان', flag: '🇱🇧' }, 'SY': { name: 'سوريا', flag: '🇸🇾' },
'IQ': { name: 'العراق', flag: '🇮🇶' }, 'YE': { name: 'اليمن', flag: '🇾🇪' },
'LY': { name: 'ليبيا', flag: '🇱🇾' }, 'TN': { name: 'تونس', flag: '🇹🇳' },
'DZ': { name: 'الجزائر', flag: '🇩🇿' }, 'MA': { name: 'المغرب', flag: '🇲🇦' },
'SD': { name: 'السودان', flag: '🇸🇩' }, 'SO': { name: 'الصومال', flag: '🇸🇴' },
'DJ': { name: 'جيبوتي', flag: '🇩🇯' }, 'MR': { name: 'موريتانيا', flag: '🇲🇷' },
'PS': { name: 'فلسطين', flag: '🇵🇸' }, 'IL': { name: 'إسرائيل', flag: '🇮🇱' },
'US': { name: 'الولايات المتحدة', flag: '🇺🇸' }, 'GB': { name: 'المملكة المتحدة', flag: '🇬🇧' },
'TR': { name: 'تركيا', flag: '🇹🇷' }, 'FR': { name: 'فرنسا', flag: '🇫🇷' },
'DE': { name: 'ألمانيا', flag: '🇩🇪' }, 'IT': { name: 'إيطاليا', flag: '🇮🇹' },
'ES': { name: 'إسبانيا', flag: '🇪🇸' }, 'BR': { name: 'البرازيل', flag: '🇧🇷' },
'RU': { name: 'روسيا', flag: '🇷🇺' }, 'CN': { name: 'الصين', flag: '🇨🇳' },
'JP': { name: 'اليابان', flag: '🇯🇵' }, 'KR': { name: 'كوريا الجنوبية', flag: '🇰🇷' },
'IN': { name: 'الهند', flag: '🇮🇳' }, 'ID': { name: 'إندونيسيا', flag: '🇮🇩' },
'TH': { name: 'تايلاند', flag: '🇹🇭' }, 'VN': { name: 'فيتنام', flag: '🇻🇳' },
'PH': { name: 'الفلبين', flag: '🇵🇭' }, 'MY': { name: 'ماليزيا', flag: '🇲🇾' },
'SG': { name: 'سنغافورة', flag: '🇸🇬' }, 'PK': { name: 'باكستان', flag: '🇵🇰' },
'BD': { name: 'بنغلاديش', flag: '🇧🇩' }, 'IR': { name: 'إيران', flag: '🇮🇷' },
'AR': { name: 'الأرجنتين', flag: '🇦🇷' }, 'MX': { name: 'المكسيك', flag: '🇲🇽' },
'CO': { name: 'كولومبيا', flag: '🇨🇴' }, 'PE': { name: 'بيرو', flag: '🇵🇪' },
'CL': { name: 'تشيلي', flag: '🇨🇱' }, 'CA': { name: 'كندا', flag: '🇨🇦' },
'AU': { name: 'أستراليا', flag: '🇦🇺' }, 'NZ': { name: 'نيوزيلندا', flag: '🇳🇿' },
'ZA': { name: 'جنوب أفريقيا', flag: '🇿🇦' }, 'NG': { name: 'نيجيريا', flag: '🇳🇬' },
'NL': { name: 'هولندا', flag: '🇳🇱' }, 'BE': { name: 'بلجيكا', flag: '🇧🇪' },
'CH': { name: 'سويسرا', flag: '🇨🇭' }, 'AT': { name: 'النمسا', flag: '🇦🇹' },
'PL': { name: 'بولندا', flag: '🇵🇱' }, 'SE': { name: 'السويد', flag: '🇸🇪' },
'NO': { name: 'النرويج', flag: '🇳🇴' }, 'DK': { name: 'الدنمارك', flag: '🇩🇰' },
'FI': { name: 'فنلندا', flag: '🇫🇮' }, 'GR': { name: 'اليونان', flag: '🇬🇷' },
'PT': { name: 'البرتغال', flag: '🇵🇹' }, 'IE': { name: 'أيرلندا', flag: '🇮🇪' },
};
const GIFT_ARABIC = {
'rose':'وردة','heart':'قلب','star':'نجمة','fire':'نار','crown':'تاج',
'diamond':'ماسة','tiger':'نمر','dragon':'تنين','rainbow':'قوس قزح',
'galaxy':'مجرة','rocket':'صاروخ','butterfly':'فراشة','lollipop':'حلوى',
'cookie':'بسكويت','donut':'دونات','ice cream':'آيس كريم','champagne':'شمبانيا',
'wine':'نبيذ','ring':'خاتم','gem':'جوهرة','pearl':'لؤلؤ','teddy bear':'دب',
'cat':'قطة','dog':'كلب','lion':'أسد','panda':'باندا','castle':'قصر',
'angel':'ملاك','phoenix':'فينيخ','mermaid':'مرأة البحر','fairy':'جنية',
'robot':'روبوت','dinosaur':'ديناصور','penguin':'بطريق',
'blue heart':'قلب أزرق','purple heart':'قلب بنفسجي','golden crown':'تاج ذهبي',
'silver crown':'تاج فضي','firework':'ألعاب نارية','fireworks':'ألعاب نارية',
'nevalyashka doll':'دمية','dancing bear':'دب راقص','lucky cat':'قطة محظوظة',
'magic':'سحر','rainbow rose':'وردة قوس قزح','pink rose':'وردة وردية',
'red rose':'وردة حمراء','white rose':'وردة بيضاء','blue rose':'وردة زرقاء',
'golden ticket':'تذكرة ذهبية','golden star':'نجمة ذهبية','diamond ring':'خاتم ماسي',
'diamond necklace':'عقد ماسي','golden egg':'بيضة ذهبية','golden heart':'قلب ذهبي',
'dragon flame':'لهب التنين','sword':'سيف','shield':'درع','halo':'هالة',
'wings':'أجنحة','balloon':'بالون','gift':'هدية','present':'هدية',
'music':'موسيقى','trophy':'كأس','medal':'وسام','flag':'علم','wizard':'ساحر',
'ninja':'نينجا','pirate':'قراصنة','santa':'سانتا','flower':'زهرة',
'crown prince':'ولي عهد','neon heart':'قلب نيون','silver heart':'قلب فضي',
'black heart':'قلب أسود','broken heart':'قلب مكسور','fire heart':'قلب محترق',
'sparkling heart':'قلب لامع','yellow heart':'قلب أصفر','green heart':'قلب أخضر',
'money':'مال','cash':'كاش','money rain':'مطر مال','viking':'فايكنغ',
'pharaoh':'فرعون','thumbs up':'إبهام','smile':'ابتسامة','love':'حب',
'kiss':'قبلة','bandage':'ضماد','ghost':'شبح','skull':'جمجمة','sun':'شمس',
'moon':'قمر','comet':'مذنب','planet':'كوكب','wolf':'ذئب','fox':'ثعلب',
'rabbit':'أرنب','gold bar':'سبيكة ذهب','gold coin':'عملة ذهبية',
'money bag':'كيس مال','diamond crown':'تاج ماسي','diamond heart':'قلب ماسي',
'super star':'نجمة خارقة','mega star':'نجمة عملاقة','legend':'أسطوري',
'epic':'ملحمي','bow':'قوس','arrow':'سهم','cherry':'كرز','apple':'تفاحة',
'grape':'عنب','watermelon':'بطيخ','strawberry':'فراولة','banana':'موز',
'peach':'خوخ','cupcake':'كعكة صغيرة','sparkler':'شرارة','lantern':'مصباح',
'candle':'شمعة','ribbon':'شريط','gift box':'صندوق هدية','party hat':'قبعة حفلة',
'confetti':'قصاصات ورقية','knight':'فرس','snowman':'رجل ثلج',
'flower garden':'حديقة زهور','treasure':'كنز','crystal ball':'كرة بلورية',
'tropical island':'جزيرة استوائية','royal carriage':'عربة ملكية',
'treasure chest':'كنز','100':'100',
};
const GIFT_VALUES = {
5953:25, 5952:1, 5951:5, 5950:10, 5949:15, 5948:20,
5947:30, 5946:50, 5945:100, 5944:200, 5943:500,
5942:1000, 5941:2000, 5940:5000, 5939:10000,
5938:25000, 5937:50000, 5936:100000,
5935:1, 5934:3, 5933:5, 5932:10, 5931:15,
5930:20, 5929:30, 5928:40, 5927:50, 5926:60,
5925:80, 5924:100, 5923:150, 5922:200, 5921:300,
5920:400, 5919:500, 5918:700, 5917:1000,
5916:1500, 5915:2000, 5914:3000, 5913:5000,
5912:10000, 5911:20000, 5910:50000, 5909:100000,
5908:250000, 5907:500000, 5906:1000000,
5905:10, 5904:25, 5903:50, 5902:100,
5901:200, 5900:500, 5899:1000, 5898:2000,
5897:5000, 5896:10000, 5895:20000, 5894:50000,
5893:100000, 5892:250000, 5891:500000, 5890:1000000,
5729:1, 5728:5, 5727:10, 5726:15, 5725:20,
5724:30, 5723:50, 5722:100, 5721:200, 5720:500,
5719:1000, 5718:2000, 5717:5000, 5716:10000,
5715:25000, 5714:50000, 5713:100000,
5712:250000, 5711:500000, 5710:1000000,
5972:1, 5971:1, 5970:1, 5969:1, 5968:3,
5967:5, 5966:10, 5965:15, 5964:20, 5963:30,
5962:40, 5961:50, 5960:100,
1817:1, 1816:1, 1815:1, 1814:1, 1813:1,
1812:1, 1811:1, 1810:5, 1809:5, 1808:5,
1807:5, 1806:10, 1805:10, 1804:10,
1803:15, 1802:20, 1801:25, 1800:30,
1799:35, 1798:40, 1797:50, 1796:60,
1795:70, 1794:80, 1793:90, 1792:100,
1791:150, 1790:200, 1789:250, 1788:300,
1787:400, 1786:500, 1785:700, 1784:1000,
1783:1500, 1782:2000, 1781:3000, 1780:5000,
1779:7000, 1778:10000, 1777:15000, 1776:20000,
1775:30000, 1774:50000, 1773:75000, 1772:100000,
7934:1, 7933:1, 7932:1, 7931:1, 7930:1,
7929:1, 7928:1, 7927:1, 7926:1, 7925:1,
7924:5, 7923:5, 7922:5, 7921:5, 7920:10,
7919:10, 7918:10, 7917:15, 7916:15, 7915:20,
7914:20, 7913:25, 7912:25, 7911:30, 7910:50,
7909:50, 7908:50, 7907:50, 7906:50, 7905:100,
7904:100, 7903:100, 7902:150, 7901:200, 7900:200,
7899:300, 7898:300, 7897:300, 7896:500, 7895:500,
7894:500, 7893:700, 7892:1000, 7891:1000, 7890:1000,
7889:1500, 7888:1500, 7887:2000, 7886:2000, 7885:2000,
7884:3000, 7883:3000, 7882:5000, 7881:5000, 7880:5000,
7879:7000, 7878:7000, 7877:10000, 7876:10000, 7875:10000,
7874:15000, 7873:20000, 7872:20000, 7871:25000, 7870:25000,
7869:50000, 7868:50000, 7867:75000, 7866:75000, 7865:100000,
7864:100000, 7863:250000, 7862:250000, 7861:500000, 7860:500000,
7859:1000000, 7858:1000000,
};
function getCountryInfo(code) {
if (!code) return { name: 'غير محدد', flag: '🌍' };
return COUNTRY_FLAGS[code.toUpperCase()] || { name: code, flag: '🌍' };
}
function getGiftArabicName(englishName, giftId) {
if (!englishName) {
const val = GIFT_VALUES[giftId];
return val ? '💎' + val : 'هدية';
}
const lower = englishName.toLowerCase().trim();
return GIFT_ARABIC[lower] || englishName;
}
function getGiftDiamonds(data) {
if (data.diamondCount && data.diamondCount > 0) return data.diamondCount;
const ext = data.extendedGiftInfo || {};
if (ext.diamond_count && ext.diamond_count > 0) return ext.diamond_count;
if (ext.diamondCount && ext.diamondCount > 0) return ext.diamondCount;
const gid = data.giftId;
if (GIFT_VALUES[gid]) return GIFT_VALUES[gid];
if (data.gift?.coinValue && data.gift.coinValue > 0) return data.gift.coinValue;
if (data.gift?.diamondCount && data.gift.diamondCount > 0) return data.gift.diamondCount;
return 1;
}
function formatK(num) {
if (!num || isNaN(num) || num === 0) return '0';
if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
return num.toString();
}
function formatDuration(seconds) {
if (!seconds || seconds <= 0) return 'دقيقة واحدة';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
const parts = [];
if (h > 0) parts.push(h + ' ساعة');
if (m > 0) parts.push(m + ' دقيقة');
if (s > 0 && h === 0) parts.push(s + ' ثانية');
return parts.join(' و ') || 'أقل من دقيقة';
}
function getBaghdadTime() {
return new Intl.DateTimeFormat('ar-IQ', {
timeZone: 'Asia/Baghdad', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true
}).format(new Date());
}
function generateProgressBar(ourScore, theirScore, length = 10) {
const total = (ourScore || 0) + (theirScore || 0);
if (total === 0) return "⬜".repeat(length);
const ourPercent = Math.min(Math.max(Math.round(((ourScore || 0) / total) * length), 0), length);
return "🟦".repeat(ourPercent) + "🟥".repeat(length - ourPercent);
}
// ====== HTTP POST ======
function httpPost(url, payload, timeout = 15000) {
return new Promise((resolve, reject) => {
const urlObj = new URL(url);
const protocol = urlObj.protocol === 'https:' ? https : http;
const body = JSON.stringify(payload);
const req = protocol.request({
hostname: urlObj.hostname,
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
path: urlObj.pathname + urlObj.search,
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
timeout: timeout
}, (res) => {
let responseData = '';
res.on('data', chunk => responseData += chunk);
res.on('end', () => resolve({ statusCode: res.statusCode, data: responseData }));
});
req.on('error', reject);
req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); });
req.write(body);
req.end();
});
}
// ====== ✅ جلب الدولة (fetch يدعم gzip تلقائياً) ======
async function getRegionFromPage(username) {
try {
const response = await fetch('https://www.tiktok.com/@' + username, {
headers: {
'User-Agent': 'Mozilla/5.0 (Linux; Android 13) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9,ar;q=0.8',
},
redirect: 'follow',
signal: AbortSignal.timeout(15000)
});
if (!response.ok) return null;
const html = await response.text();
const pattern = /<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" type="application\/json">(.*?)<\/script>/s;
const match = html.match(pattern);
if (!match) return null;
const data = JSON.parse(match[1]);
const scope = data['__DEFAULT_SCOPE__'] || {};
const webapp = scope['webapp.user-detail'] || {};
const userInfo = webapp['userInfo'] || {};
const user = userInfo['user'] || {};
return {
region: user['region'] || null,
nickname: user['nickname'] || username,
verified: user['verified'] || false
};
} catch (e) {
return null;
}
}
// ====== تليقرام ======
async function sendToTelegram(text, photoUrl = null, buttons = null) {
try {
const payload = {
chat_id: TELEGRAM_CHAT_ID,
parse_mode: 'HTML',
disable_web_page_preview: true
};
if (buttons) payload.reply_markup = JSON.stringify({ inline_keyboard: buttons });
if (photoUrl) {
payload.photo = photoUrl;
payload.caption = text;
await httpPost(`${TELEGRAM_API_URL}/bot${TELEGRAM_TOKEN}/sendPhoto`, payload);
} else {
payload.text = text;
await httpPost(`${TELEGRAM_API_URL}/bot${TELEGRAM_TOKEN}/sendMessage`, payload);
}
} catch (e) {
console.log("⚠️ فشل الإرسال:", e.message);
}
}
// ====== كاش (تم تصحيحه من const إلى let) ======
let regionCache = {};
async function fetchUserRegion(username) {
if (!username) return null;
if (regionCache[username]) return regionCache[username];
const result = await getRegionFromPage(username);
if (result) regionCache[username] = result;
return result;
}
// ====== متغيرات ======
let maxViewers = 0, totalLikes = 0, totalShares = 0;
let streamStartTime = null;
let giftersMap = {};
let pkActive = false;
let pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
let totalGiftCount = 0;
let totalGiftValue = 0;
let isEndingStream = false; // ✅ لمنع التكرار
function getTopGifters(map, top = 5) {
return Object.values(map).sort((a, b) => b.coins - a.coins).slice(0, top);
}
// ====== إرسال إشعار بداية البث ======
async function sendStartNotification(state) {
const userRegion = await getRegionFromPage(TIKTOK_USERNAME);
const countryInfo = getCountryInfo(userRegion?.region || null);
const liveLink = 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live';
let avatarUrl = '';
const owner = state.roomInfo?.owner || null;
if (owner) {
if (owner.profilePicture) avatarUrl = owner.profilePicture;
else if (owner.profilePictureUrl) avatarUrl = owner.profilePictureUrl;
else if (owner.profileThumbnail) avatarUrl = owner.profileThumbnail;
else if (owner.avatarLarge?.urlList?.[0]) avatarUrl = owner.avatarLarge.urlList[0];
else if (owner.avatarLarge?.url?.[0]) avatarUrl = owner.avatarLarge.url[0];
else if (owner.avatarThumb?.urlList?.[0]) avatarUrl = owner.avatarThumb.urlList[0];
else if (owner.avatarThumb?.url?.[0]) avatarUrl = owner.avatarThumb.url[0];
else if (owner.avatar?.urlList?.[0]) avatarUrl = owner.avatar.urlList[0];
else if (owner.avatar?.url?.[0]) avatarUrl = owner.avatar.url[0];
}
if (!avatarUrl) {
avatarUrl = state.roomInfo?.sharedCover || state.roomInfo?.coverUrl || '';
}
const displayName = userRegion?.nickname || TIKTOK_USERNAME;
const verifiedBadge = userRegion?.verified ? ' ✅' : '';
const msg = '🔴 ' + displayName + verifiedBadge + '\n\n' +
'🌐 @' + TIKTOK_USERNAME + '\n' +
countryInfo.flag + ' ' + countryInfo.name + '\n' +
'⏰ ' + getBaghdadTime();
sendToTelegram(msg, avatarUrl || undefined, [[{ text: "📺 دخول البث المباشر", url: liveLink }]]);
console.log('📸 صورة: ' + (avatarUrl ? '✅' : '❌'));
}
// ====== ربط الأحداث ======
function attachEvents(conn) {
conn.on(WebcastEvent.ROOM_USER, data => {
if (data.viewerCount > maxViewers) maxViewers = data.viewerCount;
});
conn.on(WebcastEvent.LIKE, data => {
const lc = data.likeCount || 0;
if (lc > 0) totalLikes += lc;
if (pkActive) pkInfo.ourLikes += lc;
});
conn.on(WebcastEvent.SOCIAL, () => { totalShares++; });
conn.on(WebcastEvent.GIFT, async data => {
const userObj = data.user || {};
const giftObj = data.gift || {};
const extObj = data.extendedGiftInfo || {};
const gifterUsername = data.uniqueId || userObj.uniqueId || userObj.userName || '';
const nickname = data.nickname || userObj.nickname || userObj.displayName || '';
const giftId = data.giftId || giftObj.giftId || giftObj.id || extObj.id || 0;
const giftNameEn = data.giftName || giftObj.name || extObj.name || '';
const repeatCount = data.repeatCount || giftObj.repeatCount || 1;
const giftType = data.giftType || giftObj.giftType || 0;
const repeatEnd = data.repeatEnd !== undefined ? data.repeatEnd : (giftObj.repeatEnd ? true : false);
if (giftType === 1 && !repeatEnd) return;
const baseDiamonds = getGiftDiamonds(data);
const giftCost = baseDiamonds * repeatCount;
totalGiftCount++;
totalGiftValue += giftCost;
const arabicName = getGiftArabicName(giftNameEn, giftId);
if (!gifterUsername) return;
const userId = data.userId || userObj.userId || gifterUsername;
if (!giftersMap[userId]) {
giftersMap[userId] = {
name: nickname || gifterUsername,
username: gifterUsername,
coins: 0, region: null, flag: '🌍', gifts: 0
};
}
giftersMap[userId].coins += giftCost;
giftersMap[userId].gifts += repeatCount;
const gifterData = await fetchUserRegion(gifterUsername);
let region = null;
let displayName = nickname || gifterUsername;
if (gifterData && gifterData.region) {
region = gifterData.region;
displayName = gifterData.nickname || displayName;
giftersMap[userId].region = region;
}
const gc = getCountryInfo(region);
giftersMap[userId].flag = gc.flag;
const repeatText = repeatCount > 1 ? ' ×' + repeatCount : '';
const msg = '🎁 ' + arabicName + repeatText + '\n\n' +
gc.flag + ' ' + displayName + '\n' +
'📱 @' + gifterUsername + '\n' +
'💎 ' + formatK(giftCost) + '\n' +
'🌍 ' + gc.name;
sendToTelegram(msg, null, [[
{ text: "👤 حسابه", url: 'https://www.tiktok.com/@' + gifterUsername },
{ text: "📺 دخول البث", url: 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live' }
]]);
});
conn.on(WebcastEvent.FOLLOW, async data => {
const fu = data.uniqueId || '';
if (!fu) return;
const fd = await fetchUserRegion(fu);
let region = null;
let dn = data.nickname || fu;
if (fd && fd.region) { region = fd.region; dn = fd.nickname || dn; }
const gc = getCountryInfo(region);
sendToTelegram('➕ متابع جديد!\n\n' + gc.flag + ' ' + dn + '\n📱 @' + fu + '\n🌍 ' + gc.name);
});
conn.on(WebcastEvent.ROOM_STATS, data => {
if (data.totalLikeCount) totalLikes = data.totalLikeCount;
});
conn.on('pkStart', data => {
pkActive = true;
pkInfo = { opponentName: data.opponentNickname || 'منافس', ourLikes: 0, theirLikes: 0 };
sendToTelegram('⚔️ ' + pkInfo.opponentName, null, [[{ text: "🚀 دعم البث", url: 'https://www.tiktok.com/@' + TIKTOK_USERNAME + '/live' }]]);
});
conn.on('pkUpdate', data => {
pkInfo.ourLikes = data.ourLikes || 0;
pkInfo.theirLikes = data.theirLikes || 0;
});
conn.on('pkEnd', data => {
pkActive = false;
sendToTelegram('🏆 ' + (data.winnerNickname || 'تعادل') + '\n\n' +
'🟦 نحن: ' + formatK(pkInfo.ourLikes) + ' | ' + formatK(pkInfo.theirLikes) + ' 🟥\n\n' +
generateProgressBar(pkInfo.ourLikes, pkInfo.theirLikes));
});
}
// ====== نهاية البث ======
function onStreamEnd() {
if (isEndingStream) return; // ✅ منع التكرار
isEndingStream = true;
const duration = streamStartTime ? formatDuration(Math.floor((Date.now() - streamStartTime) / 1000)) : 'غير معروف';
const top = getTopGifters(giftersMap, 5);
const medals = ['🥇', '🥈', '🥉', '4️⃣', '5️⃣'];
let topText = top.map((g, i) =>
medals[i] + ' ' + (g.flag || '🌍') + ' ' + g.name + '\n @' + g.username + ' → ' + formatK(g.coins) + ' 💎 | ' + g.gifts + ' 🎁'
).join('\n\n') || 'لا يوجد';
const countryStats = {};
Object.values(giftersMap).forEach(g => {
const r = g.region || 'XX';
countryStats[r] = (countryStats[r] || 0) + g.coins;
});
let countryRanking = Object.entries(countryStats)
.sort((a, b) => b[1] - a[1]).slice(0, 3)
.map(([r, c], i) =>
['👑', '🥈', '🥉'][i] + ' ' + getCountryInfo(r).flag + ' ' + getCountryInfo(r).name + ' → ' + formatK(c) + ' 💎'
).join('\n') || 'لا بيانات';
sendToTelegram('📊 التقرير النهائي\n\n' +
'━━━━━━━━━━━━━━━━━━━━\n' +
'⏱️ مدة البث: ' + duration + '\n' +
'👥 أعلى مشاهدات: ' + formatK(maxViewers) + '\n' +
'❤️ إعجابات: ' + formatK(totalLikes) + '\n' +
'↪️ مشاركات: ' + formatK(totalShares) + '\n' +
'🎁 إجمالي الهدايا: ' + formatK(totalGiftCount) + '\n' +
'💎 إجمالي القيم: ' + formatK(totalGiftValue) + '\n' +
'👥 عدد الداعمين: ' + Object.keys(giftersMap).length + '\n' +
'━━━━━━━━━━━━━━━━━━━━\n\n' +
'🏆 أقوى داعمين:\n\n' + topText + '\n\n' +
'🌍 توزيع حسب الدولة:\n' + countryRanking + '\n\n💤 بانتظار البث القادم...');
console.log('📴 انتهى البث');
}
// ====== إعادة الاتصال ======
let reconnectTimer = null;
function scheduleReconnect(delay) {
if (reconnectTimer) clearTimeout(reconnectTimer);
reconnectTimer = setTimeout(tryConnect, delay);
}
// ====== الاتصال ======
let activeConn = null;
async function tryConnect() {
// ✅ تنظيف أي اتصال سابق
if (activeConn) {
try { activeConn.disconnect(); } catch (e) {}
activeConn = null;
}
// إعادة ضبط المتغيرات
isEndingStream = false;
maxViewers = 0;
totalLikes = 0;
totalShares = 0;
totalGiftCount = 0;
totalGiftValue = 0;
giftersMap = {};
regionCache = {};
pkActive = false;
pkInfo = { opponentName: "", ourLikes: 0, theirLikes: 0 };
streamStartTime = Date.now();
console.log('⏳ محاولة الاتصال: @' + TIKTOK_USERNAME);
activeConn = new TikTokLiveConnection(TIKTOK_USERNAME, {
processInitialData: true,
enableExtendedGiftInfo: true,
fetchRoomInfoOnConnect: true,
clientParams: { app_language: "ar-IQ", device_platform: "web" }
});
attachEvents(activeConn);
// ✅ ربط أحداث الانقطاع
activeConn.on(WebcastEvent.DISCONNECTED, () => {
console.log('❌ قطع الاتصال');
if (streamStartTime) onStreamEnd();
scheduleReconnect(30000);
});
activeConn.on('streamEnd', () => {
console.log('📴 انتهى البث');
onStreamEnd();
scheduleReconnect(30000);
});
try {
const state = await activeConn.connect();
console.log('✅ متصل بالغرفة!');
console.log('📡 Room ID:', state.roomId);
await sendStartNotification(state);
} catch (e) {
let errMsg = '';
if (e && typeof e === 'object') errMsg = e.message || e.name || String(e);
else errMsg = String(e);
console.log('🔎 غير متاح: ' + errMsg);
scheduleReconnect(60000);
}
}
// ====== التشغيل ======
console.log('✅ جاهز | @' + TIKTOK_USERNAME);
setTimeout(tryConnect, 2000);
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('OK');
});
server.listen(7860, '0.0.0.0', () => {
console.log('🖥️ الخادم: 7860');
setInterval(() => {
http.get('http://localhost:7860', r => r.resume()).on('error', () => {});
}, 120000);
});