import { createClient } from 'bedrock-protocol' import { createServer } from 'http' const SERVER_HOST = 'Super7arbcraftnews.aternos.me' const SERVER_PORT = 57611 const BOT_USERNAME = '24hour' const RECONNECT_DELAY_MS = 15_000 let reconnectTimer = null let isShuttingDown = false let currentClient = null let reconnectCount = 0 let status = 'connecting' let lastError = null let connectedAt = null function log(msg, extra = {}) { const time = new Date().toISOString() console.log(JSON.stringify({ time, msg, ...extra })) } function connect() { if (isShuttingDown) return reconnectCount++ status = 'connecting' log('🔄 البوت يحاول الاتصال...', { host: SERVER_HOST, port: SERVER_PORT, username: BOT_USERNAME, attempt: reconnectCount }) let client try { client = createClient({ host: SERVER_HOST, port: SERVER_PORT, username: BOT_USERNAME, offline: true, skipPing: false, connectTimeout: 30_000, }) } catch (err) { log('❌ فشل إنشاء الاتصال', { error: err.message }) lastError = err.message status = 'error' scheduleReconnect() return } currentClient = client client.on('error', (err) => { log('⚠️ خطأ — سيتم إعادة المحاولة', { error: err.message }) lastError = err.message status = 'error' currentClient = null scheduleReconnect() }) client.on('spawn', () => { reconnectCount = 0 status = 'connected' connectedAt = new Date().toISOString() lastError = null log('✅ البوت دخل السيرفر بنجاح!', { username: BOT_USERNAME }) }) client.on('text', (packet) => { log('📩 رسالة', { from: packet.source_name, msg: packet.message }) }) client.on('disconnect', (reason) => { log('📴 انفصل — سيتم إعادة الاتصال', { reason: reason?.message ?? 'unknown' }) status = 'disconnected' currentClient = null scheduleReconnect() }) client.on('close', () => { log('🔌 الاتصال أُغلق — سيتم إعادة الاتصال') status = 'disconnected' currentClient = null scheduleReconnect() }) } function scheduleReconnect() { if (isShuttingDown) return if (reconnectTimer) return log(`⏳ إعادة الاتصال خلال ${RECONNECT_DELAY_MS / 1000} ثوانٍ...`) reconnectTimer = setTimeout(() => { reconnectTimer = null connect() }, RECONNECT_DELAY_MS) } process.on('uncaughtException', (err) => { if (err.message?.includes('timed out') || err.message?.includes('ETIMEDOUT')) { log('⏰ انتهت مهلة الاتصال — سيتم إعادة المحاولة', { error: err.message }) status = 'timeout' lastError = err.message currentClient = null scheduleReconnect() } else { log('💥 خطأ غير معالَج', { error: err.message, stack: err.stack }) } }) process.on('unhandledRejection', (reason) => { log('🚫 promise مرفوضة', { reason: String(reason) }) }) const httpServer = createServer((req, res) => { const uptime = Math.floor(process.uptime()) const html = `
السيرفر: ${SERVER_HOST}:${SERVER_PORT}
اسم البوت: ${BOT_USERNAME}
عدد محاولات الاتصال: ${reconnectCount}
وقت التشغيل: ${Math.floor(uptime / 3600)}س ${Math.floor((uptime % 3600) / 60)}د ${uptime % 60}ث
${connectedAt ? `آخر اتصال: ${connectedAt}
` : ''} ${lastError ? `آخر خطأ: ${lastError}
` : ''}