Spaces:
Paused
Paused
Update bot.js
Browse files43 unmodified lines444546474849505152535455565758596061622 unmodified lines65666768697071727374757677782 unmodified lines81828384858687883 unmodified lines92939495969798991001011021031041051061071081091101111121131148 unmodified lines1231241251261271281292 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751763 unmodified lines18018118218318418518688 unmodified lines27527627727827928028142 unmodified lines32432532632732832933033133233333433533633713 unmodified lines3513523533543553563574 unmodified lines3623633643653663673681 unmodified line37037137237337437537612 unmodified lines38939039139239339439539611 unmodified lines40840941041141241341441541641734 unmodified lines4524534544554564574584594604 unmodified lines46546646746846947047112 unmodified lines48448548648748848949049149256 unmodified lines54955055155255355455510 unmodified lines5665675685695705715721 unmodified line57457557657757857958024 unmodified lines605606607608609610611355 unmodified lines96796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103867 unmodified lines110611071108110911101111111211137 unmodified lines112111221123112411251126112711288 unmodified lines1137113811391140114111421143114411451146114711482 unmodified lines115111521153115411551156115736 unmodified lines11941195119611971198119912001201120212031204120575 unmodified lines1281128212831284128512861287128812891290129112921293129412951296129712981299130013011302449 unmodified lines1752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417752 unmodified lines17781779178017811782178317843 unmodified lines178817891790179117921793179417951 unmodified line1797179817991800180118021803180429 unmodified lines18341835183618371838183918404 unmodified lines184518461847184818491850185165 unmodified lines191719181919192019211922192319241925192619273 unmodified lines1931193219331934193519361937193894 unmodified lines203320342035203620372038203920402041204220432044204520462047204826 unmodified lines207520762077207820792080208155 unmodified lines21372138213921402141214251 unmodified lines21942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182 unmodified lines22212222222322242225222622272228222922302231223210 unmodified lines22432244224522462247224822492250225122526 unmodified lines22592260226122622263226422652266226722682269227022712272227322742275227621 unmodified lines2298229923002301230223032304148 unmodified lines24532454245524562457245824592460246124622463246424652466203 unmodified lines2670267126722673267426752676197 unmodified lines2874287528762877287828792880373 unmodified lines325432553256325743 unmodified linesconst CIFTCI_COMMAND = "/çiftçi menü";const CIFTCI_WINDOW_TIMEOUT_MS = 6000;const CIFTCI_LORE_FALLBACK_KEYWORDS = ["hepsini sat"];// Menü açıldıktan sonra sunucunun içeriği (lore/slot) tam yerleştirmesi için// beklenecek süre, tıklamadan önce. Ardından art arda birkaç kez tıklanır.const CIFTCI_CLICK_DELAY_AFTER_OPEN_MS = 1000;const CIFTCI_CLICK_REPEAT_COUNT = 3;const CIFTCI_CLICK_REPEAT_GAP_MS = 350;// --- KAZICI PERİYODİK DÖNGÜ AYARLARI (bağımsız, 5 dakikada bir) ---const KAZICI_CYCLE_INTERVAL_MS = 5 * 60 * 1000; // 5 dakika// --- ÇİFTÇİ PERİYODİK DÖNGÜ AYARLARI (bağımsız, 1 dakikada bir) ---const CIFTCI_CYCLE_INTERVAL_MS = 60 * 1000; // 1 dakika// --- ÇİFTÇİ FİLTRE / STORAGE INFO TARAMA AYARLARI ---const CIFTCI_FILTER_MODES = ["Standart","Favoriler",2 unmodified lines"Satışı açık olanlar","Toplaması açık olanlar"];const CIFTCI_TARGET_FILTER_INDEX = 3; // "Jeneratör materyalleri"const CIFTCI_ACTIVE_FILTER_COLOR = "#FCF988";const CIFTCI_FILTER_ITEM_NAME_KEYWORD = "Filtre";const CIFTCI_FILTER_STEP_WAIT_MS = 1000; // her tık sonrası ilk beklemeconst CIFTCI_FILTER_RETRY_WAIT_MS = 1000; // item gözükmezse ek beklemeconst CIFTCI_FILTER_MAX_RETRIES = 10; // güvenlik limiticonst STORAGE_SCAN_INTERVAL_MS = 15 * 60 * 1000; // 15 dakikaconst STORAGE_TRACKED_ITEMS = ["diamond", "emerald", "iron_block"]; // internal name eşleşmesi// --- SİPARİŞ (ORDER) SİSTEMİ AYARLARI ---const ORDER_COMMAND_PREFIX = "/order";2 unmodified linesconst ORDER_AFTER_SELECT_DELAY_MS = 500;const ORDER_IS_GO_SECOND_DELAY_MS = 5000;const ORDER_ALLOWED_ITEMS = ["diamond", "emerald"];const ORDER_LIST_TITLE_KEYWORD = "ѕiᴘᴀʀişʟᴇʀ"; // nick seçim penceresiconst ORDER_DELIVERY_TITLE_KEYWORD = "ᴛᴇѕʟiᴍ ᴇᴛᴍᴇ"; // item bırakma kutusulet storageInfoCache = {diamond: null,3 unmodified lines};let storageScanIntervalHandle = null;// Çiftçi penceresinin şu an hangi amaçla açık olduğunu tutan bayrak.// "sell" -> hepsini-sat akışı, "scan" -> storage bilgisi tarama akışı, "order" -> sipariş akışı.let ciftciWindowPurpose = "sell";// --- KAZICI FAILOVER (YEDEK HESAP) AYARLARI ---const STALL_CHECK_INTERVAL_MS = 15 * 1000; // pose kontrolü ne sıklıkla yapılsınconst STALL_TIMEOUT_MS = 60 * 1000; // bu süre hareketsiz kalırsa "durdu" sayconst FAILOVER_HOME_ARRIVAL_DELAY_MS = 4000; // yedek hesapta /is go sonrası varış beklemesiconst FAILOVER_LOGIN_DELAY_MS = 2500;const FAILOVER_SKYBLOCK_DELAY_MS = 7500;const FAILOVER_ISGO_DELAY_MS = 12500;const FAILOVER_RECHECK_INTERVAL_MS = 20 * 1000; // yedek hesapta minyonları tekrar kontrol aralığıconst FAILOVER_MAX_WAIT_MS = 60 * 60 * 1000; // güvenlik: 1 saatte hâlâ aktifleşmediyse pes et, ana hesaba dönconst FAILOVER_SPAWN_TIMEOUT_MS = 30 * 1000; // yedek hesap 30 sn içinde spawn olmazsa vazgeç// İzlenen (KAZICI_NAMES ile eşleşmeyen, başka hesaptan konan) kazıcı minyonların// skin texture hash'i. Bu skin + elde iron_pickaxe olan armor stand'ler izlenir.const WATCHED_KAZICI_SKIN_HASHES = new Set(["eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDQ4ODcwY2E3N2FhNjk5ZDAxNzA5M2I4Mjc3OWQwYTU5OGRjNGYzZjQ5ZDM1MTUzMmFlNGQ5NjMzZGNjMmE1YSJ9fX0=",]);8 unmodified lineslet isListeningChat = false;const ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });// --- GÜVENLİ BAĞLANTI DEĞİŞKENLERİ ---let isConnecting = false;let isDestroying = false;let reconnectTimeout = null;2 unmodified lineslet currentSocket = null;let windowOpenResolvers = [];// --- PANEL METRİKLERİ ---let botUptimeStart = null;let lastFullFeedTimeStr = "Henüz besleme yapılmadı";let lastCheckTimeStr = "Henüz kontrol yapılmadı";let nextScheduledCheckTimeStr = "Botun spawn olması bekleniyor...";// --- KAZICI PANEL METRİKLERİ (bağımsız) ---let lastKaziciCheckTimeStr = "Henüz kazıcı kontrolü yapılmadı";let nextKaziciTimeStr = "Botun spawn olması bekleniyor...";let nextKaziciAtMs = null;// --- ÇİFTÇİ PANEL METRİKLERİ (bağımsız) ---let lastCiftciSellTimeStr = "Henüz çiftçi satışı yapılmadı";let nextCiftciTimeStr = "Botun spawn olması bekleniyor...";let nextCiftciAtMs = null;// --- SİPARİŞ (ORDER) PANEL METRİKLERİ ---let lastOrderTimeStr = "Henüz sipariş işlemi yapılmadı";// --- ÇİFTÇİ/KAZICI PERİYODİK DÖNGÜ KONTROLÜ ---let lastCheckAtMs = null; // Besleyici için (panel bilgisi amaçlı, artık kazıcı/çiftçiyi etkilemiyor)let nextScheduledCheckAtMs = null; // Besleyici içinlet kaziciIntervalHandle = null; // Kazıcı bağımsız döngü zamanlayıcısı (5 dk)let ciftciIntervalHandle = null; // Çiftçi bağımsız döngü zamanlayıcısı (1 dk)let isMainCycleRunning = false; // Besleyici (goToIsland->besle) ana döngüsü sürüyor mu// --- KAZICI FAILOVER (YEDEK HESAP) DURUM DEĞİŞKENLERİ ---let poseTracker = new Map(); // entityId -> { poseKey, lastChangeAt, uuid }let stallCheckIntervalHandle = null;let failoverModeActive = false; // true iken ana botun periyodik işlemleri fiilen durur (bot=null olduğu için)let failoverBot = null; // yedek hesabın mineflayer instance'ılet failoverInProgress = false; // aynı anda 2 kez tetiklenmesin diye kilit// --- DİNAMİK IP VE KONUM BİLGİLERİ ---let activeConnectionIp = "Bilinmiyor";let activeConnectionLocation = "Bilinmiyor";let localExternalIp = "Bilinmiyor";// --- DİNAMİK ZAMANLAYICI KONTROLÜ ---let periodicTimeoutHandle = null;let activeTimeouts = [];3 unmodified linesreturn t;}// --- ÖNCELİKLİ GUI KİLİDİ (MUTEX) ---class PriorityGuiMutex {constructor() {this._locked = false;88 unmodified linesnextCiftciTimeStr = "Zamanlama durduruldu.";}// --- MANUEL DURDURMA/BAŞLATMA KONTROLÜ ---let manualStopRequested = false;async function getIpLocation(ip) {42 unmodified lines});}).on('error', () => {});// =====================================================================// KAZICI FAILOVER (YEDEK HESAP) YARDIMCI FONKSİYONLARI// Bunlar module-level (createBot() dışında) çünkü bot bağlantısı kesilip// yeniden kurulduğunda bile (createBot() tekrar çağrıldığında) hayatta// kalmaları gerekiyor.// =====================================================================// Entity'nin skin texture değerini (player_head equipment'inden) çıkarır.function getEntitySkinHash(entity) {try {const equipment = entity.equipment || [];13 unmodified linesreturn null;}// Entity'nin elinde (equipment[0] = main hand) iron_pickaxe olup olmadığını kontrol eder.function hasIronPickaxeEquipped(entity) {try {const equipment = entity.equipment || [];4 unmodified lines}}// Skin + iron_pickaxe ikisi birden tutuyorsa bu entity izlenen kazıcı minyondur.function isWatchedKaziciEntity(entity) {if (!entity || entity.name !== "armor_stand") return false;const skinHash = getEntitySkinHash(entity);1 unmodified linereturn hasIronPickaxeEquipped(entity);}// metadata içindeki pose (kol/kafa açıları) + pozisyonu birleştirip bir imza çıkarır.function getPoseKey(entity) {try {const md = entity.metadata || [];12 unmodified lines}}// bot.on('entityMoved', ...) ve bot.on('entitySpawn', ...) içinden çağrılır.// İzlenen kazıcı minyonun pose'unu takip eder.function trackKaziciPoseIfWatched(entity) {if (!entity) return;if (!isWatchedKaziciEntity(entity)) return;11 unmodified linesprev.poseKey = poseKey;prev.lastChangeAt = Date.now();}// poseKey aynıysa lastChangeAt GÜNCELLENMEZ -> hareketsizlik süresi büyümeye devam eder.}// Artık dünyada olmayan entity kayıtlarını temizler.function pruneStaleTrackedEntities() {if (!bot || !bot.entities) return;for (const id of poseTracker.keys()) {34 unmodified linesposeTracker.clear();}// Ana hesabı geçici düşürüp yedek hesabı (kullaniciadi1) devreye alan, izlenen// kazıcı minyonlar tekrar hareket edene kadar bekleyen, sonra ana hesabı// yeniden bağlayan tam akış.async function triggerFailoverSequence() {if (failoverInProgress) return;failoverInProgress = true;4 unmodified lineslogger.warn(`[Failover] İzlenen kazıcı(lar) durdu. Ana hesap (${mainUsername}) geçici olarak düşürülüp yedek hesap (${backupUsername}) devreye alınıyor.`);manualStopRequested = true; // mevcut auto-reconnect mantığını geçici olarak devre dışı bırakırstopPeriodicHomeChecks();safeDestroyAllConnections();12 unmodified linesfailoverInProgress = false;}// Yedek hesapla ayrı bir mineflayer bot'u başlatır: /login, /skyblock, /is go// atar (ana hesaptaki ile AYNI gecikme süreleriyle), sonra izlenen minyonların// hareketine bakar. Hareket geri gelince bağlantıyı kapatıp resolve eder.function runBackupAccountAndWaitForRecovery(backupUsername) {return new Promise((resolve) => {const backupPoseTracker = new Map();56 unmodified lineslogger.info(`[Failover - Yedek Hesap] ${GO_ISLAND_COMMAND} gönderildi, izlenen minyonların tekrar hareket etmesi bekleniyor...`);}, FAILOVER_ISGO_DELAY_MS);// Adaya varış + izleme başlatmasetTimeout(() => {recheckHandle = setInterval(() => {try {10 unmodified linesif (!prev) {backupPoseTracker.set(e.id, { poseKey, lastChangeAt: Date.now() });allRecovered = false; // henüz yeterince veri yok, bir tur daha beklecontinue;}1 unmodified lineprev.poseKey = poseKey;prev.lastChangeAt = Date.now();} else if (Date.now() - prev.lastChangeAt < STALL_TIMEOUT_MS) {// son 1 dk içinde bir değişiklik olmuş demek ki hareket ediyor} else {allRecovered = false;}24 unmodified lines}});// Güvenlik: sonsuza kadar beklemesinsafetyTimeoutHandle = setTimeout(() => {logger.warn(`[Failover - Yedek Hesap] Azami bekleme süresi (${formatDurationMs(FAILOVER_MAX_WAIT_MS)}) doldu, ana hesaba geri dönülüyor.`);finish();355 unmodified lines} catch (e) { return undefined; }};// components dizisinden belirli tipteki component'in data'sını bulurfunction getComponentData(slot, type) {try {if (!slot || !Array.isArray(slot.components)) return undefined;const comp = slot.components.find(c => c && c.type === type);return comp ? comp.data : undefined;} catch (e) { return undefined; }}// {type,value} tarzı NBT-benzeri sarmalayıcıyı açarfunction nbtUnwrap(node) {if (node && typeof node === "object" && "type" in node && "value" in node) {return node.value;}return node;};// Yeni "components" formatındaki text-component ağacını düz metne çevirirfunction flattenTextComponent(node) {if (node == null) return "";if (typeof node === "string") return node;if (Array.isArray(node)) return node.map(flattenTextComponent).join("");if (typeof node === "object") {if ("type" in node && "value" in node) {const t = node.type, v = node.value;if (t === "string") return typeof v === "string" ? v : "";if (t === "list" || t === "compound") return flattenTextComponent(v);return ""; // byte/int vs. metin değil}let out = "";if ("text" in node) out += flattenTextComponent(node.text);if ("extra" in node) out += flattenTextComponent(node.extra);return out;}return "";};// Tek bir lore satırı node'unu {text, color} olarak parse eder (yeni format)function parseComponentLoreLine(lineNode) {let text = "";let color = null;function walk(node) {if (node == null) return;if (typeof node === "string") { text += node; return; }if (Array.isArray(node)) { node.forEach(walk); return; }if (typeof node === "object") {if ("type" in node && "value" in node) {const t = node.type, v = node.value;if (t === "string") { text += (typeof v === "string" ? v : ""); return; }if (t === "list" || t === "compound") { walk(v); return; }return;}if ("color" in node) {const colVal = nbtUnwrap(node.color);if (color == null && typeof colVal === "string") color = colVal;}if ("text" in node) walk(node.text);if ("extra" in node) walk(node.extra);}}walk(lineNode);return { text: text.trim(), color };};function deepSearchForString(root, targetVariantsList) {const results = [];67 unmodified linesconst texts = [];try {if (!slot) return texts;// Yeni format: componentsconst customNameData = getComponentData(slot, "custom_name");if (customNameData !== undefined) {const nameTxt = flattenTextComponent(customNameData);7 unmodified lines}}if (texts.length > 0) return texts;// Eski format: nbt (fallback)function extractPlain(raw) {if (!raw || typeof raw !== "string") return null;try {8 unmodified lines} catch (e) {}return raw;}if (slot.nbt) {const name = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);const plainName = extractPlain(name);if (plainName) texts.push(plainName);const lore = safeGet(slot.nbt, ["value", "display", "value", "Lore", "value"]);if (Array.isArray(lore)) {for (const line of lore) {2 unmodified lines}}}if (texts.length === 0) {texts.push(util.inspect(slot, { depth: null }));}36 unmodified lines}}// --- SENDMONEY: /money oku, bakiyeden 1000 eksiğini ilgili nick'e /pay ile gönder ---const MONEY_BALANCE_REGEX = /bakiyen:\s*([\d.,]+)\s*TL/i;const MONEY_RESPONSE_TIMEOUT_MS = 8000;function parseBalanceToAdjustedAmount(rawBalanceStr) {// "444,626.89" -> virgülleri kaldır -> "444626.89" -> noktadan öncesini al -> "444626"const noCommas = rawBalanceStr.replace(/,/g, "");const beforeDot = noCommas.split(".")[0];const intValue = parseInt(beforeDot, 10);75 unmodified linesif (!bot || !botIsReady) return;try {const moves = ['forward', 'left', 'right', 'jump'];const moveCount = Math.floor(Math.random() * 4) + 2; // 2-5 hareketfor (let i = 0; i < moveCount; i++) {const move = moves[Math.floor(Math.random() * moves.length)];const duration = 150 + Math.floor(Math.random() * 500);bot.setControlState(move, true);await new Promise(r => setTimeout(r, duration));bot.setControlState(move, false);await new Promise(r => setTimeout(r, 100 + Math.random() * 300));}// Rastgele kafa hareketiawait bot.look(bot.entity.yaw + ((Math.random() - 0.5) * 1.5),bot.entity.pitch + ((Math.random() - 0.5) * 0.3),449 unmodified lines}}// =====================================================================// ÇİFTÇİ FİLTRE NAVİGASYONU + STORAGE INFO TARAMA// =====================================================================function stripColorAndGetLoreLines(window) {if (!window || !Array.isArray(window.slots)) return null;for (const slot of window.slots) {if (!slot) continue;let nameTxt = "";// Yeni format: componentsconst customNameData = getComponentData(slot, "custom_name");if (customNameData !== undefined) {nameTxt = flattenTextComponent(customNameData);}// Eski format: nbt (fallback)if (!nameTxt && slot.nbt) {const nameRaw = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);try {2 unmodified lineselse if (maybe && maybe.text) nameTxt = maybe.text;} catch (e) { nameTxt = nameRaw || ""; }}if (nameTxt.includes(CIFTCI_FILTER_ITEM_NAME_KEYWORD)) {return { slot, index: window.slots.indexOf(slot) };}3 unmodified linesfunction getFilterItemLoreEntries(filterSlot) {const entries = [];// Yeni format: componentsconst loreData = getComponentData(filterSlot, "lore");if (Array.isArray(loreData)) {for (const line of loreData) {1 unmodified line}if (entries.length > 0) return entries;}// Eski format: nbt (fallback)try {const lore = safeGet(filterSlot.nbt, ["value", "display", "value", "Lore", "value"]);if (!Array.isArray(lore)) return entries;29 unmodified lines);if (match) return i;}// fallback: sadece renkle bulmayı deneconst colorMatch = loreEntries.find(e => e.color === CIFTCI_ACTIVE_FILTER_COLOR);if (colorMatch) {for (let i = 0; i < CIFTCI_FILTER_MODES.length; i++) {4 unmodified lines}async function waitForFilterItem(maxRetries) {// window açıldıktan sonra Filtre item'ı gözükene kadar beklerfor (let attempt = 0; attempt <= maxRetries; attempt++) {await new Promise(r => setTimeout(r, attempt === 0 ? CIFTCI_FILTER_STEP_WAIT_MS : CIFTCI_FILTER_RETRY_WAIT_MS));if (!bot || !bot.currentWindow) return null;65 unmodified lines}const total = CIFTCI_FILTER_MODES.length;const forwardDist = (CIFTCI_TARGET_FILTER_INDEX - currentIndex + total) % total; // sol tık (aşağı)const backwardDist = (currentIndex - CIFTCI_TARGET_FILTER_INDEX + total) % total; // sağ tık (yukarı)const useLeftClick = forwardDist <= backwardDist;const mouseButton = useLeftClick ? 0 : 1; // 0 = left, 1 = rightlogger.info(`[Çiftçi Filtre] Mevcut: "${CIFTCI_FILTER_MODES[currentIndex]}" -> Hedef: "${CIFTCI_FILTER_MODES[CIFTCI_TARGET_FILTER_INDEX]}". ${useLeftClick ? "Sol tık (aşağı)" : "Sağ tık (yukarı)"} kullanılacak.`);3 unmodified lineslogger.error(`[Çiftçi Filtre] Tıklama hatası: ${e && e.message ? e.message : e}`);return false;}// bir sonraki turda waitForFilterItem zaten bekleyecek}logger.warn("[Çiftçi Filtre] Azami deneme sayısına ulaşıldı, Jeneratör materyallerine geçilemedi.");94 unmodified lines// =====================================================================// SİPARİŞ (ORDER) SİSTEMİ// Akış:// 1) Çiftçi menüsü -> Jeneratör materyalleri filtresine geç (varsa zaten oradadır)// 2) İstenen item'ın (diamond/emerald) slotuna shift+sağ tık -> envanter dolana kadar item verir// 3) Menüyü kapat// 4) antiBotMove -> /is go -> 5sn bekle -> /is go// 5) /order <nick> gönder// 6) windowOpen bekle, +500ms sonra güncel pencereyi oku// 7) Lore'da nick geçen slotu bul -> sol tık ile seç// 8) +500ms sonra pencere boşsa envanterdeki item'ları shift+sol tık ile order'a aktar// 9) Pencereyi kapat// =====================================================================async function waitForNextWindowOpen(timeoutMs) {26 unmodified linesreturn -1;}async function processOrderCore(itemInternalName, nick) {if (!bot || !botIsReady) return { success: false, message: "Bot hazır değil." };if (!guiMutex.isLocked()) {logger.error("[GÜVENLİK İHLALİ] processOrderCore kilitsiz çağrıldı! İşlem iptal ediliyor.");55 unmodified lineslogger.error(`[Sipariş] Shift+sağ tık hatası: ${e && e.message ? e.message : e}`);}// --- 3) Menüyü kapat ---try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}// ÖNEMLİ: purpose burada "sell"e ÇEVRİLMEZ! /order akışı (Siparişler +51 unmodified lines}logger.info(`[Sipariş] '${nick}' içeren item bulundu (idx:${targetSlotIndex}), sol tık gönderiliyor...`);try {await bot.clickWindow(targetSlotIndex, 0, 0);} catch (e) {logger.error(`[Sipariş] Slot seçim tıklaması hatası: ${e && e.message ? e.message : e}`);}// --- 8) +500ms sonra pencere tekrar okunur (Teslim Etme penceresi bu olmalı) ---await new Promise(r => setTimeout(r, ORDER_AFTER_SELECT_DELAY_MS));if (!bot.currentWindow) {logger.warn("[Sipariş] Slot seçiminden sonra pencere kapandı, işlem yarım kalmış olabilir.");ciftciWindowPurpose = "sell";return { success: false, message: "Slot seçiminden sonra pencere kapandı." };}// Teslim Etme penceresi her zaman boş açılıyor, bu yüzden dolu/boş kontrolü// yapmadan direkt envanterdeki item'ları shift+sol tık ile aktarıyoruz.const currentTitle = parseWindowTitleToString(bot.currentWindow.title);logger.info(`[Sipariş] Güncel pencere: ${currentTitle}. Envanterdeki '${itemInternalName}' item'ları Teslim Etme'ye aktarılıyor...`);let transferredCount = 0;let keepGoing = true;let safetyCounter = 0;2 unmodified lineswhile (keepGoing && safetyCounter < 40) {safetyCounter++;if (!bot.currentWindow) break;const invItem = bot.inventory.items().find(it => it && it.name === itemInternalName);if (!invItem) { keepGoing = false; break; }// Aynı slot art arda takılıp kalıyorsa (item bir türlü taşınmıyorsa) döngüyü durdur.if (stuckSlot === invItem.slot) {stuckSlotRepeatCount++;if (stuckSlotRepeatCount >= 3) {10 unmodified linesawait bot.clickWindow(invItem.slot, 0, 1); // mouseButton=0 (sol), mode=1 (shift)await new Promise(r => setTimeout(r, 250));// Gerçekten taşınmış mı doğrula: aynı slotta hâlâ aynı item duruyor mu?const stillThere = bot.inventory.items().find(it => it && it.slot === invItem.slot && it.name === itemInternalName);if (!stillThere) {transferredCount++; // slot boşaldı = gerçekten taşındı} else {logger.warn(`[Sipariş] Slot ${invItem.slot} tıklandı ama item hâlâ envanterde, taşınmamış olabilir.`);}6 unmodified linesif (safetyCounter >= 40) {logger.warn(`[Sipariş] Güvenlik limitine (40 deneme) ulaşıldı. Teslim Etme kutusu dolu/limitli olabilir, transfer yarım kalmış olabilir.`);}logger.info(`[Sipariş] Envanterden Teslim Etme'ye aktarım turu tamamlandı (${transferredCount} yığın gönderildi).`);// --- 9) Pencereyi kapat ---try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}ciftciWindowPurpose = "sell"; // akış tamamen bitti, artık normal davranışa dönreturn {success: true,message: "Sipariş işlemi tamamlandı.",item: itemInternalName,nick,inventory_transferred_batches: transferredCount};}21 unmodified linesscanStorageInfo();}, STORAGE_SCAN_INTERVAL_MS);logger.info(`[Storage Tarama] Bağımsız döngü başlatıldı (her ${formatDurationMs(STORAGE_SCAN_INTERVAL_MS)}).`);// ilk taramayı biraz gecikmeli başlat ki spawn sonrası diğer işler önce otursunsetSafeTimeout(() => { scanStorageInfo(); }, 30 * 1000);}148 unmodified linesconst isCiftciWindow = !isBesleyiciWindow && !isKaziciWindow &&(matchesAnyName(titleRaw, TARGET_CIFTCI_NORMS) || windowMatchesLoreKeyword(window, CIFTCI_LORE_FALLBACK_KEYWORDS));// Sipariş (/order) penceresi çiftçi/kazıcı/besleyici isimleriyle eşleşmez,// bu yüzden ayrıca ele alınır: ciftciWindowPurpose "order" ise otomatik// tıklama/kapatma yapılmaz, sadece resolver tetiklenir ve processOrderCore// kendi akışını (500ms bekleme + güncel pencere okuma) yönetir.if (!isBesleyiciWindow && !isKaziciWindow && !isCiftciWindow) {if (ciftciWindowPurpose === "order") {logger.info(`[${currentBotUsername}] Sipariş (/order) penceresi açıldı: ${titleRaw}`);// otomatik kapatma yapma, processOrderCore yönetecek} else {logger.info(`[${currentBotUsername}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${titleRaw}`);try { bot.closeWindow(window); } catch(e){}203 unmodified lines}, delay);}// --- MANUEL BOT KONTROLÜ (stop/start/restart) ---let pendingHardRestartTimeout = null;function stopBotHard(reason) {197 unmodified lines});});// --- MANUEL BOT KONTROLÜ ENDPOINT'LERİ ---app.get("/bot/stop", (req, res) => {stopBotHard("Web paneli üzerinden /bot/stop isteği");res.send({ success: true, message: "Bot durduruldu. Tekrar başlatmak için /bot/start kullan." });373 unmodified linesreturn true;}return originalStderrWrite.apply(process.stderr, arguments);};43 unmodified lines444546474849505152535455562 unmodified lines59606162636465666768697071722 unmodified lines75767778798081828384853 unmodified lines89909192939495969798991001011021031041051068 unmodified lines1151161171181191202 unmodified lines1231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581593 unmodified lines16316416516616716888 unmodified lines25725825926026126242 unmodified lines30530630730830931013 unmodified lines3243253263273283294 unmodified lines3343353363373383391 unmodified line34134234334434534612 unmodified lines35936036136236336411 unmodified lines37637737837938038138238334 unmodified lines4184194204214224234 unmodified lines42842943043143243343412 unmodified lines44744844945045145256 unmodified lines50951051151251351410 unmodified lines5255265275285295305311 unmodified line53353453553653753853924 unmodified lines564565566567568569355 unmodified lines92592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199267 unmodified lines10601061106210631064106510667 unmodified lines10741075107610771078107910808 unmodified lines1089109010911092109310941095109610971098109911002 unmodified lines110311041105110611071108110936 unmodified lines114611471148114911501151115211531154115575 unmodified lines123112321233123412351236123712381239124012411242124312441245124612471248124912501251449 unmodified lines1701170217031704170517061707170817091710171117121713171417151716171717182 unmodified lines17211722172317241725172617273 unmodified lines17311732173317341735173617371 unmodified line173917401741174217431744174529 unmodified lines1775177617771778177917804 unmodified lines17851786178717881789179065 unmodified lines185618571858185918601861186218631864186518663 unmodified lines18701871187218731874187594 unmodified lines19701971197219731974197526 unmodified lines200220032004200520062007200855 unmodified lines206420652066206720682069207020712072207320742075207620772078207920802081208220832084208551 unmodified lines2137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902 unmodified lines2193219421952196219721982199220022012202220322042205220622072208220910 unmodified lines2220222122222223222422252226222722286 unmodified lines223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225921 unmodified lines228122822283228422852286148 unmodified lines243524362437243824392440244124422443203 unmodified lines264726482649265026512652197 unmodified lines285028512852285328542855373 unmodified lines322932303231323243 unmodified linesconst CIFTCI_COMMAND = "/çiftçi menü";const CIFTCI_WINDOW_TIMEOUT_MS = 6000;const CIFTCI_LORE_FALLBACK_KEYWORDS = ["hepsini sat"];const CIFTCI_CLICK_DELAY_AFTER_OPEN_MS = 1000;const CIFTCI_CLICK_REPEAT_COUNT = 3;const CIFTCI_CLICK_REPEAT_GAP_MS = 350;const KAZICI_CYCLE_INTERVAL_MS = 5 * 60 * 1000;const CIFTCI_CYCLE_INTERVAL_MS = 60 * 1000;const CIFTCI_FILTER_MODES = ["Standart","Favoriler",2 unmodified lines"Satışı açık olanlar","Toplaması açık olanlar"];const CIFTCI_TARGET_FILTER_INDEX = 3;const CIFTCI_ACTIVE_FILTER_COLOR = "#FCF988";const CIFTCI_FILTER_ITEM_NAME_KEYWORD = "Filtre";const CIFTCI_FILTER_STEP_WAIT_MS = 1000;const CIFTCI_FILTER_RETRY_WAIT_MS = 1000;const CIFTCI_FILTER_MAX_RETRIES = 10;const STORAGE_SCAN_INTERVAL_MS = 15 * 60 * 1000;const STORAGE_TRACKED_ITEMS = ["diamond", "emerald", "iron_block"];// --- SİPARİŞ (ORDER) SİSTEMİ AYARLARI ---const ORDER_COMMAND_PREFIX = "/order";2 unmodified linesconst ORDER_AFTER_SELECT_DELAY_MS = 500;const ORDER_IS_GO_SECOND_DELAY_MS = 5000;const ORDER_ALLOWED_ITEMS = ["diamond", "emerald"];const ORDER_LIST_TITLE_KEYWORD = "ѕiᴘᴀʀişʟᴇʀ";const ORDER_DELIVERY_TITLE_KEYWORD = "ᴛᴇѕʟiᴍ ᴇᴛᴍᴇ";// Nick seçildikten sonra Teslim Etme penceresinin gerçekten açılmasını beklemek için// kullanılan zaman aşımı (sabit sleep yerine).const ORDER_DELIVERY_WINDOW_WAIT_MS = 8000;let storageInfoCache = {diamond: null,3 unmodified lines};let storageScanIntervalHandle = null;let ciftciWindowPurpose = "sell";const STALL_CHECK_INTERVAL_MS = 15 * 1000;const STALL_TIMEOUT_MS = 60 * 1000;const FAILOVER_HOME_ARRIVAL_DELAY_MS = 4000;const FAILOVER_LOGIN_DELAY_MS = 2500;const FAILOVER_SKYBLOCK_DELAY_MS = 7500;const FAILOVER_ISGO_DELAY_MS = 12500;const FAILOVER_RECHECK_INTERVAL_MS = 20 * 1000;const FAILOVER_MAX_WAIT_MS = 60 * 60 * 1000;const FAILOVER_SPAWN_TIMEOUT_MS = 30 * 1000;const WATCHED_KAZICI_SKIN_HASHES = new Set(["eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDQ4ODcwY2E3N2FhNjk5ZDAxNzA5M2I4Mjc3OWQwYTU5OGRjNGYzZjQ5ZDM1MTUzMmFlNGQ5NjMzZGNjMmE1YSJ9fX0=",]);8 unmodified lineslet isListeningChat = false;const ansiToHtmlConvert = new (require('ansi-to-html'))({ newline: true });let isConnecting = false;let isDestroying = false;let reconnectTimeout = null;2 unmodified lineslet currentSocket = null;let windowOpenResolvers = [];let botUptimeStart = null;let lastFullFeedTimeStr = "Henüz besleme yapılmadı";let lastCheckTimeStr = "Henüz kontrol yapılmadı";let nextScheduledCheckTimeStr = "Botun spawn olması bekleniyor...";let lastKaziciCheckTimeStr = "Henüz kazıcı kontrolü yapılmadı";let nextKaziciTimeStr = "Botun spawn olması bekleniyor...";let nextKaziciAtMs = null;let lastCiftciSellTimeStr = "Henüz çiftçi satışı yapılmadı";let nextCiftciTimeStr = "Botun spawn olması bekleniyor...";let nextCiftciAtMs = null;let lastOrderTimeStr = "Henüz sipariş işlemi yapılmadı";let lastCheckAtMs = null;let nextScheduledCheckAtMs = null;let kaziciIntervalHandle = null;let ciftciIntervalHandle = null;let isMainCycleRunning = false;let poseTracker = new Map();let stallCheckIntervalHandle = null;let failoverModeActive = false;let failoverBot = null;let failoverInProgress = false;let activeConnectionIp = "Bilinmiyor";let activeConnectionLocation = "Bilinmiyor";let localExternalIp = "Bilinmiyor";let periodicTimeoutHandle = null;let activeTimeouts = [];3 unmodified linesreturn t;}class PriorityGuiMutex {constructor() {this._locked = false;88 unmodified linesnextCiftciTimeStr = "Zamanlama durduruldu.";}let manualStopRequested = false;async function getIpLocation(ip) {42 unmodified lines});}).on('error', () => {});function getEntitySkinHash(entity) {try {const equipment = entity.equipment || [];13 unmodified linesreturn null;}function hasIronPickaxeEquipped(entity) {try {const equipment = entity.equipment || [];4 unmodified lines}}function isWatchedKaziciEntity(entity) {if (!entity || entity.name !== "armor_stand") return false;const skinHash = getEntitySkinHash(entity);1 unmodified linereturn hasIronPickaxeEquipped(entity);}function getPoseKey(entity) {try {const md = entity.metadata || [];12 unmodified lines}}function trackKaziciPoseIfWatched(entity) {if (!entity) return;if (!isWatchedKaziciEntity(entity)) return;11 unmodified linesprev.poseKey = poseKey;prev.lastChangeAt = Date.now();}}function pruneStaleTrackedEntities() {if (!bot || !bot.entities) return;for (const id of poseTracker.keys()) {34 unmodified linesposeTracker.clear();}async function triggerFailoverSequence() {if (failoverInProgress) return;failoverInProgress = true;4 unmodified lineslogger.warn(`[Failover] İzlenen kazıcı(lar) durdu. Ana hesap (${mainUsername}) geçici olarak düşürülüp yedek hesap (${backupUsername}) devreye alınıyor.`);manualStopRequested = true;stopPeriodicHomeChecks();safeDestroyAllConnections();12 unmodified linesfailoverInProgress = false;}function runBackupAccountAndWaitForRecovery(backupUsername) {return new Promise((resolve) => {const backupPoseTracker = new Map();56 unmodified lineslogger.info(`[Failover - Yedek Hesap] ${GO_ISLAND_COMMAND} gönderildi, izlenen minyonların tekrar hareket etmesi bekleniyor...`);}, FAILOVER_ISGO_DELAY_MS);setTimeout(() => {recheckHandle = setInterval(() => {try {10 unmodified linesif (!prev) {backupPoseTracker.set(e.id, { poseKey, lastChangeAt: Date.now() });allRecovered = false;continue;}1 unmodified lineprev.poseKey = poseKey;prev.lastChangeAt = Date.now();} else if (Date.now() - prev.lastChangeAt < STALL_TIMEOUT_MS) {// ok} else {allRecovered = false;}24 unmodified lines}});safetyTimeoutHandle = setTimeout(() => {logger.warn(`[Failover - Yedek Hesap] Azami bekleme süresi (${formatDurationMs(FAILOVER_MAX_WAIT_MS)}) doldu, ana hesaba geri dönülüyor.`);finish();355 unmodified lines} catch (e) { return undefined; }};function getComponentData(slot, type) {try {if (!slot || !Array.isArray(slot.components)) return undefined;const comp = slot.components.find(c => c && c.type === type);return comp ? comp.data : undefined;} catch (e) { return undefined; }}function nbtUnwrap(node) {if (node && typeof node === "object" && "type" in node && "value" in node) {return node.value;}return node;};function flattenTextComponent(node) {if (node == null) return "";if (typeof node === "string") return node;if (Array.isArray(node)) return node.map(flattenTextComponent).join("");if (typeof node === "object") {if ("type" in node && "value" in node) {const t = node.type, v = node.value;if (t === "string") return typeof v === "string" ? v : "";if (t === "list" || t === "compound") return flattenTextComponent(v);return "";}let out = "";if ("text" in node) out += flattenTextComponent(node.text);if ("extra" in node) out += flattenTextComponent(node.extra);return out;}return "";};function parseComponentLoreLine(lineNode) {let text = "";let color = null;function walk(node) {if (node == null) return;if (typeof node === "string") { text += node; return; }if (Array.isArray(node)) { node.forEach(walk); return; }if (typeof node === "object") {if ("type" in node && "value" in node) {const t = node.type, v = node.value;if (t === "string") { text += (typeof v === "string" ? v : ""); return; }if (t === "list" || t === "compound") { walk(v); return; }return;}if ("color" in node) {const colVal = nbtUnwrap(node.color);if (color == null && typeof colVal === "string") color = colVal;}if ("text" in node) walk(node.text);if ("extra" in node) walk(node.extra);}}walk(lineNode);return { text: text.trim(), color };};function deepSearchForString(root, targetVariantsList) {const results = [];67 unmodified linesconst texts = [];try {if (!slot) return texts;const customNameData = getComponentData(slot, "custom_name");if (customNameData !== undefined) {const nameTxt = flattenTextComponent(customNameData);7 unmodified lines}}if (texts.length > 0) return texts;function extractPlain(raw) {if (!raw || typeof raw !== "string") return null;try {8 unmodified lines} catch (e) {}return raw;}if (slot.nbt) {const name = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);const plainName = extractPlain(name);if (plainName) texts.push(plainName);const lore = safeGet(slot.nbt, ["value", "display", "value", "Lore", "value"]);if (Array.isArray(lore)) {for (const line of lore) {2 unmodified lines}}}if (texts.length === 0) {texts.push(util.inspect(slot, { depth: null }));}36 unmodified lines}}const MONEY_BALANCE_REGEX = /bakiyen:\s*([\d.,]+)\s*TL/i;const MONEY_RESPONSE_TIMEOUT_MS = 8000;function parseBalanceToAdjustedAmount(rawBalanceStr) {const noCommas = rawBalanceStr.replace(/,/g, "");const beforeDot = noCommas.split(".")[0];const intValue = parseInt(beforeDot, 10);75 unmodified linesif (!bot || !botIsReady) return;try {const moves = ['forward', 'left', 'right', 'jump'];const moveCount = Math.floor(Math.random() * 4) + 2;for (let i = 0; i < moveCount; i++) {const move = moves[Math.floor(Math.random() * moves.length)];const duration = 150 + Math.floor(Math.random() * 500);bot.setControlState(move, true);await new Promise(r => setTimeout(r, duration));bot.setControlState(move, false);await new Promise(r => setTimeout(r, 100 + Math.random() * 300));}await bot.look(bot.entity.yaw + ((Math.random() - 0.5) * 1.5),bot.entity.pitch + ((Math.random() - 0.5) * 0.3),449 unmodified lines}}function stripColorAndGetLoreLines(window) {if (!window || !Array.isArray(window.slots)) return null;for (const slot of window.slots) {if (!slot) continue;let nameTxt = "";const customNameData = getComponentData(slot, "custom_name");if (customNameData !== undefined) {nameTxt = flattenTextComponent(customNameData);}if (!nameTxt && slot.nbt) {const nameRaw = safeGet(slot.nbt, ["value", "display", "value", "Name", "value"]);try {2 unmodified lineselse if (maybe && maybe.text) nameTxt = maybe.text;} catch (e) { nameTxt = nameRaw || ""; }}if (nameTxt.includes(CIFTCI_FILTER_ITEM_NAME_KEYWORD)) {return { slot, index: window.slots.indexOf(slot) };}3 unmodified linesfunction getFilterItemLoreEntries(filterSlot) {const entries = [];const loreData = getComponentData(filterSlot, "lore");if (Array.isArray(loreData)) {for (const line of loreData) {1 unmodified line}if (entries.length > 0) return entries;}try {const lore = safeGet(filterSlot.nbt, ["value", "display", "value", "Lore", "value"]);if (!Array.isArray(lore)) return entries;29 unmodified lines);if (match) return i;}const colorMatch = loreEntries.find(e => e.color === CIFTCI_ACTIVE_FILTER_COLOR);if (colorMatch) {for (let i = 0; i < CIFTCI_FILTER_MODES.length; i++) {4 unmodified lines}async function waitForFilterItem(maxRetries) {for (let attempt = 0; attempt <= maxRetries; attempt++) {await new Promise(r => setTimeout(r, attempt === 0 ? CIFTCI_FILTER_STEP_WAIT_MS : CIFTCI_FILTER_RETRY_WAIT_MS));if (!bot || !bot.currentWindow) return null;65 unmodified lines}const total = CIFTCI_FILTER_MODES.length;const forwardDist = (CIFTCI_TARGET_FILTER_INDEX - currentIndex + total) % total;const backwardDist = (currentIndex - CIFTCI_TARGET_FILTER_INDEX + total) % total;const useLeftClick = forwardDist <= backwardDist;const mouseButton = useLeftClick ? 0 : 1;logger.info(`[Çiftçi Filtre] Mevcut: "${CIFTCI_FILTER_MODES[currentIndex]}" -> Hedef: "${CIFTCI_FILTER_MODES[CIFTCI_TARGET_FILTER_INDEX]}". ${useLeftClick ? "Sol tık (aşağı)" : "Sağ tık (yukarı)"} kullanılacak.`);3 unmodified lineslogger.error(`[Çiftçi Filtre] Tıklama hatası: ${e && e.message ? e.message : e}`);return false;}}logger.warn("[Çiftçi Filtre] Azami deneme sayısına ulaşıldı, Jeneratör materyallerine geçilemedi.");94 unmodified lines// =====================================================================// SİPARİŞ (ORDER) SİSTEMİ// =====================================================================async function waitForNextWindowOpen(timeoutMs) {26 unmodified linesreturn -1;}async function processOrderCore(itemInternalName, nick) {if (!bot || !botIsReady) return { success: false, message: "Bot hazır değil." };if (!guiMutex.isLocked()) {logger.error("[GÜVENLİK İHLALİ] processOrderCore kilitsiz çağrıldı! İşlem iptal ediliyor.");55 unmodified lineslogger.error(`[Sipariş] Shift+sağ tık hatası: ${e && e.message ? e.message : e}`);}// --- YENİ: Çiftçiden gerçekten item alınmış mı doğrula ---// clickWindow hata fırlatmasa bile sunucu isteği görmezden gelmiş olabilir.// Envanterde ilgili item yoksa devam etmenin anlamı yok (Teslim Etme'ye zaten// aktarılacak bir şey olmaz), bu yüzden burada erkenden kontrol edip// anlamlı bir hata dönüyoruz.const itemsAfterWithdraw = bot.inventory.items().filter(it => it && it.name === itemInternalName);const withdrawnCount = itemsAfterWithdraw.reduce((sum, it) => sum + (it.count || 0), 0);logger.info(`[Sipariş] Çiftçiden çekildikten sonra envanterde '${itemInternalName}': ${withdrawnCount} adet.`);if (withdrawnCount === 0) {logger.warn(`[Sipariş] Çiftçi menüsünden '${itemInternalName}' envantere aktarılamadı (0 adet). İşlem iptal ediliyor.`);try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}ciftciWindowPurpose = "sell";return { success: false, message: `Çiftçiden '${itemInternalName}' alınamadı (envanterde 0 adet). Depoda yeterli stok olmayabilir ya da tıklama sunucu tarafından işlenmedi.` };}// --- 3) Menüyü kapat ---try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}// ÖNEMLİ: purpose burada "sell"e ÇEVRİLMEZ! /order akışı (Siparişler +51 unmodified lines}logger.info(`[Sipariş] '${nick}' içeren item bulundu (idx:${targetSlotIndex}), sol tık gönderiliyor...`);// --- YENİ: nick'e tıkladıktan sonra sabit 500ms yerine GERÇEK yeni// pencere açılışını (Teslim Etme) bekliyoruz. Bu, mevcut buğun ana// sebebiydi: sunucu 500ms'den geç yanıt verirse eski (Siparişler)// penceresine göre hesaplanmış slotlara tıklanıyor ve hiçbir şey// taşınmıyordu (sunucu paketi reddetmediği için hata da görünmüyordu).const windowBeforeSelect = bot.currentWindow;try {await bot.clickWindow(targetSlotIndex, 0, 0);} catch (e) {logger.error(`[Sipariş] Slot seçim tıklaması hatası: ${e && e.message ? e.message : e}`);}// --- 8) Teslim Etme penceresinin gerçekten açılmasını bekle ---const deliveryOpened = await waitForNextWindowOpen(ORDER_DELIVERY_WINDOW_WAIT_MS);if (!deliveryOpened || !bot.currentWindow) {logger.warn("[Sipariş] Teslim Etme penceresi zaman aşımına uğradı ya da açılmadı, işlem yarım kalmış olabilir.");ciftciWindowPurpose = "sell";return { success: false, message: "Teslim Etme penceresi açılmadı (zaman aşımı)." };}// Pencere objesinin gerçekten DEĞİŞTİĞİNİ doğrula (bazı sunucular aynı id'yi// update edip windowOpen yerine sadece slot update gönderebilir; bu durumda// en azından title kontrolüyle devam ediyoruz).if (bot.currentWindow === windowBeforeSelect) {logger.warn("[Sipariş] windowOpen tetiklendi ama pencere referansı değişmedi, dikkatli devam ediliyor.");}const currentTitle = parseWindowTitleToString(bot.currentWindow.title);const looksLikeDelivery = matchesAnyName(currentTitle, normalizeVariants(ORDER_DELIVERY_TITLE_KEYWORD));logger.info(`[Sipariş] Yeni pencere açıldı: "${currentTitle}" (Teslim Etme eşleşmesi: ${looksLikeDelivery}). Envanterdeki '${itemInternalName}' item'ları aktarılıyor...`);if (!looksLikeDelivery) {logger.warn(`[Sipariş] Açılan pencere Teslim Etme'ye benzemiyor, yine de mevcut pencereye aktarım denenecek: "${currentTitle}"`);}// Ek güvenlik: envanterde gerçekten aktarılacak item var mı, tekrar kontrol et// (nick seçme / /is go arasında item'lar herhangi bir sebeple kaybolmuş olabilir).const invCheckBeforeTransfer = bot.inventory.items().filter(it => it && it.name === itemInternalName);if (invCheckBeforeTransfer.length === 0) {logger.warn(`[Sipariş] Aktarım öncesi envanterde '${itemInternalName}' bulunamadı, aktarım atlanıyor.`);try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}ciftciWindowPurpose = "sell";return { success: false, message: `Envanterde '${itemInternalName}' kalmamış, Teslim Etme'ye aktarılacak item yok.` };}const windowAtTransferStart = bot.currentWindow;let transferredCount = 0;let keepGoing = true;let safetyCounter = 0;2 unmodified lineswhile (keepGoing && safetyCounter < 40) {safetyCounter++;// Pencere döngü sırasında değişti/kapandıysa (ör. sunucu Teslim Etme'yi// kapattıysa) devam etmenin bir anlamı yok, güvenle çık.if (!bot.currentWindow || bot.currentWindow !== windowAtTransferStart) {logger.warn("[Sipariş] Aktarım sırasında pencere değişti/kapandı, döngü durduruluyor.");break;}const invItem = bot.inventory.items().find(it => it && it.name === itemInternalName);if (!invItem) { keepGoing = false; break; }if (stuckSlot === invItem.slot) {stuckSlotRepeatCount++;if (stuckSlotRepeatCount >= 3) {10 unmodified linesawait bot.clickWindow(invItem.slot, 0, 1); // mouseButton=0 (sol), mode=1 (shift)await new Promise(r => setTimeout(r, 250));const stillThere = bot.inventory.items().find(it => it && it.slot === invItem.slot && it.name === itemInternalName);if (!stillThere) {transferredCount++;} else {logger.warn(`[Sipariş] Slot ${invItem.slot} tıklandı ama item hâlâ envanterde, taşınmamış olabilir.`);}6 unmodified linesif (safetyCounter >= 40) {logger.warn(`[Sipariş] Güvenlik limitine (40 deneme) ulaşıldı. Teslim Etme kutusu dolu/limitli olabilir, transfer yarım kalmış olabilir.`);}const remainingAfterTransfer = bot.inventory.items().filter(it => it && it.name === itemInternalName).reduce((sum, it) => sum + (it.count || 0), 0);logger.info(`[Sipariş] Envanterden Teslim Etme'ye aktarım turu tamamlandı (${transferredCount} yığın gönderildi, envanterde kalan: ${remainingAfterTransfer}).`);// --- 9) Pencereyi kapat ---try { if (bot.currentWindow) bot.closeWindow(bot.currentWindow); } catch (e) {}ciftciWindowPurpose = "sell"; // akış tamamen bitti, artık normal davranışa dönreturn {success: transferredCount > 0,message: transferredCount > 0 ? "Sipariş işlemi tamamlandı." : "Hiçbir yığın Teslim Etme'ye aktarılamadı.",item: itemInternalName,nick,withdrawn_from_ciftci: withdrawnCount,inventory_transferred_batches: transferredCount,remaining_in_inventory: remainingAfterTransfer};}21 unmodified linesscanStorageInfo();}, STORAGE_SCAN_INTERVAL_MS);logger.info(`[Storage Tarama] Bağımsız döngü başlatıldı (her ${formatDurationMs(STORAGE_SCAN_INTERVAL_MS)}).`);setSafeTimeout(() => { scanStorageInfo(); }, 30 * 1000);}148 unmodified linesconst isCiftciWindow = !isBesleyiciWindow && !isKaziciWindow &&(matchesAnyName(titleRaw, TARGET_CIFTCI_NORMS) || windowMatchesLoreKeyword(window, CIFTCI_LORE_FALLBACK_KEYWORDS));if (!isBesleyiciWindow && !isKaziciWindow && !isCiftciWindow) {if (ciftciWindowPurpose === "order") {logger.info(`[${currentBotUsername}] Sipariş (/order) penceresi açıldı: ${titleRaw}`);} else {logger.info(`[${currentBotUsername}] Bi chest açıldı ama window title ı uyuşmadığı için kapatıldı. ${titleRaw}`);try { bot.closeWindow(window); } catch(e){}203 unmodified lines}, delay);}let pendingHardRestartTimeout = null;function stopBotHard(reason) {197 unmodified lines});});app.get("/bot/stop", (req, res) => {stopBotHard("Web paneli üzerinden /bot/stop isteği");res.send({ success: true, message: "Bot durduruldu. Tekrar başlatmak için /bot/start kullan." });373 unmodified linesreturn true;}return originalStderrWrite.apply(process.stderr, arguments);};
bot.js+177-202