feat: implement AFK retry mechanism with teleport detection and logging
This commit is contained in:
parent
ad7ee541c5
commit
f8acfa684e
45
afk.js
45
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();
|
||||
});
|
||||
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user