Update bot.js
Browse files7 unmodified lines891011121314151617111213141519202116231718262719292021227 unmodified lines303132434433344647353637385039404142434445464748495051525354555637 unmodified lines9495969495969797989998991021031041001011021071031041051111061131071081091101111121191201211221231241251261271281131141151311321331341351361371381391401411421431441451461471481491501511521531541551561161581591601611621631641171651661671681691701711721731741181191771781791801201211221231 unmodified line1251261271881891901911921931941951961971981992002012022032042052062072082092102112122132141281291301311321332171341351362211371381393 unmodified lines1431441452311461472342351481491501512402412422431521532452462472481541552502512521561572542551582572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523531591601611621631641653563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094101664124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434441671681691701714474484494504514524534544554564574584594604614624634644654664674684694704714721724744754761731744774784791751761774834844854864871781791801814901824924934944954964974984995005015025035045055065075085095105115121831841851861871881891901911921931941951961971981992002012025175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535542032042052065555565575582075602082092102115625635645655665675685695705715725735745755765772122132142152162172182192202212222232242252262272282292302312325812335835842345852352365885892372382395922402412425952432445972452462476002482496026032502512522532542556086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736742562572582592602612622632642652662672686786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217222692702712722732742752762772782792807247257262812822832842852867287297307317327332877347352887377387397407417427437447457467477487497507517522892902912922937567577587597607617627637647657667677687697707717727737742942952962972987767777787797807817827837847857867872993003017917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568573023033043058603063073083098658668678688698708718723103117 unmodified linesconst loggers = require("./logging.js");const logger = loggers.logger;
// --- AYARLAR (Buradan hızlıca değiştirebilirsin) ---const HOME_ARRIVAL_DELAY_MS = 1500; // /home sonrası bekleme (ms)const POST_ACTION_DELAY_MS = 2500; // panel işlem sonrası kısa bekleme (ms)const WINDOW_OPEN_TIMEOUT_MS = 2600; // panel açılma timeout (ms)
// Periyodik kontrol aralığı (50dk bekleme bittikten sonra bu aralıkla kontrol et)// Kullanıcı isteğine göre 10 dakika önerildi: 10 * 60 * 1000// --- AYARLAR ---const HOME_ARRIVAL_DELAY_MS = 2000;const POST_ACTION_DELAY_MS = 4000;const WINDOW_OPEN_TIMEOUT_MS = 6000;const PERIODIC_CHECK_INTERVAL_MS = 10 * 60 * 1000;
// Eğer minyon canı 10 ise veya besleme yapıldıysa bekleme süresi (ms).// Varsayılan 50 dakika. İstersen süreyi değiştirmek için burayı düzenle.const FULL_FEED_COOLDOWN_MS = 50 * 60 * 1000;
const GO_HOME_COMMAND = "/home";const RETURN_ISLAND_COMMAND = "/is home";
// Besleyici isimleri (array). Birden fazla isim desteklenir.const BESLEYICI_NAMES = (config.utils && config.utils["besleyici-names"]) || ["Besleyici", "ʙᴇsʟᴇʏiᴄi"];// ------------------------------------------------
function createBot() { const bot = mineflayer.createBot({7 unmodified lines
bot.loadPlugin(pathfinder);
// --- Durum / zamanlayıcı değişkenleri --- // Son tam besleme (veya panelde can 10 görüldüğü zaman) zaman damgası (ms) // --- SADECE TİMİNG SIFIRLAMA İÇİN EKLENEN KISIM --- let lastFullFeedAt = 0;
// windowOpen bekleyici resolver listesi (mevcut mantığı korumak için) let windowOpenResolvers = []; let periodicHandle = null; let activeTimeouts = [];
// --- Yardımcı fonksiyonlar --- function setSafeTimeout(fn, delay) { const t = setTimeout(fn, delay); activeTimeouts.push(t); return t; }
function stopPeriodicHomeChecks() { if (periodicHandle) clearInterval(periodicHandle); periodicHandle = null; activeTimeouts.forEach(t => clearTimeout(t)); activeTimeouts = []; } // ------------------------------------------------
// --- 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, "");37 unmodified lines let cur = obj; for (const p of pathArray) { if (cur == null) return undefined; if (typeof p === "number") { if (!Array.isArray(cur)) return undefined; cur = cur[p]; cur = cur[p]; } else { cur = cur[p]; } } return cur; } catch (e) { return undefined; } } catch (e) { return undefined; } }
// Deep search sadece fallback olarak kullanılacak function deepSearchForString(root, targetLower) { const results = []; const visited = new WeakSet();
function recurse(obj, path) { if (obj == null) return; if (obj == null || typeof obj === "function") return; if (typeof obj === "string") { const norm = normalizeForMatch(obj); if (norm.includes(targetLower)) results.push({ path, value: obj }); return; } if (typeof obj !== "object") { try { const s = obj != null ? obj.toString() : ""; if (typeof s === "string") { const norm = normalizeForMatch(s); if (norm.includes(targetLower)) results.push({ path, value: s }); } } catch (e) {} return; } if (typeof obj !== "object") return; if (visited.has(obj)) return; visited.add(obj);
if (obj.displayName && typeof obj.displayName.toString === "function") { try { const s = obj.displayName.toString(); if (typeof s === "string") { const norm = normalizeForMatch(s); if (norm.includes(targetLower)) results.push({ path: path + ".displayName", value: s }); } } catch (e) {} }
if (Array.isArray(obj)) { for (let i = 0; i < obj.length; i++) recurse(obj[i], `${path}[${i}]`); return; }
if (obj instanceof Map) { let idx = 0; for (const [k, v] of obj.entries()) { recurse(k, `${path}.MapKey(${idx})`); recurse(v, `${path}.MapValue(${idx})`); idx++; } return; }
for (const key of Object.keys(obj)) { try { const val = obj[key]; if (typeof val === "string") { const norm = normalizeForMatch(val); if (norm.includes(targetLower)) results.push({ path: `${path}.${key}`, value: val }); } else if (val && typeof val === "object") { recurse(val, `${path}.${key}`); recurse(obj[key], `${path}.${key}`); } else { try { const s = val != null ? val.toString() : ""; if (typeof s === "string") { const norm = normalizeForMatch(s); if (norm.includes(targetLower)) results.push({ path: `${path}.${key}`, value: s }); } } catch (e) {} } } catch (e) {} } }
try { recurse(root, "root"); } catch (e) {} try { recurse(root, "root"); } catch (e) {} return results; }
1 unmodified line try { if (!titleObj) return ""; if (typeof titleObj === "string") return titleObj; if (titleObj && typeof titleObj.toString === "function") { const s = titleObj.toString(); if (s && s !== "[object Object]") return s; } if (typeof titleObj === "object") { if (typeof titleObj.text === "string" && titleObj.text.trim().length > 0) return titleObj.text; if (Array.isArray(titleObj.extra) && titleObj.extra.length > 0) { for (const e of titleObj.extra) { if (!e) continue; if (typeof e === "string" && e.trim()) return e; if (e && typeof e.text === "string" && e.text.trim()) return e.text; try { const s = e.toString(); if (s && s !== "[object Object]") return s; } catch (e2) {} } } try { return JSON.stringify(titleObj); } catch (e) { return String(titleObj); } } return String(titleObj); } catch (err) { try { return String(titleObj); } catch (e) { return ""; } } const s = titleObj.toString(); if (s && s !== "[object Object]") return s; return JSON.stringify(titleObj); } catch (err) { return ""; } }
// --- Minyon canı çıkarma (geliştirilmiş, çeşitli yolları dener) --- function extractMinyonCanFromSlot(slot) { try { if (!slot) return null;
function tryParseLoreText(text) { try { if (!text || typeof text !== "string") return null;3 unmodified lines if (maybe && typeof maybe === "object") { if (maybe.extra && Array.isArray(maybe.extra) && maybe.extra.length > 0) { if (typeof maybe.extra[0].text === "string") plain = maybe.extra[0].text; else plain = JSON.stringify(maybe.extra); } else if (typeof maybe.text === "string") { plain = maybe.text; } else { plain = JSON.stringify(maybe); } } } catch (e) {} const xyMatch = plain.match(/(\d{1,4})\s*\/\s*(\d{1,4})/); if (xyMatch) { const x = Number(xyMatch[1]); if (!Number.isNaN(x)) return x; } if (xyMatch) return Number(xyMatch[1]); const numMatch = plain.match(/(\d{1,4})/); if (numMatch) { const n = Number(numMatch[1]); if (!Number.isNaN(n)) return n; } if (numMatch) return Number(numMatch[1]); return null; } catch (e) { return null; } } catch (e) { return null; } }
// 1) slot.nbt yolları if (slot.nbt) { try { const candidates = [ ["value", "display", "value", "Lore", "value"], ["value", "display", "value", "Lore"], ["value", "display", "value"], ]; for (const path of candidates) { let cur = slot.nbt; let ok = true; for (const p of path) { if (cur == null) { ok = false; break; } cur = cur[p]; } if (!ok) continue; if (Array.isArray(cur) && cur.length > 0) { const tryIndices = [1, cur.length - 1, 0]; for (const idx of tryIndices) { const item = cur[idx]; if (!item) continue; if (typeof item === "string") { const parsed = tryParseLoreText(item); if (parsed != null) return parsed; } if (item && typeof item.value === "string") { const parsed = tryParseLoreText(item.value); if (parsed != null) return parsed; } try { const s = item.toString(); const parsed = tryParseLoreText(s); if (parsed != null) return parsed; } catch (e) {} } } else if (typeof cur === "string") { const parsed = tryParseLoreText(cur); if (parsed != null) return parsed; } else if (cur && typeof cur.toString === "function") { const parsed = tryParseLoreText(cur.toString()); if (parsed != null) return parsed; } } } catch (e) {} }
// 2) components içinde custom_data veya lore try { if (Array.isArray(slot.components)) { for (const c of slot.components) { if (!c) continue; if (c.type === "custom_data" && c.data && c.data.value && c.data.value.display && c.data.value.display.value && c.data.value.display.value.Lore) { const loreObj = c.data.value.display.value.Lore; if (loreObj && loreObj.value && Array.isArray(loreObj.value)) { for (const s of loreObj.value) { const parsed = tryParseLoreText(String(s)); if (parsed != null) return parsed; } } else if (typeof loreObj === "string") { const parsed = tryParseLoreText(loreObj); if (parsed != null) return parsed; } } if (c.type === "lore" && Array.isArray(c.data)) { for (const entry of c.data) { const text = safeGet(entry, ["value", "text", "value"]) || safeGet(entry, ["value", "extra", "value", 0, "value", "text", "value"]) || (entry && entry.toString && entry.toString()); const parsed = tryParseLoreText(String(text || "")); if (parsed != null) return parsed; } } } } } catch (e) {}
// 3) componentMap kontrolü try { if (slot.componentMap && typeof slot.componentMap === "object") { const getFromMap = (m, key) => { try { if (m.get) return m.get(key); return m[key]; } catch (e) { return null; } }; const loreComp = getFromMap(slot.componentMap, "custom_data") || getFromMap(slot.componentMap, "lore"); if (loreComp) { const data = loreComp.data || loreComp; if (Array.isArray(data)) { for (const entry of data) { const text = safeGet(entry, ["value", "text", "value"]) || entry.toString?.(); const parsed = tryParseLoreText(String(text || "")); if (parsed != null) return parsed; } } else if (data && data.value && Array.isArray(data.value)) { for (const item of data.value) { const text = safeGet(item, ["value", "text", "value"]) || item.toString?.(); const parsed = tryParseLoreText(String(text || "")); if (parsed != null) return parsed; } } const lore = safeGet(slot.nbt, ["value", "display", "value", "Lore", "value"]); if (Array.isArray(lore)) { for (const line of lore) { const res = tryParseLoreText(line.value || line); if (res != null) return res; } } } catch (e) {}
// 4) fallback: inspect tüm slot try { const full = util.inspect(slot, { depth: null, maxArrayLength: null }); const xyMatch = full.match(/(\d{1,4})\s*\/\s*(\d{1,4})/); if (xyMatch) return Number(xyMatch[1]); const numMatch = full.match(/(\d{1,4})/); if (numMatch) return Number(numMatch[1]); } catch (e) {}
return null; } catch (err) { logger.warn("extractMinyonCanFromSlot hata: " + (err && err.message ? err.message : err)); return null; } }
// --- Activate API detection (startup) --- let hasActivateAt = false; let hasActivate = false; function detectActivateApis() { hasActivateAt = typeof bot.activateEntityAt === "function"; hasActivate = typeof bot.activateEntity === "function"; }
// safe activate: prefer activateEntityAt, minimal logging async function safeActivateEntityPreferAt(entity, options = {}) { const maxRetries = options.maxRetries ?? 3; const retryDelay = options.retryDelay ?? 250; const requireLook = options.requireLook ?? true; const maxDistance = options.maxDistance ?? 7;
if (!entity) { logger.warn("safeActivateEntityPreferAt: entity yok"); return false; }
try { if (entity.position && bot.entity && bot.entity.position) { const dist = entity.position.distanceTo(bot.entity.position); if (dist > maxDistance) { logger.warn(`safeActivateEntityPreferAt: entity id:${entity.id} uzak (${dist.toFixed(2)}). Max ${maxDistance} blok.`); return false; } }
if (requireLook && entity.position && bot.lookAt) { try { const lookPos = (typeof entity.position.offset === "function") ? entity.position.offset(0, 1.5, 0) : { x: entity.position.x, y: entity.position.y + 1.5, z: entity.position.z }; await bot.lookAt(lookPos, true); await new Promise(r => setTimeout(r, 180)); } catch (e) {} }
for (let attempt = 1; attempt <= maxRetries; attempt++) { try { if (hasActivateAt) { try { bot.activateEntityAt(entity, entity.position); logger.info(`activateEntityAt çağrıldı id:${entity.id}`); return true; } catch (err) { // retry silently } } if (hasActivate) { try { bot.activateEntity(entity); logger.info(`activateEntity çağrıldı id:${entity.id}`); return true; } catch (err) { // retry silently } } } catch (err) { // swallow and retry } await new Promise(r => setTimeout(r, retryDelay)); }
logger.warn(`safeActivateEntityPreferAt: tüm denemeler başarısız id:${entity.id}`); return false; } catch (err) { logger.error(`safeActivateEntityPreferAt hata: ${err && err.stack ? err.stack : err}`); return false; } const full = util.inspect(slot, { depth: null }); return tryParseLoreText(full); } catch (err) { return null; } }
// windowOpen wait helper (mevcut resolver mantığını koruyor) function waitForWindowOpenOrTimeout(timeoutMs) { return new Promise((resolve) => { try { if (bot.currentWindow && bot.currentWindow.type) { resolve({ opened: true }); return; } } catch (e) {}
const timer = setTimeout(() => { const idx = windowOpenResolvers.indexOf(resolver); if (idx !== -1) windowOpenResolvers.splice(idx, 1); resolve({ opened: false, timedOut: true }); }, timeoutMs);
function resolver() { clearTimeout(timer); resolve({ opened: true, timedOut: false }); }
windowOpenResolvers.push(resolver); }); }
// --- GO / SCAN / RETURN helpers --- async function goHome() { try { logger.info(`[${config["bot-account"]["username"]}] ${GO_HOME_COMMAND} komutu gönderiliyor.`); bot.chat(GO_HOME_COMMAND); logger.info(`[${config["bot-account"]["username"]}] ${GO_HOME_COMMAND} komutu gönderiliyor.`); bot.chat(GO_HOME_COMMAND); } catch (e) { logger.warn("goHome: komut gönderilemedi: " + (e && e.message ? e.message : e)); } }
async function returnIsland() { try { bot.chat(RETURN_ISLAND_COMMAND); } catch (e) { logger.warn("returnIsland: komut gönderilemedi: " + (e && e.message ? e.message : e)); } logger.info(`[${config["bot-account"]["username"]}] ${RETURN_ISLAND_COMMAND} komutu gönderiliyor.`); bot.chat(RETURN_ISLAND_COMMAND); }
// Scan & feed mantığı (aynı işleyiş korunuyor) async function scanAndFeed() { try { // Eğer son tam beslemeden (veya can 10 görüldüğünden) henüz FULL_FEED_COOLDOWN_MS geçmediyse atla if (Date.now() < (lastFullFeedAt + FULL_FEED_COOLDOWN_MS)) { // sessizce atla; log spam olmasın return; }
const arr = Object.values(bot.entities); if (!arr || arr.length === 0) { logger.info(`[${config["bot-account"]["username"]}] /home sonrası: entity bulunamadı.`); return; }
// 1) quick checks let found = null; let foundPath = null; for (const e of arr) { const name = getEntityReadableName(e); if (isBesleyiciName(name)) { found = e; foundPath = "displayName/name"; if (Date.now() < (lastFullFeedAt + FULL_FEED_COOLDOWN_MS)) return; const arr = Object.values(bot.entities); let best = null;
for (const e of arr) { const name = getEntityReadableName(e); if (isBesleyiciName(name)) { best = { entity: e, path: "displayName/name" }; break; } for (const target of TARGET_NAME_NORMS) { const deep = deepSearchForString(e, target); if (deep.length > 0) { best = { entity: e, path: deep[0].path }; break; } } if (best) break; }
// 2) metadata quick path if (!found) { for (const e of arr) { const candidate = safeGet(e, ["metadata", 2, "value", "extra", "value", "value", 0]); if (candidate) { let candidateStr = null; try { if (typeof candidate === "string") candidateStr = candidate; else if (candidate && typeof candidate.toString === "function") candidateStr = candidate.toString(); else candidateStr = util.inspect(candidate, { depth: 1 }); } catch (err) { candidateStr = String(candidate); } if (TARGET_NAME_NORMS.some(t => normalizeForMatch(candidateStr).includes(t))) { found = e; foundPath = "metadata[2].value.extra.value.value[0]"; break; } } } }
// 3) deep search only if still not found if (!found) { for (const e of arr) { const matches = deepSearchForString(e, TARGET_NAME_NORMS[0]); if (matches && matches.length > 0) { found = e; foundPath = matches[0].path; break; } } }
if (!found) { logger.info(`[${config["bot-account"]["username"]}] /home sonrası tarama: besleyici minyon bulunamadı.`); return; } if (!best) { logger.info(`[${config["bot-account"]["username"]}] /home sonrası tarama: besleyici minyon bulunamadı.`); return; }
const readable = getEntityReadableName(found); const dist = (found.position && bot.entity && bot.entity.position) ? found.position.distanceTo(bot.entity.position).toFixed(2) : "n/a"; logger.info(`[${config["bot-account"]["username"]}] '${readable || BESLEYICI_NAMES[0]}' bulundu id:${found.id} path:${foundPath} dist:${dist} — aktive ediliyor.`);
detectActivateApis(); const dist = bot.entity.position.distanceTo(best.entity.position); // SENİN LOGUN: 'Armor Stand' bulundu id:... 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.`);
const activated = await safeActivateEntityPreferAt(found, { maxRetries: 4, retryDelay: 300, requireLook: true, maxDistance: 7 }); if (!activated) { logger.warn(`[${config["bot-account"]["username"]}] '${BESLEYICI_NAMES[0]}' aktive edilemedi (id:${found.id}).`); return; }
// wait for windowOpen (handler will process and set lastFullFeedAt if needed) const waitResult = await waitForWindowOpenOrTimeout(WINDOW_OPEN_TIMEOUT_MS); if (waitResult.opened) { await new Promise(r => setTimeout(r, POST_ACTION_DELAY_MS)); } else { logger.warn(`[${config["bot-account"]["username"]}] Panel açılmadı veya timeout oldu; devam ediliyor.`); await new Promise(r => setTimeout(r, POST_ACTION_DELAY_MS)); } } catch (err) { logger.error("scanAndFeed hata: " + (err && err.stack ? err.stack : err)); 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; }
try { if (bot.lookAt) await bot.lookAt(best.entity.position.offset(0, 1.0, 0), true); await new Promise(r => setTimeout(r, 200)); logger.info(`activateEntityAt çağrıldı id:${best.entity.id}`); if (typeof bot.activateEntityAt === "function") bot.activateEntityAt(best.entity, best.entity.position); else if (typeof bot.activateEntity === "function") bot.activateEntity(best.entity); await new Promise((resolve) => { const timer = setTimeout(() => resolve(), WINDOW_OPEN_TIMEOUT_MS); windowOpenResolvers.push(() => { clearTimeout(timer); resolve(); }); }); } catch (err) {} }
// --- Bot olayları ve ana mantık --- bot.once("spawn", async () => { const defaultMove = new Movements(bot); bot.pathfinder.setMovements(defaultMove); bot.pathfinder.setMovements(new Movements(bot)); bot.settings.colorsEnabled = false; logger.info("Bot sunucuya giriş yaptı.");
detectActivateApis();
if (config.utils && config.utils["auto-auth"] && config.utils["auto-auth"].enabled) { const password = config.utils["auto-auth"].password; setTimeout(() => { setSafeTimeout(() => { bot.chat(`/login ${password}`); logger.info(`[${config["bot-account"]["username"]}] Login komutu kullanıldı.`); }, 500); }, 2500);
setTimeout(() => { setSafeTimeout(() => { bot.chat(`/skyblock`); logger.info(`[${config["bot-account"]["username"]}] Skyblock'a ışınlanma komutu kullanıldı.`); }, 5000); }, 7500);
// İlk döngü: goHome -> scanAndFeed -> returnIsland setTimeout(async () => { setSafeTimeout(async () => { await goHome(); await new Promise(r => setTimeout(r, HOME_ARRIVAL_DELAY_MS)); await scanAndFeed(); await new Promise(r => setTimeout(r, POST_ACTION_DELAY_MS)); await returnIsland(); startPeriodicHomeChecks(); }, 10000); } else { startPeriodicHomeChecks(); }
// chat-messages, position, anti-afk mantığı aynen korunuyor if (config.utils && config.utils["chat-messages"] && config.utils["chat-messages"].enabled) { logger.info("Started chat-messages module"); let messages = config.utils["chat-messages"]["messages"]; if (config.utils["chat-messages"].repeat) { let delay = config.utils["chat-messages"]["repeat-delay"]; let i = 0; setInterval(() => { bot.chat(`${messages[i]}`); if (i + 1 === messages.length) i = 0; else i++; }, delay * 1000); } else { messages.forEach((msg) => bot.chat(msg)); } }
const pos = config.position; if (config.position && config.position.enabled) { logger.info(`Starting moving to target location (${pos.x}, ${pos.y}, ${pos.z})`); bot.pathfinder.setGoal(new GoalBlock(pos.x, pos.y, pos.z)); }
if (config.utils && config.utils["anti-afk"] && config.utils["anti-afk"].enabled) { if (config.utils["anti-afk"].sneak) bot.setControlState("sneak", true); if (config.utils["anti-afk"].jump) bot.setControlState("jump", true);
if (config.utils["anti-afk"]["hit"] && config.utils["anti-afk"]["hit"].enabled) { let delay = config.utils["anti-afk"]["hit"]["delay"]; let attackMobs = config.utils["anti-afk"]["hit"]["attack-mobs"]; setInterval(() => { if (attackMobs) { let entity = bot.nearestEntity( (e) => e.type !== "object" && e.type !== "player" && e.type !== "global" && e.type !== "orb" && e.type !== "other", ); if (entity) { bot.attack(entity); return; } } bot.swingArm("right", true); }, delay); }
if (config.utils["anti-afk"].rotate) { setInterval(() => { bot.look(bot.entity.yaw + 1, bot.entity.pitch, true); }, 100); }
if (config.utils["anti-afk"]["circle-walk"] && config.utils["anti-afk"]["circle-walk"].enabled) { let radius = config.utils["anti-afk"]["circle-walk"]["radius"]; setInterval(() => { circleWalk(bot, radius); }, 30000); } periodicHandle = setInterval(async () => { if (Date.now() < (lastFullFeedAt + FULL_FEED_COOLDOWN_MS)) return; await goHome(); await new Promise(r => setTimeout(r, HOME_ARRIVAL_DELAY_MS)); await scanAndFeed(); await new Promise(r => setTimeout(r, POST_ACTION_DELAY_MS)); await returnIsland(); }, PERIODIC_CHECK_INTERVAL_MS); }, 12500); } });
// windowClose: resolver'ları çözer bot.on("windowClose", (window) => { try { while (windowOpenResolvers.length > 0) { const r = windowOpenResolvers.shift(); try { r(); } catch (e) {} } } catch (e) {} });
// windowOpen: minimal log, tek satır sonuç; burada lastFullFeedAt ayarlanır bot.on("windowOpen", function (window) { try { const titleStr = parseWindowTitleToString(window.title); const panelMatch = (titleStr && (titleStr.toLowerCase().includes("besleyici") || titleStr.includes("ʙᴇsʟᴇʏiᴄi"))); if (!panelMatch) { try { bot.closeWindow(window); } catch (e) {} try { while (windowOpenResolvers.length > 0) { const r = windowOpenResolvers.shift(); try { r(); } catch (e) {} } } catch (e) {} return; }
const beefSlots = window.slots.filter(xx => xx?.name && xx?.name === "cooked_beef"); if (beefSlots.length === 0) { try { bot.closeWindow(window); } catch (e) {} try { while (windowOpenResolvers.length > 0) { const r = windowOpenResolvers.shift(); try { r(); } catch (e) {} } } catch (e) {} return; }
const beefSlot = beefSlots[0]; const minyoncani = extractMinyonCanFromSlot(beefSlot);
if (minyoncani == null) { logger.info(`[${config["bot-account"]["username"]}] Minyon canı okunamadı (null).`); } else if (minyoncani <= 2) { // Besleme yapıldı bot.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; } const beefSlot = window.slots.find(s => s?.name === "cooked_beef"); const can = extractMinyonCanFromSlot(beefSlot); if (can != null) { if (can <= 2) { bot.clickWindow(36, 0, 0); lastFullFeedAt = Date.now(); // besleme yapıldığı an 50dk bekle logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${minyoncani} olduğu için beslendi. ${FULL_FEED_COOLDOWN_MS / 60000}dk bekleme aktif.`); try { bot.closeWindow(window); } catch (e) {} 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 { // Eğer can 10 ise veya yüksekse, 50dk bekleme kuralını tetikle if (minyoncani >= 10) { lastFullFeedAt = Date.now(); logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${minyoncani} (tam). ${FULL_FEED_COOLDOWN_MS / 60000}dk bekleme aktif.`); } else { logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${minyoncani} olduğu için yenilenmedi.`); logger.info(`[${config["bot-account"]["username"]}] Minyon canı ${can} olduğu için yenilenmedi.`); } try { bot.closeWindow(window); } catch (e) {} }
try { while (windowOpenResolvers.length > 0) { const r = windowOpenResolvers.shift(); try { r(); } catch (e) {} } } catch (e) {} } catch (err) { logger.error("windowOpen işlenirken hata: " + (err && err.stack ? err.stack : err)); try { bot.closeWindow(window); } catch (e) {} try { while (windowOpenResolvers.length > 0) { const r = windowOpenResolvers.shift(); try { r(); } catch (e) {} } } catch (e) {} } setSafeTimeout(() => { try { bot.closeWindow(window); } catch(e){} }, 500); while (windowOpenResolvers.length > 0) windowOpenResolvers.shift()(); });
bot.on("chat", (username, message) => { if (config.utils && config.utils["chat-log"]) logger.info(`<${username}> ${message}`); });
bot.on('login', () => { // 1. Ayarları gerçekçi yap bot._client.write('settings', { locale: 'tr_tr', viewDistance: 10, chatFlags: 0, chatColors: true, skinParts: 127, mainHand: 1 }); });
bot.on("goal_reached", () => { if (config.position && config.position.enabled) logger.info(`Bot arrived to target location. ${bot.entity.position}`); });
bot.on("death", () => { logger.warn(`Bot has been died and was respawned at ${bot.entity.position}`); });
if (config.utils && config.utils["auto-reconnect"]) { bot.on("end", () => { bot.on("end", () => { logger.warn("Bağlantı koptu. Tüm zamanlayıcılar sıfırlanıyor..."); stopPeriodicHomeChecks(); if (config.utils && config.utils["auto-reconnect"]) { setTimeout(() => createBot(), config.utils["auto-reconnect-delay"]); }); }
bot.on("kicked", (reason) => { let reasonText = ""; try { const parsed = JSON.parse(reason); reasonText = parsed.text || parsed.extra?.[0]?.text || ""; reasonText = reasonText?.replace(/§./g, ""); logger.warn(`Bot sunucudan atıldı. Sebep: ${reasonText}`); } catch { logger.warn(`Bot sunucudan atıldı. Sebep: Bulunamadı.`); } });
bot.on("error", (err) => logger.error(`${err && err.message ? err.message : err}`));
// process message dump helper process.on("message", (msg) => { try { if (!msg) return; if (msg.type === "dumpEntityById" && msg.id) { const ent = Object.values(bot.entities).find(e => e && e.id === msg.id); if (ent) console.log(util.inspect(ent, { depth: 1 })); } } catch (e) {} });
// --- Periyodik kontrol başlatma/durdurma --- let periodicHandle = null; function startPeriodicHomeChecks() { if (periodicHandle) return; periodicHandle = setInterval(() => { (async () => { try { // Eğer son tam beslemeden (veya can 10 görüldüğünden) henüz FULL_FEED_COOLDOWN_MS geçmediyse atla if (Date.now() < (lastFullFeedAt + FULL_FEED_COOLDOWN_MS)) { return; } await goHome(); await new Promise(r => setTimeout(r, HOME_ARRIVAL_DELAY_MS)); await scanAndFeed(); await returnIsland(); } catch (e) {} })(); }, PERIODIC_CHECK_INTERVAL_MS); }
function stopPeriodicHomeChecks() { if (!periodicHandle) return; clearInterval(periodicHandle); periodicHandle = null; }
// circleWalk fonksiyonu (orijinal) function circleWalk(botRef, radius) { return new Promise(() => { const pos = botRef.entity.position; const x = pos.x; const y = pos.y; const z = pos.z;
const points = [ [x + radius, y, z], [x, y, z + radius], [x - radius, y, z], [x, y, z - radius], ];
let i = 0; setTimeout(() => { if (i === points.length) i = 0; const defaultMove = new Movements(botRef); botRef.pathfinder.setMovements(defaultMove); botRef.pathfinder.setGoal(new GoalXZ(points[i][0], points[i][2])); i++; }, 1000); }); }
// startPeriodicHomeChecks çağrısı spawn içinde veya auto-auth sonrası yapılıyor // createBot fonksiyonu sonu bot.on("kicked", (reason) => logger.warn(`Bot sunucudan atıldı: ${util.inspect(reason)}`)); bot.on("error", (err) => logger.error(`${err}`));}
// create bot ve küçük web pingcreateBot();
const express = require("express");const app = express();const port = process.env.PORT || 7860;app.get("/", (req, res) => res.send("Pinglendi"));app.listen(port, () => logger.info(`Bot bu adres üzerinde çalışıyor: http://localhost:${port}`));
process.on("uncaughtException", function (err) { logger.error("Hata aldım!"); logger.error(err && err.stack ? err.stack : err);});app.get("/", (req, res) => res.send("Bot Aktif"));app.listen(process.env.PORT || 7860);bot.js+133-694