From f8acfa684e12fdc6e53bfbe3902d0bda18630cfc Mon Sep 17 00:00:00 2001 From: ZareMate <0.zaremate@gmail.com> Date: Wed, 1 Apr 2026 18:43:54 +0200 Subject: [PATCH] feat: implement AFK retry mechanism with teleport detection and logging --- afk.js | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/afk.js b/afk.js index ba8c3e1..061d5f2 100644 --- a/afk.js +++ b/afk.js @@ -31,6 +31,12 @@ const LOG_FILE = path.join( `afk-${toSafeFilePart(runtimeUsername)}.log`, ); const TELEPORT_DETECT_REGEX = /you teleported to\b/i; +const AFK_RETRY_DELAY_MS = 5000; +const AFK_MIN_NUMBER = 1; +const AFK_MAX_NUMBER = 50; + +let hasDetectedTeleport = false; +let afkRetryTimer = null; // Logging function log(message) { @@ -40,6 +46,35 @@ function log(message) { fs.appendFileSync(LOG_FILE, logMessage + "\n"); } +function getRandomIntInclusive(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; +} + +function clearAfkRetryTimer() { + if (afkRetryTimer) { + clearTimeout(afkRetryTimer); + afkRetryTimer = null; + } +} + +function scheduleAfkRetryCheck() { + clearAfkRetryTimer(); + + afkRetryTimer = setTimeout(() => { + if (hasDetectedTeleport) return; + + const randomNumber = getRandomIntInclusive(AFK_MIN_NUMBER, AFK_MAX_NUMBER); + const command = `/afk ${randomNumber}`; + log( + `No teleport detected after ${AFK_RETRY_DELAY_MS}ms; sending: ${command}`, + ); + bot.chat(command); + + // Keep checking every delay window until teleport is detected. + scheduleAfkRetryCheck(); + }, AFK_RETRY_DELAY_MS); +} + function toPlainText(value) { if (value == null) return ""; if (typeof value === "string") return value; @@ -73,6 +108,12 @@ function logIfTeleport(source, text) { if (!normalized) return; if (!TELEPORT_DETECT_REGEX.test(normalized)) return; log(`Teleport detected from ${source}: ${normalized}`); + + if (!hasDetectedTeleport) { + hasDetectedTeleport = true; + clearAfkRetryTimer(); + log("Teleport confirmed; stopped AFK retry loop"); + } } // Create bot @@ -91,6 +132,8 @@ bot.on("login", () => { bot.on("spawn", () => { log("Bot spawned"); + hasDetectedTeleport = false; + scheduleAfkRetryCheck(); }); bot.on("error", (err) => { @@ -102,6 +145,7 @@ bot.on("kicked", (reason) => { }); bot.on("end", () => { + clearAfkRetryTimer(); log("Bot disconnected"); process.exit(0); }); @@ -159,6 +203,7 @@ bot._client.on("set_subtitle_text", (packet) => { // Graceful shutdown process.on("SIGINT", () => { log("Shutdown signal received"); + clearAfkRetryTimer(); bot.quit(); });