feat: implement AFK retry mechanism with teleport detection and logging

This commit is contained in:
ZareMate 2026-04-01 18:43:54 +02:00
parent ad7ee541c5
commit f8acfa684e

45
afk.js
View File

@ -31,6 +31,12 @@ const LOG_FILE = path.join(
`afk-${toSafeFilePart(runtimeUsername)}.log`, `afk-${toSafeFilePart(runtimeUsername)}.log`,
); );
const TELEPORT_DETECT_REGEX = /you teleported to\b/i; 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 // Logging
function log(message) { function log(message) {
@ -40,6 +46,35 @@ function log(message) {
fs.appendFileSync(LOG_FILE, logMessage + "\n"); 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) { function toPlainText(value) {
if (value == null) return ""; if (value == null) return "";
if (typeof value === "string") return value; if (typeof value === "string") return value;
@ -73,6 +108,12 @@ function logIfTeleport(source, text) {
if (!normalized) return; if (!normalized) return;
if (!TELEPORT_DETECT_REGEX.test(normalized)) return; if (!TELEPORT_DETECT_REGEX.test(normalized)) return;
log(`Teleport detected from ${source}: ${normalized}`); log(`Teleport detected from ${source}: ${normalized}`);
if (!hasDetectedTeleport) {
hasDetectedTeleport = true;
clearAfkRetryTimer();
log("Teleport confirmed; stopped AFK retry loop");
}
} }
// Create bot // Create bot
@ -91,6 +132,8 @@ bot.on("login", () => {
bot.on("spawn", () => { bot.on("spawn", () => {
log("Bot spawned"); log("Bot spawned");
hasDetectedTeleport = false;
scheduleAfkRetryCheck();
}); });
bot.on("error", (err) => { bot.on("error", (err) => {
@ -102,6 +145,7 @@ bot.on("kicked", (reason) => {
}); });
bot.on("end", () => { bot.on("end", () => {
clearAfkRetryTimer();
log("Bot disconnected"); log("Bot disconnected");
process.exit(0); process.exit(0);
}); });
@ -159,6 +203,7 @@ bot._client.on("set_subtitle_text", (packet) => {
// Graceful shutdown // Graceful shutdown
process.on("SIGINT", () => { process.on("SIGINT", () => {
log("Shutdown signal received"); log("Shutdown signal received");
clearAfkRetryTimer();
bot.quit(); bot.quit();
}); });