PrismarineJS / mineflayer

Create Minecraft bots with a powerful, stable, and high level JavaScript API.
https://prismarinejs.github.io/mineflayer/
MIT License
4.75k stars 871 forks source link

Protocol Error #3374

Open overtimepog opened 1 month ago

overtimepog commented 1 month ago

the bot keeps getting kicked like 5 seconds after it spawns, all I get is this, Idk what It means

Bot is starting...
Mineflayer detected that you are using a deprecated event (physicTick)! Please use this event (physicsTick) instead.
Bot has logged in!
ChatMessage {
  json: { color: 'yellow', text: 'OvertimesBot joined the game' },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: 'OvertimesBot joined the game',
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: 'yellow'
}
ChatMessage {
  json: { extra: [ [Object], [Object] ], text: '' },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '                                                                       ',
      bold: false,
      italic: false,
      underlined: false,
      strikethrough: true,
      obfuscated: false,
      color: '#00FFF7'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: false,
      obfuscated: undefined,
      color: undefined
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
ChatMessage {
  json: {
    extra: [ [Object], [Object], [Object], [Object], [Object] ],
    text: ''
  },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'Welcome to ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'green'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'SMP',
      bold: true,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'white'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'Online ',
      bold: true,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'green'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'Season 4',
      bold: false,
      italic: false,
      underlined: false,
      strikethrough: false,
      obfuscated: false,
      color: '#FF6A00'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '!',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'green'
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
ChatMessage {
  json: { extra: [ [Object], [Object] ], text: '' },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '                                                                       ',
      bold: false,
      italic: false,
      underlined: false,
      strikethrough: true,
      obfuscated: false,
      color: '#0080FF'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: false,
      obfuscated: undefined,
      color: undefined
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
ChatMessage {
  json: {
    extra: [ [Object], [Object], [Object], [Object], [Object] ],
    text: ''
  },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'Be sure to ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'yellow'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'read ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'aqua'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'all of the ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'yellow'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'signs at spawn',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'aqua'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '! Our server has a',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'yellow'
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
ChatMessage {
  json: { extra: [ [Object] ], text: '' },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'few notable differences and tweaks from vanilla survival.',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'yellow'
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
ChatMessage {
  json: { extra: [ [Object], [Object], [Object] ], text: '' },
  warn: [Function: debug] {
    namespace: 'minecraft-protocol',
    useColors: true,
    color: 3,
    extend: [Function: extend],
    destroy: [Function: deprecated],
    enabled: [Getter/Setter],
    inspectOpts: {}
  },
  text: '',
  extra: [
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'Read the ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'red'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: '/rules ',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'gray'
    },
    ChatMessage {
      json: [Object],
      warn: [Function],
      text: 'or risk the ban!',
      bold: undefined,
      italic: false,
      underlined: undefined,
      strikethrough: undefined,
      obfuscated: undefined,
      color: 'red'
    }
  ],
  bold: undefined,
  italic: undefined,
  underlined: undefined,
  strikethrough: undefined,
  obfuscated: undefined,
  color: undefined
}
Bot has spawned!
Prismarine viewer web server running on *:3007
{"color":"red","extra":[{"text":"You were kicked from "},{"text":"subserver"},{"text":": "},{"text":"Protocol Error"}],"text":""} true

this is my code, any help in fixing this would be nice

const mineflayer = require('mineflayer');
const { Block } = require('prismarine-block');
const { mineflayer: mineflayerViewer } = require('prismarine-viewer');
const pathfinder = require('mineflayer-pathfinder').pathfinder;
const Movements = require('mineflayer-pathfinder').Movements;
const { GoalNear, GoalBlock } = require('mineflayer-pathfinder').goals;
const blockFinderPlugin = require('mineflayer-blockfinder')(mineflayer);
const collectBlock = require('mineflayer-collectblock').plugin;
const { Vec3 } = require('vec3');
const minecraftData = require('minecraft-data');
const pvp = require('mineflayer-pvp').plugin;

const locations = {
  NewSpawnTown: { x: 16287, y: 78, z: 3995 },
  // Add more locations as needed
};

const bot = mineflayer.createBot({
  host: 'play.callmecarson.live',
  auth: 'microsoft',
  version: '1.20.2',
});

const mcData = require('minecraft-data')(bot.version);

console.log("Bot is starting...");

bot.on('login', () => {
  console.log("Bot has logged in!");
});

bot._client.on('resource_pack_send', (data) => {
  bot._client.write('resource_pack_receive', { hash: "Resourcepack", result: 3 });
  bot._client.write('resource_pack_receive', { hash: "Resourcepack", result: 0 });
});

bot.on('message', (jsonMsg) => {
  console.log(jsonMsg);
});

bot.loadPlugin(pathfinder);
bot.loadPlugin(blockFinderPlugin);
bot.loadPlugin(collectBlock)
bot.loadPlugin(pvp);

let isSpleefing = false;

function playSpleef() {
  const mcData = minecraftData(bot.version);

  // Configure the bot's PVP behavior

  // Set up the bot's pathfinding
  const defaultMove = new Movements(bot, mcData);
  bot.pathfinder.setMovements(defaultMove);

  // Function to check if the player is standing on snow
  function isStandingOnSnow(playerPosition) {
    const blockBeneath = bot.blockAt(playerPosition.offset(0, -1, 0));
    return blockBeneath && blockBeneath.name === 'snow_block';
  }

  // Function to find the nearest player standing on snow
  function findNearestPlayer() {
    const players = Object.values(bot.players).filter(p => p.entity && p.entity.position);
    let nearestPlayer = null;
    let nearestDistance = Infinity;

    for (const player of players) {
      if (!bot.entity.position || !isStandingOnSnow(player.entity.position)) {
        continue;  // Skip if the bot's position or the player's position is not available, or the player is not standing on snow
      }
      const distance = player.entity.position.distanceTo(bot.entity.position);
      if (distance < nearestDistance) {
        nearestPlayer = player;
        nearestDistance = distance;
      }
    }

    return nearestPlayer;  // Return the nearest player found, or null if no valid player was found
  }

  // Function to determine the bot's strategy based on the game state
  function determineStrategy() {
    const numTeammates = Object.values(bot.players).filter(p => p.team === bot.team).length;
    const numOpponents = Object.values(bot.players).filter(p => p.team !== bot.team).length;

    if (numTeammates > numOpponents) {
      return 'attack'; // Attack strategy: Pursue and spleef opponents aggressively
    } else if (numTeammates < numOpponents) {
      return 'evasion'; // Evasion strategy: Run and avoid attacks, focus on survival
    } else {
      return 'balanced'; // Balanced strategy: Mix of attacking and defending
    }
  }

  // Main loop for playing spleef
  function startSpleef() {
    if (!isSpleefing) return;

    const player = findNearestPlayer();
    const strategy = determineStrategy();

    if (player) {
      if (strategy === 'attack' || (strategy === 'balanced' && bot.entity.position.distanceTo(player.entity.position) < 5)) {
        // Define the goal near the player
        const goal = new GoalNear(player.entity.position.x, player.entity.position.y, player.entity.position.z, 2);
        bot.pathfinder.setGoal(goal);
        bot.pathfinder.goto(goal);

        // Attempt to equip the netherite shovel and dig the block below the player
        const shovelItem = bot.inventory.items().find(item => item.name === 'netherite_shovel');
        if (!shovelItem) {
          console.log('No netherite shovel found in inventory.');
          return;  // Exit the function or choose an alternative action
        }

        bot.equip(shovelItem, 'hand', (err) => {
          if (err) {
            console.log(`Error equipping netherite shovel:`, err);
            return;
          }
          const blockBelow = bot.blockAt(player.entity.position.offset(0, -1, 0));
          if (blockBelow) {
            bot.dig(blockBelow, (err) => {
              if (err) {
                console.log('Error digging block:', err);
              }
            });
          }
        });
      } else if (strategy === 'evasion') {
        // Run away from opponents and focus on survival
        const escapeDirection = bot.entity.position.minus(player.entity.position).normalize();
        const escapeGoal = new GoalNear(
          bot.entity.position.x + escapeDirection.x * 10,
          bot.entity.position.y,
          bot.entity.position.z + escapeDirection.z * 10
        );
        bot.pathfinder.setGoal(escapeGoal);
        bot.pathfinder.goto(escapeGoal);
      } else {
        // Balanced strategy when far from the opponent...
        const defendDirection = bot.entity.position.minus(player.entity.position).normalize();
        const defendGoal = new GoalNear(
          bot.entity.position.x + defendDirection.x * 5,
          bot.entity.position.y,
          bot.entity.position.z + defendDirection.z * 5,
          1
        );
        bot.pathfinder.setGoal(defendGoal);
        bot.pathfinder.goto(defendGoal);
      }
    }

    // Schedule the next spleef iteration
    setTimeout(startSpleef, 500); // Adjust the delay as needed
  }  
  // Start playing spleef
  isSpleefing = true;
  startSpleef();
}

//look at a player
function lookAtPlayer(player) {
  const pos = player.entity.position.offset(0, player.entity.height, 0);
  bot.lookAt(pos, true)
}

// Define global variables for storing bot stats
let botHealth = 0;
let botHunger = 0;

// Update bot stats
function updateBotStats() {
  botHealth = bot.health;
  botHunger = bot.food;
}

// Command handler for displaying bot stats
function showBotStats(username) {
  bot.whisper(username, `Bot Stats:
  Health: ${botHealth}
  Hunger: ${botHunger}`);
}

// Add a listener for when the bot's health changes
bot.on('health', () => {
  updateBotStats();
});

let followingPlayer = null;
let followGoal = null;

function updateFollowGoal() {
  if (followingPlayer) {
    const player = bot.players[followingPlayer];
    if (player && player.entity) {
      // Calculate the distance to the player
      const distance = bot.entity.position.distanceTo(player.entity.position);
      const visibleDistance = 100; // Set a distance threshold for following

      if (distance <= visibleDistance) {
        const newPosition = new Vec3(player.entity.position.x, player.entity.position.y, player.entity.position.z);

        // Check if there is already a goal and if it is the same as the new position
        if (bot.pathfinder.goal && bot.pathfinder.goal.isEnd(newPosition)) {
          return; // If the current goal is the same, do not update it
        }

        const mcData = require('minecraft-data')(bot.version);
        const movements = new Movements(bot, mcData);
        movements.scaffoldingBlocks = [];
        movements.canDig = false;
        bot.pathfinder.setMovements(movements);

        const goal = new GoalNear(newPosition.x, newPosition.y, newPosition.z, 1);
        followGoal = goal;
        bot.pathfinder.setGoal(goal, true);
      }
    }
  }
}

function findAndSit() {
  const blockTypes = ['wooden_slab', 'brick_slab', 'stone_brick_slab', 'nether_brick_slab', 'quartz_slab', 'stone_slab', 'sandstone_slab', 'purpur_slab',
                      'wooden_stairs', 'brick_stairs', 'stone_brick_stairs', 'nether_brick_stairs', 'quartz_stairs', 'stone_stairs', 'sandstone_stairs', 'purpur_stairs'];
  const blockIDs = blockTypes.map(type => bot.registry.blocksByName[type]?.id).filter(id => id !== undefined);

  const startTime = performance.now();
  bot.findBlock({
    point: bot.entity.position,
    matching: blockIDs,
    maxDistance: 128,
    count: 10,
  }, (err, blocks) => {
    if (err) {
      console.log('Error finding blocks:', err);
      return;
    }
    const time = (performance.now() - startTime).toFixed(2);
    if (blocks.length > 0) {
      const block = blocks[0];
      const mcData = require('minecraft-data')(bot.version);
      const movements = new Movements(bot, mcData);
      movements.canDig = false;
      movements.allowSprinting = false;
      movements.scaffoldingBlocks = [];
      bot.pathfinder.setMovements(movements);
      const goal = new GoalBlock(block.position.x, block.position.y + 1, block.position.z);
      bot.pathfinder.setGoal(goal, true);
      bot.pathfinder.goto(goal);

      bot.on('goal_reached', () => {
        //make sure its an empty hand
        //remove the item from main hand
        bot.unequip("hand");
        bot.activateBlock(block);
      });
    } else {
      bot.whisper("overtimepog", `No blocks found in ${time} ms.`);
    }
  });
}

// Global variable to track the Sumo game state
let isPlayingSumo = false;
const SumoMovements = new Movements(bot, mcData);
SumoMovements.canDig = false;
SumoMovements.allowSprinting = true;
SumoMovements.scaffoldingBlocks = [];

// Function to start playing Sumo and continuously attempt to hit the opponent
function playSumo() {
  bot.pathfinder.setMovements(SumoMovements);
    if (!isPlayingSumo) return;

    const opponents = Object.values(bot.players).filter(p => p.username !== bot.username && p.entity);
    const nearestOpponent = opponents.reduce((nearest, opponent) => {
        if (!nearest || bot.entity.position.distanceTo(opponent.entity.position) < bot.entity.position.distanceTo(nearest.entity.position)) {
            return opponent;
        }
        return nearest;
    }, null);

    if (nearestOpponent) {
        const opponentPos = nearestOpponent.entity.position;
        const distanceToOpponent = bot.entity.position.distanceTo(opponentPos);

        // Ensure we're close enough to hit the opponent
        if (distanceToOpponent > 3) {
            // Move closer to the opponent
            const moveToOpponentGoal = new GoalNear(opponentPos.x, opponentPos.y, opponentPos.z, 2);

            bot.pathfinder.setGoal(moveToOpponentGoal, true);
            bot.pathfinder.goto(moveToOpponentGoal);
        } else {
            // Stop moving and swing at the opponent
            bot.pathfinder.setGoal(null);
            bot.lookAt(opponentPos.offset(0, nearestOpponent.entity.height, 0), true, () => {
                bot.attack(nearestOpponent.entity);
            });
        }

        // Check if the opponent has fallen
        if (opponentPos.y <= bot.entity.position.y - 2) {
            console.log(`${nearestOpponent.username} has fallen off!`);
            isPlayingSumo = false; // Stop the game if opponent has fallen
            bot.pathfinder.setGoal(null); // Clear the current goal
            console.log('Sumo minigame stopped.');
        }
    } else {
        console.log('No opponents found nearby.');
    }
}

function checkAndEatFood() {
  const hungerThreshold = 16;  // Minecraft uses 20 scale, 16 means eat when 4 or less hunger shanks are full

  if (bot.food <= hungerThreshold) {
    const food = findFoodInInventory();
    if (food) {
      bot.equip(food, 'hand').then(() => {
        bot.activateItem();
      }).catch(console.error);
    }
  }
}

function stopSpleef() {
  if (!isSpleefing) {
    console.log('Spleef is not currently running.');
    return;
  }
  isSpleefing = false;
  bot.pathfinder.setGoal(null);
  clearTimeout(spleefTimeout);
  console.log('Spleef stopped.');
}

function findFoodInInventory() {
  const foodItems = ['apple', 'bread', 'cooked_porkchop', 'baked_potato']; // List all the food items you want the bot to consider
  return bot.inventory.items().find(item => foodItems.includes(item.name));
}

async function bringItemToPlayer(itemName, quantity, playerName) {
  if (playerName === "me") {
      playerName = "overtimepog";  // Assuming 'overtimepog' is your username.
  }

  const player = bot.players[playerName];
  if (!player) {
      bot.whisper("overtimepog", `Player '${playerName}' not found.`);
      return;
  }

  bot.whisper("overtimepog", `Attempting to bring ${quantity} of ${itemName} to ${playerName}.`);

  if (!mcData.blocksByName[itemName]) {
      bot.whisper("overtimepog", `Item '${itemName}' not found.`);
      return;
  }

  const blocks = await bot.findBlocks({
      matching: mcData.blocksByName[itemName].id,
      maxDistance: 64,
      count: quantity
  });

  if (blocks.length < quantity) {
      bot.whisper("overtimepog", `Not enough blocks of '${itemName}' found nearby. Only found ${blocks.length}.`);
      return;
  }

  bot.whisper("overtimepog", `Found ${blocks.length} blocks. Beginning to collect.`);

  const movements = new Movements(bot, mcData);
  movements.allowSprinting = false;
  movements.canDig = true;
  bot.pathfinder.setMovements(movements);

  for (let i = 0; i < blocks.length; i++) {
      const blockPos = blocks[i];
      if (!await moveToAndCollectBlock(new Vec3(blockPos.x, blockPos.y, blockPos.z))) {
          bot.whisper("overtimepog", `Failed to collect block at (${blockPos.x}, ${blockPos.y}, ${blockPos.z}). Stopping collection.`);
          break;
      }
  }
}

async function moveToAndCollectBlock(blockPos) {
  return new Promise((resolve, reject) => {
      const goal = new GoalNear(blockPos.x, blockPos.y, blockPos.z, 1);
      bot.pathfinder.setGoal(goal, true);

      const listener = () => {
          bot.removeListener('goal_reached', listener);  // Remove the listener to clean up
          bot.collectBlock.collect(blockPos, (err) => {
              if (err) {
                  bot.whisper("overtimepog", `Error collecting item: ${err.message}`);
                  reject(false);  // false indicates failure
              } else {
                  bot.whisper("overtimepog", `Successfully collected item from (${blockPos.x}, ${blockPos.y}, ${blockPos.z}).`);
                  resolve(true);  // true indicates success
              }
          });
      };

      bot.once('goal_reached', listener);
  });
}

function lookForBoats() {
  const nearestBoat = bot.nearestEntity(entity => ['boat', 'oak_boat', 'spruce_boat', 'birch_boat', 'jungle_boat', 'acacia_boat', 'dark_oak_boat'].includes(entity.name));

  if (!nearestBoat) {
    bot.whisper("overtimepog", "No boats found nearby.");
    return;
  }

  // Check if "overtimepog" is near the boat
  let overtimepogNearby = false;
  for (const playerName in bot.players) {
    const player = bot.players[playerName];
    if (player.entity && player.entity.position.distanceTo(nearestBoat.position) <= 3) {
      overtimepogNearby = true;
      break; // Exit loop early if found
    }
  }

  if (overtimepogNearby) {
    const mcData = require('minecraft-data')(bot.version);
    const movements = new Movements(bot, mcData);
    movements.canDig = false;
    movements.allowSprinting = false;
    movements.scaffoldingBlocks = [];
    bot.pathfinder.setMovements(movements);
    const goal = new GoalNear(nearestBoat.position.x, nearestBoat.position.y, nearestBoat.position.z, 2);
    bot.pathfinder.setGoal(goal, true);
    bot.pathfinder.goto(goal);
    bot.whisper("overtimepog", "Heading towards the nearest boat...");
    bot.once('goal_reached', () => {
      bot.whisper("overtimepog", "Reached the nearest boat.");
      bot.activateEntity(nearestBoat);
      bot.activateBlock(nearestBoat);
    });
  } else {
    bot.whisper("overtimepog", "No boats with 'overtimepog' nearby.");
  }
}

let lastBoatGiveTime = 0;
const boatGiveInterval = 5000; // 5000 milliseconds or 5 seconds between giving boats

function giveBoatsToPlayer(username) {
  const player = bot.players[username];
  if (!player || !player.entity) {
      //console.log(`Player ${username} not found or not loaded.`);
      return;
  }

  const boatTypes = ['oak_boat', 'spruce_boat', 'birch_boat', 'jungle_boat', 'acacia_boat', 'dark_oak_boat'];
  const boats = bot.inventory.items().filter(item => boatTypes.includes(item.name));

  if (boats.length === 0) {
      //console.log(`I have no boats to give to ${username}.`);
      return;
  }

  const targetPosition = player.entity.position;
  if (bot.entity.position.distanceTo(targetPosition) > 5) {
      //console.log(`Player ${username} is too far away to give boats.`);
      return;
  }

  for (const boat of boats) {
      bot.tossStack(boat, err => {
          if (err) {
              console.log(`Error giving boat to ${username}: ${err.message}`);
          } else {
              console.log(`Gave a ${boat.name} to ${username}.`);
          }
      });
  }
}

let sumoInterval; // Holds the reference to the interval for managing lifecycle

function startSumoGame() {
    if (!isPlayingSumo) {
        isPlayingSumo = true;
        // Start the interval only if it hasn't been started before
        if (!sumoInterval) {
            sumoInterval = setInterval(playSumo, 100);
        }
    }
}

function stopSumoGame() {
    if (isPlayingSumo) {
        isPlayingSumo = false;
        if (sumoInterval) {
            clearInterval(sumoInterval); // Clear the interval when the game stops
            sumoInterval = null; // Reset the interval variable
        }
    }
}

bot.on('physicsTick', () => {
  const currentTime = Date.now();
    if (currentTime - lastBoatGiveTime > boatGiveInterval) {
        lastBoatGiveTime = currentTime;
        giveBoatsToPlayer('overtimepog'); // Replace 'overtimepog' with your username
    }
  updateFollowGoal();
  checkAndEatFood();
});

bot.on('whisper', (username, message) => {
  if (username === bot.username) return;

  if (message === "hi" && username === "overtimepog") {
    bot.chat("Hello!");

  } else if (message.startsWith('follow') && username === "overtimepog") {
    const targetPlayer = message.split(' ')[1];
    if (targetPlayer === "me") {
      followingPlayer = "overtimepog";
    } else {
      followingPlayer = targetPlayer;
    }

    if (targetPlayer === '') {
      bot.whisper(username, "Player not found.");
      return;
    }
    bot.whisper(followingPlayer, `Following ${followingPlayer}, type "stop" to stop following`);

  } else if (message === "stop" && (username === "overtimepog" || username === followingPlayer)) {
    followingPlayer = null;
    followGoal = null;
    bot.pathfinder.setGoal(null);
    if (isSpleefing) {
      stopSpleef(); // Ensure this stops the spleef game if it is running
    }
    isPlayingSumo = false;
    stopSumoGame();
    bot.whisper(username, "Stopped.");

  } else if (message.startsWith('find') && message.split(' ').length === 2 && username === "overtimepog") {
    const name = message.split(' ')[1];
    if (bot.registry.blocksByName[name] === undefined) {
      bot.whisper(username, `${name} is not a block name`);
      return;
    }
    const ids = [bot.registry.blocksByName[name].id];

    const startTime = performance.now();
    const blocks = bot.findBlocks({ matching: ids, maxDistance: 128, count: 10 });
    const time = (performance.now() - startTime).toFixed(2);

    const validBlocks = blocks.filter(block => block.position && block.position.x !== undefined && block.position.y !== undefined && block.position.z !== undefined);

    if (validBlocks.length > 0) {
      const coords = validBlocks.map(block => `(${block.position.x}, ${block.position.y}, ${block.position.z})`).join(', ');
      bot.whisper(username, `I found ${validBlocks.length} ${name} blocks in ${time} ms at coordinates: ${coords}`);
    } else {
      bot.whisper(username, `No ${name} blocks found within the search radius or with complete coordinates.`);
    }

  } else if (message === "sit" && username === "overtimepog") {
    findAndSit();
    bot.whisper(username, "Sitting down.")
  }

  else if (message === ("up" || "get up") && username === "overtimepog") {
    bot.dismount();
  } 
  else if (message.startsWith("look at ") && username === "overtimepog") {
    const targetPlayerName = message.substring("look at ".length); // Extract the player's name from the message
    if (!targetPlayerName) {
      bot.whisper(username, "Please specify a player name.");
      return;
    }
    if (targetPlayerName === bot.username) {
      bot.whisper(username, "I'm already looking at myself.");
      return;
    }
    if (targetPlayerName === "me") {
      lookAtPlayer(bot.players[username]);
      bot.whisper(username, "Looking at you.");
      return;
    }
    const targetPlayer = bot.players[targetPlayerName];
    if (targetPlayer) {
      lookAtPlayer(targetPlayer);
      bot.whisper(username, `Looking at ${targetPlayerName}.`);
    } else {
      bot.whisper(username, `Player '${targetPlayerName}' not found.`);
    }
  }
  else if (message.startsWith('bring') && username === "overtimepog") {
    const parts = message.split(' ');
    if (parts.length !== 4) {
      bot.whisper(username, "Invalid format. Usage: bring <player> <quantity> <item>");
      return;
    }
    const targetPlayer = parts[1];
    const quantity = parseInt(parts[2]);
    if (isNaN(quantity) || quantity <= 0) {
      bot.whisper(username, "Invalid quantity. Please specify a positive integer.");
      return;
    }
    const itemName = parts[3];
    bringItemToPlayer(itemName, quantity, targetPlayer);
  }
  else if (message === 'stats' && username === "overtimepog") {
    showBotStats(username);
  }
  else if (message === 'eat' && username === "overtimepog") {
    checkAndEatFood();
  }
  else if (message === 'boat' && username === "overtimepog") {
    if (followingPlayer !== null) {
      followingPlayer = null;
      followGoal = null;
      isPlayingSumo = false;
      bot.pathfinder.setGoal(null);
    }
    lookForBoats();
  }
  else if (message === 'spleef' && username === "overtimepog") {
    followingPlayer = null;
    followGoal = null;
    isPlayingSumo = false;
    playSpleef();
  }
  else if (message === 'join minigame' && username === "overtimepog") {
    bot.chat("/mini join")
  }
  else if (message.startsWith('say ') && username === "overtimepog") {
    const toSay = message.slice(4);  // Removes the 'say ' part of the message
    bot.chat(toSay);
  }
  if (message === 'start sumo') {
    isPlayingSumo = true;
    console.log('Starting Sumo minigame.');
    startSumoGame(); // Start the Sumo strategy
  }
});

//bot.on('entitySleep', () => {
//  bot.chat("gn :))");
//});

bot.once('spawn', () => {
  console.log("Bot has spawned!");
  mineflayerViewer(bot, { port: 3007, firstPerson: true });
});

// Log errors and kick reasons:
bot.on('kicked', console.log);
bot.on('error', console.log);
extremeheat commented 1 month ago

Can you please provide a more concise piece of code that can replicate the error?

There is too much code here to determine what exactly is wrong with it without running and debugging it.