Spaces:
Paused
Paused
Update bot.js
Browse files6 unmodified lines7891011121314151617181920212223242526272829303132333435363738397 unmodified lines474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920017 unmodified lines21821922022122222322432 unmodified lines25725825926026126275 unmodified lines33833934034134234334434534634734834919 unmodified lines36937037137237337437537637737837938038138238338438522 unmodified lines40840941041141241341441541641741841918 unmodified lines4384394404414424434443 unmodified lines44844945045145245345445545645745845921 unmodified lines48148248348448548648748848911 unmodified lines50150250350450550650750850951051151251351451551651751814 unmodified lines5335345355365375385394 unmodified lines54454554654754854955021 unmodified lines57257357457557657757822 unmodified lines6016026036046056066076086096106116126136146156166176186192 unmodified lines62262362462562662762862963063163263363463563625 unmodified lines66266366466566666766821 unmodified lines6906916926936946956966 unmodified linesconst { SocksClient } = require('socks');const { Client } = require('ssh2');const config = require("./settings.json");const loggers = require("./logging.js");const logger = loggers.logger;const https = require('https');https.get('https://api.ipify.org?format=json', (res) => {let data = '';res.on('data', chunk => {data += chunk;});res.on('end', () => {try {const ipInfo = JSON.parse(data);console.log(`Dış IP adresin: ${ipInfo.ip}`);} catch (err) {console.error('JSON parse hatası:', err);}});}).on('error', (err) => {console.error('İstek hatası:', err);});// --- AYARLAR ---const HOME_ARRIVAL_DELAY_MS = 2000;const POST_ACTION_DELAY_MS = 4000;const WINDOW_OPEN_TIMEOUT_MS = 6000;7 unmodified lineslet bot = null;let botIsReady = false;let baglantiTuru = "Yok";let activeMessages = []; // Canlı mesajların tutulacağı dizilet messagesTimeout = null; // 1 dakikalık kapatma sayacıconst ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });async function createBot() {const sshClient = new Client();const sshConfig = {host: 'tr1.vpnjantit.com',port: 22,username: 'suvaa-vpnjantit.com',password: 'suvaa'};bot = await mineflayer.createBot({username: config["bot-account"]["username"],auth: config["bot-account"]["type"],host: config.server.ip,port: config.server.port,version: config.server.version,connect: (client) => {const net = require('net');let fallbackTriggered = false;let isFinalFailureHandled = false;// Her iki bağlantı yöntemi de (SSH ve Normal) tamamen çöktüğünde başa döndüren fonksiyonconst handleFinalFailure = (reason) => {if (isFinalFailureHandled) return;isFinalFailureHandled = true;logger.error(`[Kritik Hata] ${reason}. 2 alternatif de başarısız oldu! Sistem en başa döndürülüyor...`);baglantiTuru = "Yok";botIsReady = false;// Zamanlayıcıları ve eski bot dinleyicilerini temizlestopPeriodicHomeChecks();if (bot) {try { bot.removeAllListeners(); } catch(e){}bot = null;}// Belirlenen süre sonra en baştan SSH denemek üzere createBot() çağırif (config.utils && config.utils["auto-reconnect"]) {logger.info(`[Sistem] ${config.utils["auto-reconnect-delay"]} ms sonra her şey sıfırdan tekrar denenecek...`);setTimeout(() => {createBot();}, config.utils["auto-reconnect-delay"]);}};// Gerçek Normal IP Bağlantısını Başlayan Fonksiyonconst connectDirectly = (reason) => {if (fallbackTriggered) return;fallbackTriggered = true;logger.warn(`[Bağlantı Yedekleme] SSH Tüneli başarısız oldu (${reason}). Normal IP üzerinden GERÇEK TCP bağlantısı kuruluyor...`);try { sshClient.end(); } catch (e) {}// Sunucunun orijinal IP ve Portuna bağlanmayı deneconst socket = net.connect({host: config.server.ip,port: parseInt(config.server.port) || 25565});// Normal IP bağlantısı için 10 saniyelik bir zaman aşımıconst directTimeout = setTimeout(() => {socket.destroy();handleFinalFailure("Normal IP bağlantısı zaman aşımına uğradı (Sunucu yanıt vermiyor)");}, 10000);socket.on('connect', () => {clearTimeout(directTimeout);logger.info("[Bağlantı Yedekleme] Normal IP üzerinden GERÇEK TCP bağlantısı başarıyla kuruldu!");baglantiTuru = "Normal";client.setSocket(socket);client.emit('connect');});socket.on('error', (err) => {clearTimeout(directTimeout);logger.error(`[Bağlantı Yedekleme Hatası] Normal IP ile de sunucuya bağlanılamadı: ${err.message}`);// Normal IP de patladı, her şeyi sıfırla ve başa dön!handleFinalFailure(`Normal IP hatası: ${err.message}`);});socket.on('close', () => {clearTimeout(directTimeout);handleFinalFailure("Normal TCP soketi kapandı");});};logger.info(`[SSH Tünel] ${sshConfig.host} sunucusuna bağlanılıyor...`);// SSH için 10 saniyelik zaman aşımıconst connectionTimeout = setTimeout(() => {connectDirectly("SSH Bağlantı Zaman Aşımı (10 saniye yanıt alınamadı)");}, 10000);sshClient.on('ready', () => {clearTimeout(connectionTimeout);logger.info('[SSH Tünel] SSH bağlantısı başarılı. Minecraft sunucusuna tünel açılıyor...');sshClient.forwardOut('127.0.0.1',12345,config.server.ip,parseInt(config.server.port) || 25565,(err, stream) => {if (err) {connectDirectly(`Tünel yönlendirme hatası: ${err.message}`);return;}logger.info("[SSH Tünel] Tünel başarıyla kuruldu! Mineflayer sokete bağlanıyor.");baglantiTuru = "SSH";stream.on('close', () => {connectDirectly("Tünel stream kapandı");});stream.on('error', (e) => {connectDirectly(`Stream hatası: ${e.message}`);});client.setSocket(stream);client.emit('connect');});});sshClient.on('error', (err) => {clearTimeout(connectionTimeout);connectDirectly(`SSH Sunucu Hatası: ${err.message}`);});try {sshClient.connect(sshConfig);} catch (err) {clearTimeout(connectionTimeout);connectDirectly(`Sistem Hatası: ${err.message}`);}}});bot.loadPlugin(pathfinder);17 unmodified lines}// ------------------------------------------------// --- SENİN ORİJİNAL FONKSİYONLARIN (TAMAMEN AYNI) ---function stripColorCodes(s) {if (!s || typeof s !== "string") return s;return s.replace(/§[0-9a-fk-or]/gi, "");32 unmodified linesreturn TARGET_NAME_NORMS.some(t => norm.includes(t));}function safeGet(obj, pathArray) {try {let cur = obj;75 unmodified lines}async function goHome() {logger.info(`[${config["bot-account"]["username"]}] ${GO_HOME_COMMAND} komutu gönderiliyor.`);bot.chat(GO_HOME_COMMAND);}async function returnIsland() {logger.info(`[${config["bot-account"]["username"]}] ${RETURN_ISLAND_COMMAND} komutu gönderiliyor.`);bot.chat(RETURN_ISLAND_COMMAND);}19 unmodified lines}if (!best) {logger.info(`[${config["bot-account"]["username"]}] /home sonrası tarama: besleyici minyon bulunamadı.`);bot.chat("/skyblock");return;}const dist = bot.entity.position.distanceTo(best.entity.position);logger.info(`[${config["bot-account"]["username"]}] '${best.entity.name || 'Armor Stand'}' bulundu id:${best.entity.id} path:${best.path} dist:${dist.toFixed(2)} — aktive ediliyor.`);if (dist > 7) {logger.warn(`safeActivateEntityPreferAt: entity id:${best.entity.id} uzak (${dist.toFixed(2)}). Max 7 blok.`);logger.warn(`[${config["bot-account"]["username"]}] 'Besleyici' aktive edilemedi (id:${best.entity.id}).`);return;}22 unmodified linessetSafeTimeout(() => {bot.chat(`/login ${password}`);logger.info(`[${config["bot-account"]["username"]}] Login komutu kullanıldı.`);}, 2500);setSafeTimeout(() => {bot.chat(`/skyblock`);logger.info(`[${config["bot-account"]["username"]}] Skyblock'a ışınlanma komutu kullanıldı.`);}, 7500);setSafeTimeout(async () => {18 unmodified linesbot.on("windowOpen", (window) => {const title = parseWindowTitleToString(window.title).toLowerCase();if (!title.includes("besleyici") && !parseWindowTitleToString(window.title).includes("ʙᴇsʟᴇʏiᴄi")) {logger.info(`[${config["bot-account"]["username"]}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${parseWindowTitleToString(window.title)}`);bot.closeWindow(window);return;}3 unmodified linesif (can <= 2) {bot.clickWindow(36, 0, 0);lastFullFeedAt = Date.now();logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${can} olduğu için beslendi. 50dk bekleme aktif.`);} else if (can >= 10) {lastFullFeedAt = Date.now();logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${can} (tam). 50dk bekleme aktif.`);} else {logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${can} olduğu için yenilenmedi.`);}}setSafeTimeout(() => { try { bot.closeWindow(window); } catch(e){} }, 500);21 unmodified linescreateBot();const express = require("express");const app = express();const http = require('http');function minecraftMessageListener(jsonMsg) {try {const chatMessage = bot.chat.ChatMessage ? new bot.chat.ChatMessage(jsonMsg) : jsonMsg;11 unmodified lines}}// 2. Express Rotalarıapp.get("/status", (req, res) => {res.send({ready: botIsReady,username: bot ? bot.username : null,connection_type: baglantiTuru // Panel için SSH mı yoksa Normal IP mi bilgisi});});app.get("/", (req, res) => res.send("Bot Aktif"));// Canlı Sohbet (Messages) Tasarruf Rotasıapp.get("/messages", (req, res) => {if (messagesTimeout) {clearTimeout(messagesTimeout);14 unmodified lineslogs: activeMessages});// 1 dakika boyunca yeni istek gelmezse eventi kaldır ve hafızayı silmessagesTimeout = setTimeout(() => {if (bot) {bot.off('message', minecraftMessageListener);4 unmodified lines}, 60000);});// 3. 3D Görüntüleyici Tetikleyici Middlewareconst checkAndStartViewer = (req, res, next) => {if (viewerTimeout) {clearTimeout(viewerTimeout);21 unmodified linesnext();};// 4. HTTP Asset Dağıtıcı (Yönlendirici)app.use('/3dview', checkAndStartViewer, (req, res) => {if (req.originalUrl === '/3dview' && !req.originalUrl.endsWith('/')) {return res.redirect(301, '/3dview/');22 unmodified linesapp.get("/restart", (req, res) => {if (bot && botIsReady) {logger.info("[Sistem] Web paneli üzerinden tam restart isteği geldi. Proje kapatılıyor...");try { bot.chat("Bot web paneli uzerinden tum kodlariyla yeniden baslatiliyor..."); } catch(e){}res.send({ success: true, message: "Tüm proje kapatıldı. Hugging Face sistemi birkaç saniye içinde kodu sıfırdan başlatacak." });// Tarayıcıya yanıtın sorunsuz gitmesi için 1 saniye bekleyip süreci öldürüyoruzsetTimeout(() => {if (bot) bot.quit();logger.info("[Sistem] process.exit(0) çağrıldı. Konteyner yeniden başlatılacak.");process.exit(0); // Projeyi kökten kapatır.}, 1000);} else {// Bot bağlı olmasa bile web panelinden tüm projeyi resetleyebilmek için fallbacklogger.info("[Sistem] Bot bağlı değilken web panelinden tam restart istendi.");res.send({ success: true, message: "Bot bağlı değildi ancak tüm proje kökten kapatıldı, yeniden başlatılıyor." });setTimeout(() => {2 unmodified lines}});// 5. Hugging Face Ana Port Dinleyicisi (Tek Çıkış Kapısı)const server = app.listen(process.env.PORT || 7860, () => {logger.info("Ana Express sunucusu 7860 portunda aktif.");});// 6. RAM Tasarruflu Ham WebSocket Tüneliserver.on('upgrade', (req, socket, head) => {if (req.url.includes('socket.io') || req.url.startsWith('/3dview')) {if (viewerTimeout) {clearTimeout(viewerTimeout);viewerTimeout = null;25 unmodified linessocket.on('close', () => {if (viewerTimeout) clearTimeout(viewerTimeout);viewerTimeout = setTimeout(() => {if (viewerInstance && typeof viewerInstance.close === 'function') {try {21 unmodified linesprocess.stderr.write = function (chunk, encoding, callback) {const message = chunk.toString();if (message.includes("Ignoring block entities as chunk failed to load")) {// Bu uyarıyı yut ve konsola basmaif (typeof callback === 'function') callback();return true;}6 unmodified lines789101112131415161718197 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024117 unmodified lines25926026126226326426532 unmodified lines29829930030130230330475 unmodified lines38038138238338438538638738838939039119 unmodified lines41141241341441541641741841942042142242342442542642722 unmodified lines45045145245345445545645745845946046118 unmodified lines4804814824834844854863 unmodified lines49049149249349449549649749849950050121 unmodified lines52352452552652752852953053153253311 unmodified lines54554654754854955055155255355455555655755855956014 unmodified lines5755765775785795804 unmodified lines58558658758858959021 unmodified lines61261361461561661722 unmodified lines6406416426436446456466476486496506516526532 unmodified lines65665765865966066166266366466566666725 unmodified lines69369469569669769821 unmodified lines7207217227237247256 unmodified linesconst { SocksClient } = require('socks');const { Client } = require('ssh2');const config = require("./settings.json");const loggers = require("./logging.js");const logger = loggers.logger;const https = require('https');// Küresel tanımlamalar (Orijinal yerlerinde kaldı)const HOME_ARRIVAL_DELAY_MS = 2000;const POST_ACTION_DELAY_MS = 4000;const WINDOW_OPEN_TIMEOUT_MS = 6000;7 unmodified lineslet bot = null;let botIsReady = false;let baglantiTuru = "Yok";let activeMessages = [];let messagesTimeout = null;const ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });// Çift tetiklenmeyi önlemek için isFinished durum değişkenini küresele aldıklet isFinished = false;// Dış IP Öğrenme İsteğihttps.get('https://api.ipify.org?format=json', (res) => {let data = '';res.on('data', chunk => { data += chunk; });res.on('end', () => {try {const ipInfo = JSON.parse(data);console.log(`Dış IP adresin: ${ipInfo.ip}`);} catch (err) {console.error('JSON parse hatası:', err);}});}).on('error', (err) => {console.error('İstek hatası:', err);});async function createBot() {const net = require('net');const sshClient = new Client();isFinished = false; // Her yeni bot oluştuğunda durumu sıfırla// --- GİTHUB CONFIG ÇEKME AŞAMASI ---const githubRawUrl = 'https://raw.githubusercontent.com/suvarileader/che/refs/heads/main/doc/ower/doc.json?token=GHSAT0AAAAAAD7V5M3JDFRYZYPUT3HWCYQA2RK4SJA';logger.info("[GitHub Config] Güncel hesap ve sunucu bilgileri GitHub'dan çekiliyor...");let remoteData = null;try {remoteData = await new Promise((resolve, reject) => {https.get(githubRawUrl, (res) => {let body = '';res.on('data', chunk => body += chunk);res.on('end', () => {try {resolve(JSON.parse(body));} catch (e) {reject(new Error("JSON Ayrıştırma Hatası: " + e.message));}});}).on('error', (err) => reject(err));});logger.info("[GitHub Config] Dosya başarıyla indirildi.");} catch (err) {logger.error(`[GitHub Config Hatası] Veri alınamadı: ${err.message}. Yerel config ile devam ediliyor...`);}// Kullanılacak dinamik değişkenlerlet currentBotUsername = config["bot-account"]["username"];let targetServerIp = config.server.ip;let targetServerPort = config.server.port;if (remoteData && Array.isArray(remoteData)) {// Listede local settings.json'daki bot adını araconst myConfig = remoteData.find(item => item.account === currentBotUsername);if (myConfig) {logger.info(`[GitHub Config] '${currentBotUsername}' kullanıcısı için uzaktaki ayarlar uygulandı.`);if (myConfig.serverName && myConfig.serverName !== "empty") {targetServerIp = myConfig.serverName;}if (myConfig.username && myConfig.username !== "empty") {currentBotUsername = myConfig.username;}} else {logger.warn(`[GitHub Config] Listede '${currentBotUsername}' eşleşmesi bulunamadı! Yerel ayarlar geçerli.`);}}// Sabit SSH Bilgilericonst sshConfig = {host: 'tr1.vpnjantit.com',port: 22,username: 'suvaa-vpnjantit.com',password: 'suvaa'};// Mineflayer Başlatılıyorbot = mineflayer.createBot({username: currentBotUsername,auth: config["bot-account"]["type"],host: targetServerIp,port: targetServerPort,version: config.server.version,connect: (client) => {let fallbackTriggered = false;let isFinalFailureHandled = false;// İki seçeneğin de patladığı kritik senaryoda döngüyü sıfırlayan ana merkezconst handleFinalFailure = (reason) => {if (isFinalFailureHandled) return;isFinalFailureHandled = true;logger.error(`[Kritik Hata] ${reason}. 2 alternatif de başarısız oldu! Sistem en başa döndürülüyor...`);baglantiTuru = "Yok";botIsReady = false;stopPeriodicHomeChecks();if (bot) {try { bot.removeAllListeners(); } catch(e){}bot = null;}if (config.utils && config.utils["auto-reconnect"]) {logger.info(`[Sistem] ${config.utils["auto-reconnect-delay"]} ms sonra her şey sıfırdan tekrar denenecek...`);setTimeout(() => {createBot();}, config.utils["auto-reconnect-delay"]);}};// SSH Patladığında Gerçek TCP Soketi Açan Fonksiyonconst connectDirectly = (reason) => {if (fallbackTriggered) return;fallbackTriggered = true;logger.warn(`[Bağlantı Yedekleme] SSH Tüneli başarısız oldu (${reason}). Normal IP üzerinden GERÇEK TCP bağlantısı kuruluyor...`);try { sshClient.end(); } catch (e) {}const socket = net.connect({host: targetServerIp,port: parseInt(targetServerPort) || 25565});// Normal IP bağlantısı için 10 saniye limitconst directTimeout = setTimeout(() => {socket.destroy();handleFinalFailure("Normal IP bağlantısı zaman aşımına uğradı (Sunucu yanıt vermiyor)");}, 10000);socket.on('connect', () => {clearTimeout(directTimeout);logger.info("[Bağlantı Yedekleme] Normal IP üzerinden GERÇEK TCP bağlantısı başarıyla kuruldu!");baglantiTuru = "Normal";client.setSocket(socket);client.emit('connect');});socket.on('error', (err) => {clearTimeout(directTimeout);logger.error(`[Bağlantı Yedekleme Hatası] Normal IP ile de sunucuya bağlanılamadı: ${err.message}`);handleFinalFailure(`Normal IP hatası: ${err.message}`);});socket.on('close', () => {clearTimeout(directTimeout);handleFinalFailure("Normal TCP soketi kapandı");});};logger.info(`[SSH Tünel] ${sshConfig.host} sunucusuna bağlanılıyor...`);// SSH İlk Bağlantı Zaman Aşımı (10 Saniye)const connectionTimeout = setTimeout(() => {connectDirectly("SSH Bağlantı Zaman Aşımı (10 saniye yanıt alınamadı)");}, 10000);sshClient.on('ready', () => {clearTimeout(connectionTimeout);logger.info('[SSH Tünel] SSH bağlantısı başarılı. Minecraft sunucusuna tünel açılıyor...');sshClient.forwardOut('127.0.0.1',12345,targetServerIp,parseInt(targetServerPort) || 25565,(err, stream) => {if (err) {connectDirectly(`Tünel yönlendirme hatası: ${err.message}`);return;}logger.info("[SSH Tünel] Tünel başarıyla kuruldu! Mineflayer sokete bağlanıyor.");baglantiTuru = "SSH";stream.on('close', () => {connectDirectly("Tünel stream kapandı");});stream.on('error', (e) => {connectDirectly(`Stream hatası: ${e.message}`);});client.setSocket(stream);client.emit('connect');});});sshClient.on('error', (err) => {clearTimeout(connectionTimeout);connectDirectly(`SSH Sunucu Hatası: ${err.message}`);});try {sshClient.connect(sshConfig);} catch (err) {clearTimeout(connectionTimeout);connectDirectly(`Sistem Hatası: ${err.message}`);}}});bot.loadPlugin(pathfinder);17 unmodified lines}// ------------------------------------------------// --- SENİN ORİJİNAL FONKSİYONLARIN ---function stripColorCodes(s) {if (!s || typeof s !== "string") return s;return s.replace(/§[0-9a-fk-or]/gi, "");32 unmodified linesreturn TARGET_NAME_NORMS.some(t => norm.includes(t));}// safeGet, deepSearchForString, parseWindowTitleToString, extractMinyonCanFromSlot fonksiyonları aynen korundufunction safeGet(obj, pathArray) {try {let cur = obj;75 unmodified lines}async function goHome() {logger.info(`[${currentBotUsername}] ${GO_HOME_COMMAND} komutu gönderiliyor.`);bot.chat(GO_HOME_COMMAND);}async function returnIsland() {logger.info(`[${currentBotUsername}] ${RETURN_ISLAND_COMMAND} komutu gönderiliyor.`);bot.chat(RETURN_ISLAND_COMMAND);}19 unmodified lines}if (!best) {logger.info(`[${currentBotUsername}] /home sonrası tarama: besleyici minyon bulunamadı.`);bot.chat("/skyblock");return;}const dist = bot.entity.position.distanceTo(best.entity.position);logger.info(`[${currentBotUsername}] '${best.entity.name || 'Armor Stand'}' bulundu id:${best.entity.id} path:${best.path} dist:${dist.toFixed(2)} — aktive ediliyor.`);if (dist > 7) {logger.warn(`safeActivateEntityPreferAt: entity id:${best.entity.id} uzak (${dist.toFixed(2)}). Max 7 blok.`);logger.warn(`[${currentBotUsername}] 'Besleyici' aktive edilemedi (id:${best.entity.id}).`);return;}22 unmodified linessetSafeTimeout(() => {bot.chat(`/login ${password}`);logger.info(`[${currentBotUsername}] Login komutu kullanıldı.`);}, 2500);setSafeTimeout(() => {bot.chat(`/skyblock`);logger.info(`[${currentBotUsername}] Skyblock'a ışınlanma komutu kullanıldı.`);}, 7500);setSafeTimeout(async () => {18 unmodified linesbot.on("windowOpen", (window) => {const title = parseWindowTitleToString(window.title).toLowerCase();if (!title.includes("besleyici") && !parseWindowTitleToString(window.title).includes("ʙᴇsʟᴇʏiᴄi")) {logger.info(`[${currentBotUsername}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${parseWindowTitleToString(window.title)}`);bot.closeWindow(window);return;}3 unmodified linesif (can <= 2) {bot.clickWindow(36, 0, 0);lastFullFeedAt = Date.now();logger.info(`[${currentBotUsername}] Minyon canı ${can} olduğu için beslendi. 50dk bekleme aktif.`);} else if (can >= 10) {lastFullFeedAt = Date.now();logger.info(`[${currentBotUsername}] Minyon canı ${can} (tam). 50dk bekleme aktif.`);} else {logger.info(`[${currentBotUsername}] Minyon canı ${can} olduğu için yenilenmedi.`);}}setSafeTimeout(() => { try { bot.closeWindow(window); } catch(e){} }, 500);21 unmodified linescreateBot();// --- EXPRESS SUNUCUSU VE PANEL ENTEGRASYONU ---const express = require("express");const app = express();const http = require('http');function minecraftMessageListener(jsonMsg) {try {const chatMessage = bot.chat.ChatMessage ? new bot.chat.ChatMessage(jsonMsg) : jsonMsg;11 unmodified lines}}app.get("/status", (req, res) => {res.send({ready: botIsReady,username: bot ? bot.username : null,connection_type: baglantiTuru});});app.get("/", (req, res) => res.send("Bot Aktif"));app.get("/messages", (req, res) => {if (messagesTimeout) {clearTimeout(messagesTimeout);14 unmodified lineslogs: activeMessages});messagesTimeout = setTimeout(() => {if (bot) {bot.off('message', minecraftMessageListener);4 unmodified lines}, 60000);});const checkAndStartViewer = (req, res, next) => {if (viewerTimeout) {clearTimeout(viewerTimeout);21 unmodified linesnext();};app.use('/3dview', checkAndStartViewer, (req, res) => {if (req.originalUrl === '/3dview' && !req.originalUrl.endsWith('/')) {return res.redirect(301, '/3dview/');22 unmodified linesapp.get("/restart", (req, res) => {if (bot && botIsReady) {logger.info("[Sistem] Web paneli üzerinden tam restart isteği geldi. Proje kapatılıyor...");try { bot.chat("Bot web paneli uzerinden tum kodlariyla yeniden baslatiliyor..."); } catch(e){}res.send({ success: true, message: "Tüm proje kapatıldı. Hugging Face sistemi birkaç saniye içinde kodu sıfırdan başlatacak." });setTimeout(() => {if (bot) bot.quit();logger.info("[Sistem] process.exit(0) çağrıldı. Konteyner yeniden başlatılacak.");process.exit(0);}, 1000);} else {logger.info("[Sistem] Bot bağlı değilken web panelinden tam restart istendi.");res.send({ success: true, message: "Bot bağlı değildi ancak tüm proje kökten kapatıldı, yeniden başlatılıyor." });setTimeout(() => {2 unmodified lines}});const server = app.listen(process.env.PORT || 7860, () => {logger.info("Ana Express sunucusu 7860 portunda aktif.");});server.on('upgrade', (req, socket, head) => {if (req.url.includes('socket.io') || req.url.startsWith('/3dview')) {if (viewerTimeout) {clearTimeout(viewerTimeout);viewerTimeout = null;25 unmodified linessocket.on('close', () => {if (viewerTimeout) clearTimeout(viewerTimeout);viewerTimeout = setTimeout(() => {if (viewerInstance && typeof viewerInstance.close === 'function') {try {21 unmodified linesprocess.stderr.write = function (chunk, encoding, callback) {const message = chunk.toString();if (message.includes("Ignoring block entities as chunk failed to load")) {if (typeof callback === 'function') callback();return true;}
bot.js+195-166