Search code examples
javascriptbotsminecraftmineflayer

mineflayer bot crashes with 'digging aborted'


Error my problem is that the bot gets killed by a zombie or just any mob it just gives digging aborted and leaves the server here is my code :

const mineflayer = require('mineflayer');
const fs = require('fs');
const path = require('path');
const keep_alive = require('./keep_alive.js');

function readConfig() {
  const configPath = path.resolve(__dirname, 'config.json');
  try {
    const rawdata = fs.readFileSync(configPath);
    const config = JSON.parse(rawdata);
    if (!config.ip || !config.port || !Array.isArray(config.names) || config.names.length === 0) {
      throw new Error('Invalid config format.');
    }
    return config;
  } catch (error) {
    console.error('Error reading config.json:', error);
    return null;
  }
}

const config = readConfig();
if (!config) {
  console.error('No valid config found, exiting.');
  process.exit(1);
}

const { ip: host, port, names } = config;
const moveInterval = 20 * 1000;
const actions = ['forward', 'back', 'left', 'right'];
const chatInterval = 10 * 60 * 1000;
const miningInterval = 60 * 1000;
const randomMessages = [
  "Just finished building my house!",
  "Anyone up for a mining trip?",
  "Need help with anything?",
  "Check out my new farm!",
  "Found some diamonds today!",
  "Anyone want to trade?",
  "Just exploring the area.",
  "Looking for a village.",
  "Time to gather some resources.",
  "Building a new project, wish me luck!",
  "Anyone seen any cool caves nearby?",
  "Avoiding creepers like a pro.",
  "What's everyone working on today?",
  "Need some food, anyone got extra?",
  "Found a great spot to build!",
];

let bot;
let moveIntervalId, chatIntervalId, miningIntervalId;

function createBot() {
  bot = mineflayer.createBot({
    host,
    port,
    username: getRandomName(),
  });

  bot.on('login', onLogin);
  bot.on('spawn', onSpawn);
  bot.on('death', onDeath);
  bot.on('kicked', onKicked);
  bot.on('end', onEnd);
  bot.on('error', onError);
}

function onLogin() {
  console.log(`Logged in as ${bot.username}`);
  startMoving();
  scheduleChatMessages();
  startMining();
}

function onSpawn() {
  console.log("Spawned");
}

function onDeath() {
  console.log("Died, respawning...");
  bot.emit("respawn");
}

function onKicked(reason) {
  console.log(`Kicked from the server: ${reason}`);
  setTimeout(reconnect, 5000);
}

function onEnd() {
  console.log("Disconnected");
  reconnect();
}

function onError(err) {
  console.error(`Error occurred: ${err}`);
  reconnect();
}

function getRandomAction() {
  return actions[Math.floor(Math.random() * actions.length)];
}

function getRandomMessage() {
  return randomMessages[Math.floor(Math.random() * randomMessages.length)];
}

function getRandomName() {
  return names[Math.floor(Math.random() * names.length)];
}

function startMoving() {
  moveIntervalId = setInterval(() => {
    const action = getRandomAction();
    bot.setControlState(action, true);
    setTimeout(() => {
      bot.setControlState(action, false);
    }, 1000 + Math.random() * 2000);
  }, moveInterval);
}

function scheduleChatMessages() {
  chatIntervalId = setInterval(() => {
    const message = getRandomMessage();
    bot.chat(message);
    console.log(`Sent message: ${message}`);
  }, chatInterval);
}

function startMining() {
  miningIntervalId = setInterval(() => {
    const targetBlock = bot.findBlock({
      matching: block => block.name === 'stone' || block.name === 'cobblestone' || block.name.endsWith('_log') || block.name.endsWith('_wood'),
      maxDistance: 32,
    });

    if (targetBlock) {
      bot.dig(targetBlock, (err) => {
        if (err) {
          console.error(`Failed to mine: ${err.message}`);
        } else {
          console.log(`Successfully mined ${targetBlock.name}`);
        }
      });
    } else {
      console.log('No suitable block found to mine.');
    }
  }, miningInterval);
}

function reconnect() {
  cleanupIntervals();
  console.log("Reconnecting...");
  setTimeout(createBot, 1000);
}

function cleanupIntervals() {
  clearInterval(moveIntervalId);
  clearInterval(chatIntervalId);
  clearInterval(miningIntervalId);
}

createBot();

as you can see it just got killed by a zombie then it just disconnected and i dont know why! i have been trying to fix it for days, like i literally asked chatgpt, i know he is a mess but i didnt have any solution to this problem!

i tried writing it in different ways but nothing works


Solution

  • Here's the relevant code: mineflayer/lib/plugins/digging.js

    And here's the API.

    bot.dig(block, [forceLook = true], [digFace])

    This function returns a Promise, with void as its argument when the block is broken or you are interrupted.

    Begin digging into block with the currently equipped item. See also "diggingCompleted" and "diggingAborted" events.

    Note that once you begin digging into a block, you may not dig any other blocks until the block has been broken, or you call bot.stopDigging().

    • block - the block to start digging into
    • forceLook - (optional) if true, look at the block and start mining instantly. If false, the bot will slowly turn to the block to mine. Additionally, this can be assigned to 'ignore' to prevent the bot from moving it's head at all. Also, this can be assigned to 'raycast' to raycast from the bots head to place where the bot is looking.
    • digFace - (optional) Default is 'auto' looks at the center of the block and mines the top face. Can also be a vec3 vector of the face the bot should be looking at when digging the block. For example: vec3(0, 1, 0) when mining the top. Can also be 'raycast' raycast checks if there is a face visible by the bot and mines that face. Useful for servers with anti cheat.

    This doesn't match the way you're calling bot.dig(), where you're passing the error handler into the function.

    Read Using Promises and in particular the catch() method.

    bot.dig(targetBlock)
        .then(() => {
            console.log(`Successfully mined ${targetBlock.name}`);
        }).catch((err) => { 
            console.error(`Failed to mine: ${err.message}`); 
        });