Spaces:
Paused
Paused
Update bot.js
Browse files1234567891011121314151617181920212223242526272829303132333435363738234567891011121341424344454647484950515253141516171819202122232425565758596061626364656667686970717273747576777879808182838485868788899026272829309293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136313233343536373839404142434445464748495051521401415354555614314414514614757585960611491501511521531541551561576263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112161162113114115116164165166167168169170171172173174175176177117118119120121122123124125126127128129130131132181182133134135136184137138139140141142143144145146147148149150151152186187188189190153154155156157158159160161162163164165166167168169170171172173174175176177178192179180181182183195184185const TelegramBot = require('node-telegram-bot-api');const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg');const ffmpeg = require('fluent-ffmpeg');const si = require('systeminformation');
const TOKEN = '7899900752:AAE6xg24cB29m2O7_-Ox8P9e0Fhmyw6Y8bo';const ADMIN_ID = 7708913693;
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
const bot = new TelegramBot(TOKEN, { polling: true });
const userStreams = {}; // { chatId: { streamId: { proc, timeout } } }const streamCounter = {}; // { chatId: number }
function getSystemSettings() { return si.cpu() .then(cpu => si.mem() .then(mem => { const cores = cpu.cores || 1; const ramGB = mem.total / 1024 / 1024 / 1024;
let preset = 'ultrafast'; if (cores >= 8) preset = 'faster'; else if (cores >= 4) preset = 'veryfast';
let bitrate = '800k'; let resolution = '640x360'; if (ramGB >= 8) { bitrate = '3000k'; resolution = '1280x720'; } else if (ramGB >= 4) { bitrate = '1500k'; resolution = '854x480'; } return { preset, bitrate, resolution }; }) );const { spawn } = require('child_process');const ffmpegPath = require('@ffmpeg-installer/ffmpeg').path;const os = require('os');
// Initialize Telegram bot with pollingconst token = '7899900752:AAFUdjznKaXgSkpp7eqFJjXanpb9eQVqw6E';if (!token) { console.error('خطأ: يجب تعيين TELEGRAM_BOT_TOKEN في الكود'); process.exit(1);}const bot = new TelegramBot(token, { polling: true });
function usageExample(chatId) { return bot.sendMessage(chatId, `❌ الأمر غير صحيح أو غير مكتمل.\n\n` + `استخدم أحد الأوامر التالية:\n\n` + `/stream streamkey m3u8_url [cc_text]\n` + `مثال:\n` + `/stream FB-123456789 https://example.com/stream.m3u8 مرحباً بالعالم\n\n` + `/stop stream_id\n` + `مثال:\n` + `/stop 1\n\n` + `/check\n` + `لعرض معلومات النظام` );// Admin user ID (replace with your actual user ID)const ADMIN_USER_ID = '7708913693'; // TODO: Replace with your Telegram user ID
// Store active streams: { id: { process: childProcess, chatId: number, rtmpsUrl: string } }const activeStreams = new Map();
// Helper function to log with timestampfunction logToConsole(message) { const timestamp = new Date().toISOString(); console.log(`[${timestamp}] ${message}`);}
// /streambot.onText(/^\/stream(?:\s+(.+))?$/, async (msg, match) => { const chatId = msg.chat.id; const argsText = match[1]; if (!argsText) return usageExample(chatId);
const args = argsText.trim().split(/\s+/); if (args.length < 2) return usageExample(chatId);
const key = args[0]; const m3u8 = args[1]; const ccText = args.slice(2).join(' ');
if (!streamCounter[chatId]) streamCounter[chatId] = 0; streamCounter[chatId]++; const streamId = streamCounter[chatId];
try { const { preset, bitrate, resolution } = await getSystemSettings();
let command = ffmpeg(m3u8) .videoCodec('libx264') .audioCodec('aac') .outputOptions([ `-preset ${preset}`, `-b:v ${bitrate}`, '-f', 'flv' ]) .size(resolution);
if (ccText && ccText.trim() !== '') { const filter = `drawbox=x=(w-text_w)/2-10:y=h-text_h-40:w=text_w+20:h=text_h+30:color=black@0.5:t=max,` + `drawtext=text='${ccText}':fontcolor=white:fontsize=24:x=(w-text_w)/2:y=h-text_h-30`; command = command.videoFilters(filter); }// Generate a random 4-digit IDfunction generateStreamId() { return Math.floor(1000 + Math.random() * 9000).toString();}
const rtmpUrl = `rtmps://live-api-s.facebook.com:443/rtmp/${key}`; command = command.output(rtmpUrl);
const proc = command.spawn();
if (!userStreams[chatId]) userStreams[chatId] = {}; userStreams[chatId][streamId] = { proc };
const timeout = setTimeout(() => { if (proc && !proc.killed) { proc.kill('SIGTERM'); bot.sendMessage(chatId, `⏹️ تم إيقاف البث معرف ${streamId} تلقائياً بعد 4 ساعات.`); delete userStreams[chatId][streamId]; } }, 4 * 60 * 60 * 1000);
userStreams[chatId][streamId].timeout = timeout;
bot.sendMessage(chatId, `✅ تم بدء البث بنجاح!\n\n` + `▶️ معرف البث: ${streamId}\n` + `الدقة: ${resolution}\n` + `معدل البت: ${bitrate}\n` + `الإعدادات: ${preset}\n` + `⏳ سيتم إيقاف البث تلقائياً بعد 4 ساعات` );
proc.on('error', err => { bot.sendMessage(chatId, `❌ حدث خطأ في البث معرف ${streamId}:\n${err.message}`); clearTimeout(timeout); delete userStreams[chatId][streamId]; });
proc.on('exit', (code, signal) => { if (signal === 'SIGTERM') { bot.sendMessage(chatId, `⏹️ تم إيقاف البث معرف ${streamId}.`); } else if (code !== 0) { bot.sendMessage(chatId, `⚠️ البث معرف ${streamId} انتهى برمز خروج ${code}.`); } clearTimeout(timeout); delete userStreams[chatId][streamId]; });
} catch (e) { return bot.sendMessage(chatId, `❌ فشل بدء البث:\n${e.message}`);// Check if user is adminfunction isAdmin(userId) { return userId.toString() === ADMIN_USER_ID;}
// Handle /start commandbot.onText(/\/start/, (msg) => { const userId = msg.from.id; const chatId = msg.chat.id; if (!isAdmin(userId)) { bot.sendMessage(chatId, 'خطأ: لست مخولًا لاستخدام هذا البوت'); logToConsole(`Unauthorized user ${userId} sent /start`); return; } const message = 'مرحبًا! أنا بوت بث الفيديو. استخدم الأوامر التالية:\n' + '/stream <مفتاح_فيسبوك> <رابط_m3u8> - لبدء البث\n' + '/check - لعرض معلومات النظام\n' + '/stop <رقم_البث> - لإيقاف البث'; bot.sendMessage(chatId, message); logToConsole(`User ${userId} sent /start`);});
// /stopbot.onText(/^\/stop(?:\s+(\d+))?$/, (msg, match) => {// Handle /stream <fbkey> <m3u8>bot.onText(/\/stream (.+) (.+)/, (msg, match) => { const userId = msg.from.id; const chatId = msg.chat.id; const streamId = match[1] ? Number(match[1]) : null; if (!streamId) return usageExample(chatId);
if (!userStreams[chatId] || !userStreams[chatId][streamId]) { return bot.sendMessage(chatId, `⚠️ لا يوجد بث نشط بالمعرف ${streamId}.`); if (!isAdmin(userId)) { bot.sendMessage(chatId, 'خطأ: لست مخولًا لاستخدام هذا البوت'); logToConsole(`Unauthorized user ${userId} attempted /stream`); return; }
const { proc, timeout } = userStreams[chatId][streamId]; if (proc && !proc.killed) { proc.kill('SIGTERM'); clearTimeout(timeout); bot.sendMessage(chatId, `⏹️ تم إيقاف البث معرف ${streamId} من قبلك.`); delete userStreams[chatId][streamId]; } else { bot.sendMessage(chatId, `⚠️ البث معرف ${streamId} متوقف بالفعل.`); const fbKey = match[1].trim(); const m3u8Url = match[2].trim(); const rtmpsUrl = `rtmps://live-api-s.facebook.com:443/rtmp/${fbKey}`;
// Validate inputs if (!m3u8Url.startsWith('http') || !rtmpsUrl.startsWith('rtmps')) { bot.sendMessage(chatId, 'خطأ: رابط M3U8 أو RTMPS غير صالح'); logToConsole(`Invalid URLs for user ${userId}: ${m3u8Url}, ${rtmpsUrl}`); return; }
// Generate unique stream ID let streamId; do { streamId = generateStreamId(); } while (activeStreams.has(streamId));
// Single-line FFmpeg command with reconnect and 5-second delay const ffmpegCommand = `ffmpeg -reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5 -itsoffset 5 -re -i "${m3u8Url}" -c:v copy -c:a aac -f flv "${rtmpsUrl}"`; logToConsole(`Executing FFmpeg for Stream ${streamId}: ${ffmpegCommand}`);
// Start FFmpeg process const ffmpegProcess = spawn(ffmpegCommand, { shell: true });
ffmpegProcess.stdout.on('data', (data) => { logToConsole(`FFmpeg stdout (Stream ${streamId}): ${data}`); });
ffmpegProcess.stderr.on('data', (data) => { logToConsole(`FFmpeg stderr (Stream ${streamId}): ${data}`); });
ffmpegProcess.on('spawn', () => { bot.sendMessage(chatId, `تم بدء البث برقم تعريف: ${streamId}`); activeStreams.set(streamId, { process: ffmpegProcess, chatId, rtmpsUrl }); logToConsole(`Stream ${streamId} started for user ${userId}`); });
ffmpegProcess.on('error', (err) => { bot.sendMessage(chatId, `فشل البث ${streamId}: ${err.message}`); logToConsole(`FFmpeg error (Stream ${streamId}): ${err.message}`); activeStreams.delete(streamId); });
ffmpegProcess.on('close', (code) => { bot.sendMessage(chatId, `انتهى البث ${streamId} (رمز الخروج: ${code}).`); logToConsole(`FFmpeg closed (Stream ${streamId}) with code ${code}`); activeStreams.delete(streamId); });});
// /checkbot.onText(/\/check/, async (msg) => {// Handle /checkbot.onText(/\/check/, (msg) => { const userId = msg.from.id; const chatId = msg.chat.id; try { const cpu = await si.cpu(); const mem = await si.mem(); const osInfo = await si.osInfo();
const message = `<b>معلومات النظام:</b>نظام التشغيل: ${osInfo.distro} ${osInfo.release}المعالج: ${cpu.manufacturer} ${cpu.brand} (${cpu.cores} أنوية)الذاكرة: ${(mem.total / 1024 / 1024 / 1024).toFixed(2)} GB `; bot.sendMessage(chatId, message, { parse_mode: 'HTML' }); } catch (err) { bot.sendMessage(chatId, `❌ خطأ في جلب معلومات النظام: ${err.message}`); if (!isAdmin(userId)) { bot.sendMessage(chatId, 'خطأ: لست مخولًا لاستخدام هذا البوت'); logToConsole(`Unauthorized user ${userId} attempted /check`); return; } const systemInfo = `معلومات النظام:- استخدام المعالج: ${Math.round(os.loadavg()[0] * 100) / 100}% (متوسط دقيقة واحدة)- الذاكرة الحرة: ${(os.freemem() / 1024 / 1024 / 1024).toFixed(2)} غيغابايت- إجمالي الذاكرة: ${(os.totalmem() / 1024 / 1024 / 1024).toFixed(2)} غيغابايت- البثوث النشطة: ${activeStreams.size} `; bot.sendMessage(chatId, systemInfo); logToConsole(`User ${userId} requested /check`);});
// رد افتراضيbot.on('message', (msg) => {// Handle /stop <number>bot.onText(/\/stop (\d{4})/, (msg, match) => { const userId = msg.from.id; const chatId = msg.chat.id; const text = msg.text || ""; if (!isAdmin(userId)) { bot.sendMessage(chatId, 'خطأ: لست مخولًا لاستخدام هذا البوت'); logToConsole(`Unauthorized user ${userId} attempted /stop ${match[1]}`); return; } const streamId = match[1];
if (!activeStreams.has(streamId)) { bot.sendMessage(chatId, `لا يوجد بث برقم تعريف: ${streamId}`); logToConsole(`User ${userId} tried to stop non-existent stream ${streamId}`); return; }
const stream = activeStreams.get(streamId); logToConsole(`Attempting to stop FFmpeg process for Stream ${streamId} (PID: ${stream.process.pid})`);
if ( text.startsWith('/stream') || text.startsWith('/stop') || text.startsWith('/check') ) return; // Try SIGTERM first, then SIGKILL after 5 seconds if not terminated stream.process.kill('SIGTERM'); const timeout = setTimeout(() => { if (activeStreams.has(streamId)) { stream.process.kill('SIGKILL'); logToConsole(`Force-killed FFmpeg process for Stream ${streamId} (PID: ${stream.process.pid})`); } }, 5000);
stream.process.on('close', (code) => { clearTimeout(timeout); // Cancel SIGKILL if process closes bot.sendMessage(chatId, `انتهى البث ${streamId} (رمز الخروج: ${code}).`); logToConsole(`FFmpeg closed (Stream ${streamId}) with code ${code}`); activeStreams.delete(streamId); });
bot.sendMessage(chatId, `تم إيقاف البث ${streamId}.`); logToConsole(`User ${userId} stopped stream ${streamId}`); activeStreams.delete(streamId); // Ensure cleanup even if close event is delayed});
// Log errorsbot.on('error', (err) => { logToConsole(`Bot error: ${err.message}`);});
usageExample(chatId);// Handle polling errorsbot.on('polling_error', (err) => { logToConsole(`Polling error: ${err.message}`);});
console.log('🤖 البوت يعمل الآن...');logToConsole('Bot started');console.log('البوت يعمل...');bot.js+162-172