### Basic Usage Example Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md A simple example demonstrating how to load the pathfinder plugin and use it to make the bot follow a player. ```APIDOC ## Example ```js const mineflayer = require('mineflayer') const pathfinder = require('mineflayer-pathfinder').pathfinder const Movements = require('mineflayer-pathfinder').Movements const { GoalNear } = require('mineflayer-pathfinder').goals const bot = mineflayer.createBot({ username: 'Player' }) bot.loadPlugin(pathfinder) bot.once('spawn', () => { const defaultMove = new Movements(bot) bot.on('chat', function(username, message) { if (username === bot.username) return const target = bot.players[username] ? bot.players[username].entity : null if (message === 'come') { if (!target) { bot.chat('I don\'t see you !') return } const p = target.position bot.pathfinder.setMovements(defaultMove) bot.pathfinder.setGoal(new GoalNear(p.x, p.y, p.z, 1)) } }) }) ``` ``` -------------------------------- ### PlaceBlock Example Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Provides an example of how to use the `placeBlock` functionality. This is useful for tasks that require the bot to place blocks in the world. ```javascript const { GoalPlaceBlock } = require('mineflayer-pathfinder').goals const blockToPlace = bot.findBlock({ matching: mcData.blocksByName.cobblestone.id, maxDistance: 32 }) if (!blockToPlace) { bot.chat('No cobblestone found') } else { const goal = new GoalPlaceBlock(blockToPlace.position, blockToPlace.faceVector, false) bot.pathfinder.setGoal(goal) } ``` -------------------------------- ### Installation Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Install the mineflayer-pathfinder plugin using npm. ```APIDOC ## Install ```bash npm install mineflayer-pathfinder ``` ``` -------------------------------- ### Implement a Complete Pathfinding Bot Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt A full-featured example demonstrating plugin initialization, movement configuration, and chat-based goal commands. ```javascript const mineflayer = require('mineflayer') const { pathfinder, Movements } = require('mineflayer-pathfinder') const { GoalNear, GoalBlock, GoalXZ, GoalY, GoalFollow, GoalInvert, GoalGetToBlock } = require('mineflayer-pathfinder').goals const bot = mineflayer.createBot({ host: process.argv[2] || 'localhost', port: parseInt(process.argv[3]) || 25565, username: process.argv[4] || 'PathBot' }) bot.loadPlugin(pathfinder) bot.once('spawn', () => { const defaultMove = new Movements(bot) defaultMove.canDig = true defaultMove.allowParkour = true defaultMove.allowSprinting = true bot.pathfinder.setMovements(defaultMove) bot.on('path_update', (r) => { console.log(`Path: ${r.path.length} moves, ${r.time.toFixed(0)}ms, status: ${r.status}`) }) bot.on('goal_reached', () => bot.chat('Arrived!')) bot.on('path_reset', (reason) => console.log(`Reset: ${reason}`)) bot.on('chat', async (username, message) => { if (username === bot.username) return const target = bot.players[username]?.entity const args = message.split(' ') const cmd = args[0].toLowerCase() switch (cmd) { case 'come': if (!target) return bot.chat("I can't see you!") bot.pathfinder.setGoal(new GoalNear(target.position.x, target.position.y, target.position.z, 1)) break case 'goto': if (args.length === 4) { bot.pathfinder.setGoal(new GoalBlock(+args[1], +args[2], +args[3])) } else if (args.length === 3) { bot.pathfinder.setGoal(new GoalXZ(+args[1], +args[2])) } break case 'follow': if (!target) return bot.chat("I can't see you!") bot.pathfinder.setGoal(new GoalFollow(target, 3), true) break case 'avoid': if (!target) return bot.chat("I can't see you!") bot.pathfinder.setGoal(new GoalInvert(new GoalFollow(target, 8)), true) break case 'chest': const chest = bot.findBlock({ matching: bot.registry.blocksByName.chest.id, maxDistance: 32 }) if (!chest) return bot.chat('No chest nearby') await bot.pathfinder.goto(new GoalGetToBlock(chest.position.x, chest.position.y, chest.position.z)) break case 'stop': bot.pathfinder.stop() break } }) }) bot.on('error', console.error) ``` -------------------------------- ### Install mineflayer-pathfinder Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Command to install the package via npm. ```bash npm install mineflayer-pathfinder ``` -------------------------------- ### Added Multiple Bot Example Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Includes an example demonstrating how to manage multiple bots simultaneously using the pathfinder. This is useful for coordinating several bots in a Minecraft world. ```javascript // Example code for managing multiple bots with pathfinder. ``` -------------------------------- ### Callback and Promise Examples for goto Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Illustrates two ways to use the `goto` function: with a traditional callback and with Promises. This allows developers to choose the asynchronous pattern that best suits their needs. ```javascript // Callback example bot.pathfinder.goto(new GoalNear(x, y, z, 1), () => { console.log('Reached the destination (callback)') }) // Promise example bot.pathfinder.goto(new GoalNear(x, y, z, 1)).then(() => { console.log('Reached the destination (promise)') }).catch((err) => { console.log('Pathfinding failed:', err) }) ``` -------------------------------- ### Implement basic pathfinding bot Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Example of initializing the pathfinder plugin and setting a goal to move towards a player upon receiving a chat command. ```js const mineflayer = require('mineflayer') const pathfinder = require('mineflayer-pathfinder').pathfinder const Movements = require('mineflayer-pathfinder').Movements const { GoalNear } = require('mineflayer-pathfinder').goals const bot = mineflayer.createBot({ username: 'Player' }) bot.loadPlugin(pathfinder) bot.once('spawn', () => { const defaultMove = new Movements(bot) bot.on('chat', function(username, message) { if (username === bot.username) return const target = bot.players[username] ? bot.players[username].entity : null if (message === 'come') { if (!target) { bot.chat('I don\'t see you !') return } const p = target.position bot.pathfinder.setMovements(defaultMove) bot.pathfinder.setGoal(new GoalNear(p.x, p.y, p.z, 1)) } }) }) ``` -------------------------------- ### Add Movement Class Example Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Demonstrates how to use custom movement classes for more advanced pathfinding behaviors. This allows for fine-grained control over bot movement. ```javascript const { GoalNear } = require('mineflayer-pathfinder').goals const { Movements } = require('mineflayer-pathfinder').Movements const movements = new Movements(bot) movements.canDig = true bot.pathfinder.setMovements(movements) bot.pathfinder.setGoal(new GoalNear(x, y, z, 1)) ``` -------------------------------- ### Fix Path Starting on Shorter Blocks Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Addresses an issue where pathfinding could be unreliable when the bot starts on a shorter block (e.g., a slab). This ensures a stable starting point for path calculations. ```javascript const mcData = require('minecraft-data')(bot.version) const defaultMove = new Movements(bot, mcData) // Pathfinding start logic on shorter blocks has been improved. ``` -------------------------------- ### Fixed 12.x Node.js Compatibility in Example Bot Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Ensures that the example bot code is compatible with Node.js version 12.x. This allows users running older Node.js versions to execute the examples without issues. ```javascript // Example bot code updated for Node.js 12.x compatibility. ``` -------------------------------- ### bot.pathfinder.getPathFromTo*(movements, startPos, goal, options = {}) Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Generates a path from a starting position to a goal using a generator function, allowing for incremental path computation. ```APIDOC ## bot.pathfinder.getPathFromTo*(movements, startPos, goal, options = {}) ### Description Returns a Generator. The generator computes the path for as long as no full path is found or `options.timeout` is reached. The generator will block the event loop until a path is found or `options.tickTimeout` (default to 50ms) is reached. ### Parameters #### Path Parameters - **movements** (Movements instance) - The movement settings to use for pathfinding. - **startPos** (Vec3 instance) - The starting position to base the path search from. - **goal** (Goal instance) - The goal to calculate the path to. - **options** (object) - Optional. An options object containing: - **optimizePath** (Boolean) - Optional. Optimize path for shortcuts like going to the next node in a strait line instead of walking only diagonal or along axis. - **resetEntityIntersects** (Boolean) - Optional. Reset the `entityIntersections` index for `movements`. Default: true. - **timeout** (Number) - Optional. Total computation timeout. - **tickTimeout** (Number) - Optional. Maximum amount of time before yielding. - **searchRadius** (Number) - Optional. Max distance to search. - **startMove** (Move instance) - Optional. A starting position as a Move. Replaces `startPos` as the starting position. ``` -------------------------------- ### Navigate with Status Updates Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Navigate to a goal while sending chat messages to indicate the start and end of the movement. ```js bot.chat('Going to my goal!') const myGoal = new GoalBlock(15, 3, 75) await bot.pathfinder.goto(myGoal) bot.chat('Arrived at my goal!') ``` -------------------------------- ### Configure Pathfinder Movements Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Customize pathfinding behavior by creating a new `Movements` instance, modifying its properties, and setting it for the pathfinder. This example shows how to disable block breaking and 1x1 tower building, and add netherrack to scaffolding blocks. ```javascript const { Movements } = require('mineflayer-pathfinder') // Import the Movements class from pathfinder bot.once('spawn', () => { // A new movement instance for specific behavior const defaultMove = new Movements(bot) defaultMove.allow1by1towers = false // Do not build 1x1 towers when going up defaultMove.canDig = false // Disable breaking of blocks when pathing defaultMove.scafoldingBlocks.push(bot.registry.itemsByName['netherrack'].id) // Add nether rack to allowed scaffolding items bot.pathfinder.setMovements(defaultMove) // Update the movement instance pathfinder uses // Do pathfinder things // ... }) ``` -------------------------------- ### Movements Initialized by Default Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md The `Movements` object is now initialized with default settings when the pathfinder plugin is loaded. This simplifies setup as developers don't need to manually create and configure `Movements` unless they want to customize it. ```javascript const pathfinder = require('mineflayer-pathfinder').pathfinder bot.loadPlugin(pathfinder) // Default movements are now active. ``` -------------------------------- ### Execute Pathfinding to Goal Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Use the goto method to navigate the bot to the specified goal, awaiting completion. ```js await bot.pathfinder.goto(myGoal) ``` -------------------------------- ### bot.pathfinder.goto(goal) Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Initiates pathfinding to a specified goal. Returns a Promise that resolves when the goal is reached or rejects on error. ```APIDOC ## bot.pathfinder.goto(goal) ### Description Returns a Promise with the path result. Resolves when the goal is reached. Rejects on error. ### Parameters #### Path Parameters - **goal** (Goal instance) - The goal to navigate to. ``` -------------------------------- ### Avoid Cobwebs Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Enables the pathfinder to avoid cobwebs. This prevents the bot from getting stuck or slowed down significantly when encountering cobwebs. ```javascript const mcData = require('minecraft-data')(bot.version) const defaultMove = new Movements(bot, mcData) defaultMove.ignoreCobwebs = false bot.pathfinder.setMovements(defaultMove) ``` -------------------------------- ### Configure Pathfinder Plugin Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Load the pathfinder plugin and define default movement settings upon bot spawn. ```js bot.once('spawn', () => { bot.loadPlugin(pathfinder) // load pathfinder plugin into the bot const defaultMovements = new Movements(bot) // create a new instance of the `Movements` class bot.pathfinder.setMovements(defaultMovements) // set the bot's movements to the `Movements` we just created }) ``` -------------------------------- ### Full Chat Listener Implementation Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Integrate the goal definition and navigation logic into the chat listener. ```js bot.on('chat', async (username, message) => { if (username === bot.username) return // make bot ignore its own messages if (message === 'go') { // this is our trigger message (only works on servers with vanilla chat) bot.chat('Going to my goal!') const myGoal = new GoalBlock(15, 3, 75) await bot.pathfinder.goto(myGoal) bot.chat('Arrived at my goal!') } }) ``` -------------------------------- ### Initialize Mineflayer Bot Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Create a standard Mineflayer bot instance to be used with the pathfinder plugin. ```js const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'Pathfinder', auth: 'offline' }) ``` -------------------------------- ### Create GoalCompositeAll Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Combine multiple goals into a GoalCompositeAll instance. The bot must satisfy all contained goals simultaneously to complete this goal. ```javascript const goalsArray = [LapisGoal, GoldGoal, DiamondGoal] // array containing all three of our goals; we'll use this array in our `GoalCompositeAll` goal ``` ```javascript const goalAll = new GoalCompositeAll(goalsArray) ``` ```javascript await bot.pathfinder.goto(goalAll) ``` -------------------------------- ### Navigate to Meet Multiple Conditions Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Uses GoalCompositeAll to ensure all provided goals are satisfied simultaneously before completing the path. ```javascript const { GoalCompositeAll, GoalNear, GoalY } = require('mineflayer-pathfinder').goals bot.on('chat', async (username, message) => { if (message === 'meet-conditions') { const target = bot.players[username]?.entity if (!target) return const p = target.position // Must be near player AND at Y=64 const goals = [ new GoalNear(p.x, p.y, p.z, 5), // Within 5 blocks of player new GoalY(64) // At Y level 64 ] const compositeGoal = new GoalCompositeAll(goals) try { await bot.pathfinder.goto(compositeGoal) bot.chat('Met all conditions!') } catch (err) { bot.chat('Could not satisfy all conditions') } } }) ``` -------------------------------- ### Implement Chat Trigger Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Set up a chat listener to trigger pathfinding actions based on specific user messages. ```js bot.on('chat', async (username, message) => { if (username === bot.username) return // make bot ignore its own messages if (message === 'go') { // this is our trigger message (only works on servers with vanilla chat) // our pathfinder code goes here! } }) ``` -------------------------------- ### bot.pathfinder.getPathTo(movements, goal, timeout) Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Calculates a path to a given goal using specified movement settings. ```APIDOC ## bot.pathfinder.getPathTo(movements, goal, timeout) ### Description Returns the path. ### Parameters #### Path Parameters - **movements** (Movements instance) - The movement settings to use for pathfinding. - **goal** (Goal instance) - The goal to calculate the path to. - **timeout** (number) - Optional. The maximum time in milliseconds to spend calculating the path. Defaults to `bot.pathfinder.thinkTimeout`. ``` -------------------------------- ### Configure Pathfinder Properties Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Adjust pathfinding performance and behavior settings within the bot's spawn event. ```javascript bot.once('spawn', () => { // Maximum time for path computation (ms) bot.pathfinder.thinkTimeout = 5000 // Default: 5000 // Time allocated to thinking per game tick (ms, max 50) bot.pathfinder.tickTimeout = 40 // Default: 40 // Search radius limit (-1 for unlimited) bot.pathfinder.searchRadius = 150 // Default: -1 // Enable path shortcuts (can cause issues in some terrain) bot.pathfinder.enablePathShortcut = false // Default: false // Require line of sight when placing blocks bot.pathfinder.LOSWhenPlacingBlocks = true // Default: true // Access current goal (read-only) console.log('Current goal:', bot.pathfinder.goal) // Access current movements (read-only) console.log('Current movements:', bot.pathfinder.movements) }) ``` -------------------------------- ### Set Static and Dynamic Pathfinding Goals Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Use `bot.pathfinder.setGoal()` to set a pathfinding goal. Set `dynamic=true` for goals that change position, like following an entity. Dynamic goals do not emit `goal_reached` events. ```javascript const { GoalNear, GoalFollow } = require('mineflayer-pathfinder').goals bot.on('chat', (username, message) => { if (username === bot.username) return const target = bot.players[username]?.entity if (message === 'come' && target) { // Static goal - emits goal_reached when arrived const p = target.position bot.pathfinder.setGoal(new GoalNear(p.x, p.y, p.z, 1)) } if (message === 'follow' && target) { // Dynamic goal - continuously follows, no goal_reached event bot.pathfinder.setGoal(new GoalFollow(target, 3), true) } }) bot.on('goal_reached', (goal) => { console.log('Arrived at goal!') }) ``` -------------------------------- ### Configure Custom Pathfinding Movements Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Customize bot navigation behavior by creating a `Movements` instance with specific properties like `canDig`, `allowParkour`, and `maxDropDown`. ```javascript const { Movements } = require('mineflayer-pathfinder') bot.once('spawn', () => { const customMoves = new Movements(bot) // Disable block breaking during pathfinding customMoves.canDig = false // Disable 1x1 tower building when going up customMoves.allow1by1towers = false // Disable parkour jumps over gaps customMoves.allowParkour = false // Disable sprinting customMoves.allowSprinting = false // Set maximum fall distance (blocks) customMoves.maxDropDown = 3 // Add additional scaffolding blocks customMoves.scafoldingBlocks.push(bot.registry.itemsByName.stone.id) customMoves.scafoldingBlocks.push(bot.registry.itemsByName.netherrack.id) // Add blocks to avoid walking on customMoves.blocksToAvoid.add(bot.registry.blocksByName.cactus.id) customMoves.blocksToAvoid.add(bot.registry.blocksByName.fire.id) // Apply the custom movements bot.pathfinder.setMovements(customMoves) }) ``` -------------------------------- ### Create GoalCompositeAny Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Combine multiple goals into a GoalCompositeAny instance. The bot will complete this goal if any of the contained goals are met. ```javascript const goalsArray = [LapisGoal, GoldGoal, DiamondGoal] // array containing all three of our goals; we'll use this array in our `GoalCompositeAny` goal ``` ```javascript const goalAny = new GoalCompositeAny(goalsArray) ``` ```javascript await bot.pathfinder.goto(goalAny) ``` -------------------------------- ### Navigate to a Specific Block Goal Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Use the `bot.pathfinder.goto()` method to navigate the bot to a specific block coordinate. Handles various pathfinding errors like NoPath, Timeout, GoalChanged, and PathStopped. ```javascript const { GoalBlock, GoalNear } = require('mineflayer-pathfinder').goals bot.once('spawn', async () => { const defaultMove = new Movements(bot) bot.pathfinder.setMovements(defaultMove) try { // Navigate to specific coordinates const goal = new GoalBlock(100, 64, 200) await bot.pathfinder.goto(goal) console.log('Arrived at destination!') } catch (err) { if (err.name === 'NoPath') { console.log('Could not find a path to the goal') } else if (err.name === 'Timeout') { console.log('Pathfinding took too long') } else if (err.name === 'GoalChanged') { console.log('Goal was changed before reaching destination') } else if (err.name === 'PathStopped') { console.log('Pathfinding was stopped') } } }) ``` -------------------------------- ### bot.pathfinder.stop() - Graceful and Force Stop Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Provides methods to stop pathfinding. `bot.pathfinder.stop()` stops gracefully at the next node, while `bot.pathfinder.setGoal(null)` forces an immediate stop. ```APIDOC ## bot.pathfinder.stop() ### Description Stop pathfinding as soon as the bot reaches the next node in the path. This prevents stopping mid-air or mid-jump. ### Method `bot.pathfinder.stop()` ### Endpoint N/A (Internal function) ### Parameters None ### Request Example ```javascript bot.pathfinder.stop() ``` ## bot.pathfinder.setGoal(null) - Force Stop ### Description Immediately stops pathfinding, potentially leaving the bot in an unsafe position. ### Method `bot.pathfinder.setGoal(null)` ### Endpoint N/A (Internal function) ### Parameters - `goal` (null) - Setting the goal to null aborts the current path. ### Request Example ```javascript bot.pathfinder.setGoal(null) ``` ### Response N/A ### Events - `path_stop`: Emitted when pathfinding is stopped. ``` -------------------------------- ### Create GoalBlock Instance Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Define a target destination using the GoalBlock class with specific X, Y, and Z coordinates. ```js const myGoal = new GoalBlock(15, 3, 75) ``` -------------------------------- ### GoalGetToBlock Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Navigate to be adjacent to a block. ```APIDOC ## GoalGetToBlock ### Description Navigate to be adjacent to a block (not inside it). Ideal for interacting with chests, crafting tables, etc. ### Parameters - **x** (number) - Required - Block X coordinate - **y** (number) - Required - Block Y coordinate - **z** (number) - Required - Block Z coordinate ``` -------------------------------- ### Added Simple Postprocessing Fallback Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Introduces a simple fallback mechanism for postprocessing paths when the primary method fails. This increases the robustness of pathfinding in complex scenarios. ```javascript const mcData = require('minecraft-data')(bot.version) const defaultMove = new Movements(bot, mcData) // Postprocessing fallback has been added. ``` -------------------------------- ### bot.pathfinder.setGoal(goal, dynamic) Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Sets a pathfinding goal for the bot, with support for dynamic targets. ```APIDOC ## bot.pathfinder.setGoal(goal, dynamic) ### Description Sets the current pathfinding goal. If dynamic is set to true, the goal is treated as moving (e.g., following an entity) and will not emit the 'goal_reached' event. ### Parameters #### Request Body - **goal** (Goal) - Required - The target goal instance. - **dynamic** (boolean) - Optional - Set to true for moving targets. ``` -------------------------------- ### API in the Readme Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Indicates that the API documentation is available in the README file. Developers can refer to the README for detailed information on available functions and options. ```markdown Refer to the README.md file for detailed API documentation. ``` -------------------------------- ### A* Algorithm Stored as a Class Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md Encapsulates the A* pathfinding algorithm within a class. This promotes better code structure and allows for easier extension or modification of the algorithm. ```javascript const mcData = require('minecraft-data')(bot.version) const defaultMove = new Movements(bot, mcData) // The A* algorithm is now implemented as a class. ``` -------------------------------- ### Stop pathfinding execution Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Demonstrates graceful stopping of pathfinding to reach a safe node versus an immediate stop that may leave the bot in an unsafe position. ```javascript bot.on('chat', (username, message) => { if (message === 'stop') { // Graceful stop - waits for safe position bot.pathfinder.stop() } if (message === 'force-stop') { // Immediate stop - may leave bot in unsafe position bot.pathfinder.setGoal(null) } }) bot.on('path_stop', () => { console.log('Pathfinding stopped') }) ``` -------------------------------- ### Pathfinding Control Methods Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Methods to control and monitor the pathfinding process. ```APIDOC ## bot.pathfinder.setMovements(movements) ### Description Assigns the movements config. ### Method `bot.pathfinder.setMovements` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **movements** (Movements) - Movements instance ### Request Example ```js // Assuming 'movements' is a valid Movements instance bot.pathfinder.setMovements(movements); ``` ### Response None ``` ```APIDOC ## bot.pathfinder.stop() ### Description Stops pathfinding as soon as the bot has reached the next node in the path. Emits `path_stop` when called. Note: to force stop immediately, use `bot.pathfinder.setGoal(null)`. ### Method `bot.pathfinder.stop` ### Endpoint None ### Parameters None ### Request Example ```js bot.pathfinder.stop(); ``` ### Response None ``` ```APIDOC ## bot.pathfinder.isMoving() ### Description A function that checks if the bot is currently moving. ### Method `bot.pathfinder.isMoving` ### Endpoint None ### Parameters None ### Request Example ```js const moving = bot.pathfinder.isMoving(); console.log('Is bot moving?', moving); ``` ### Response #### Success Response (200) * **Returns** (boolean) - True if the bot is currently moving, false otherwise. ``` ```APIDOC ## bot.pathfinder.isMining() ### Description A function that checks if the bot is currently mining blocks. ### Method `bot.pathfinder.isMining` ### Endpoint None ### Parameters None ### Request Example ```js const mining = bot.pathfinder.isMining(); console.log('Is bot mining?', mining); ``` ### Response #### Success Response (200) * **Returns** (boolean) - True if the bot is currently mining, false otherwise. ``` ```APIDOC ## bot.pathfinder.isBuilding() ### Description A function that checks if the bot is currently placing blocks. ### Method `bot.pathfinder.isBuilding` ### Endpoint None ### Parameters None ### Request Example ```js const building = bot.pathfinder.isBuilding(); console.log('Is bot building?', building); ``` ### Response #### Success Response (200) * **Returns** (boolean) - True if the bot is currently placing blocks, false otherwise. ``` -------------------------------- ### Define Multiple GoalNear Instances Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Create instances of GoalNear to define target locations and ranges. Each instance represents a distinct area the bot should approach. ```javascript const LapisGoal = new GoalNear(0, 1, 3, 5) // our bot needs to stand within 5 blocks of the point (0, 1, 3) in order to satisfy this goal (blue circle below) const GoldGoal = new GoalNear(3, 1, -2, 5) // our bot needs to stand within 5 blocks of the point (3, 1, -2) in order to satisfy this goal (yellow circle below) const DiamondGoal = new GoalNear(-3, 1, -2, 5) // our bot needs to stand within 5 blocks of the point (-3, 1, -2) in order to satisfy this goal (white circle below) ``` -------------------------------- ### Status Check Methods: isMoving(), isMining(), isBuilding() Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Provides methods to check the bot's current activity status related to pathfinding, mining, and building. ```APIDOC ## Status Check Methods ### Description Check the bot's current pathfinding state using `isMoving()`, `isMining()`, and `isBuilding()`. ### Methods - **`bot.pathfinder.isMoving()`** - Returns `true` if the bot is currently moving along a path, `false` otherwise. - **`bot.pathfinder.isMining()`** - Returns `true` if the bot is currently mining a block, `false` otherwise. - **`bot.pathfinder.isBuilding()`** - Returns `true` if the bot is currently placing a block, `false` otherwise. ### Endpoint N/A (Internal functions) ### Parameters None for these methods. ### Request Example ```javascript if (bot.pathfinder.isMoving()) { console.log('Bot is moving') } ``` ### Response - **boolean**: `true` or `false` indicating the status. ### Utility Function Example ```javascript async function waitUntilIdle() { while (bot.pathfinder.isMoving() || bot.pathfinder.isMining() || bot.pathfinder.isBuilding()) { await new Promise(resolve => setTimeout(resolve, 100)) } } ``` ``` -------------------------------- ### bot.pathfinder.getPathFromTo(movements, startPos, goal, options) Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt A generator function for computing paths with fine-grained control, yielding partial results during computation. ```APIDOC ## bot.pathfinder.getPathFromTo(movements, startPos, goal, options) ### Description Generator function for computing paths with fine-grained control. Yields partial results during computation. ### Method `GET` (Conceptual - this is a generator function call) ### Endpoint N/A (Internal function) ### Parameters - **movements** (object) - The movement configuration for pathfinding. - **startPos** (Vec3) - The starting position vector. - **goal** (object) - The goal object (e.g., `GoalBlock`). - **options** (object) - Configuration options for path computation: - **timeout** (number) - Total computation timeout in milliseconds. - **tickTimeout** (number) - Maximum time per tick in milliseconds. - **searchRadius** (number) - Maximum search distance in blocks. - **optimizePath** (boolean) - Enable path optimization. ### Request Example ```javascript const { GoalBlock } = require('mineflayer-pathfinder').goals const { Vec3 } = require('vec3') const movements = bot.pathfinder.movements const startPos = bot.entity.position const goal = new GoalBlock(100, 64, 100) const options = { timeout: 10000, tickTimeout: 40, searchRadius: 150, optimizePath: true } const generator = bot.pathfinder.getPathFromTo(movements, startPos, goal, options) ``` ### Response Yields objects with a `result` property: - **result.status** (string) - 'partial' while computing, or final status ('success', 'noPath', 'timeout'). - **result.visitedNodes** (number) - Number of nodes visited so far. - **result.path** (array) - The computed path (if available). - **result.cost** (number) - The cost of the path (if available). - **result.time** (number) - Computation time (if available). ### Response Example (during computation) ```json { "status": "partial", "visitedNodes": 150 } ``` ### Response Example (final) ```json { "status": "success", "path": [...], "cost": 200.50, "visitedNodes": 600, "time": 500.00 } ``` ``` -------------------------------- ### bot.pathfinder.bestHarvestTool(block) Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Determines the most suitable tool from the bot's inventory for harvesting a given block. ```APIDOC ## bot.pathfinder.bestHarvestTool(block) ### Description Returns the best harvesting tool in the inventory for the specified block. ### Parameters #### Path Parameters - **block** (Block instance) - The block to determine the best tool for. ``` -------------------------------- ### bot.pathfinder.setGoal(Goal, dynamic) Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Sets the current navigation goal for the pathfinder. ```APIDOC ## bot.pathfinder.setGoal(Goal, dynamic) ### Description Sets the current navigation goal for the pathfinder. ### Parameters #### Path Parameters - **goal** (Goal instance) - The goal to set. - **dynamic** (boolean) - Optional. If true, the goal is considered dynamic and may be updated during navigation. Defaults to false. ``` -------------------------------- ### Navigate to Place a Block Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Uses GoalPlaceBlock to navigate to a position suitable for placing a block, with configurable line-of-sight and face requirements. ```javascript const { GoalPlaceBlock } = require('mineflayer-pathfinder').goals const { Vec3 } = require('vec3') bot.on('chat', async (username, message) => { if (message.startsWith('place ')) { const [, x, y, z] = message.split(' ').map(Number) const targetPos = new Vec3(x, y, z) const goal = new GoalPlaceBlock(targetPos, bot.world, { range: 5, LOS: true, // Require line of sight faces: [ // Allowed placement faces new Vec3(0, -1, 0), // Bottom new Vec3(0, 1, 0), // Top new Vec3(0, 0, -1), // North new Vec3(0, 0, 1), // South new Vec3(-1, 0, 0), // West new Vec3(1, 0, 0) // East ] }) try { await bot.pathfinder.goto(goal) // Get reference block and place const referenceBlock = bot.blockAt(targetPos.offset(0, -1, 0)) if (referenceBlock) { await bot.placeBlock(referenceBlock, new Vec3(0, 1, 0)) bot.chat('Block placed!') } } catch (err) { console.log('Could not place block:', err.message) } } }) ``` -------------------------------- ### Promisified goto Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/history.md The `goto` function is now fully promisified, allowing for cleaner asynchronous code using `async/await` or `.then()` syntax. ```javascript async function navigate () { try { await bot.pathfinder.goto(new GoalNear(x, y, z, 1)) console.log('Arrived at destination!') } catch (err) { console.error('Pathfinding failed:', err) } } navigate() ``` -------------------------------- ### Navigate to Nearest Target Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Uses GoalCompositeAny to reach the most accessible target from a collection of potential goals. ```javascript const { GoalCompositeAny, GoalGetToBlock } = require('mineflayer-pathfinder').goals bot.on('chat', async (username, message) => { if (message === 'find-ore') { // Find all nearby diamond ore const ores = bot.findBlocks({ matching: bot.registry.blocksByName.diamond_ore.id, maxDistance: 32, count: 10 }) if (ores.length === 0) { bot.chat('No diamond ore found') return } // Create a goal for each ore location const goals = ores.map(pos => new GoalGetToBlock(pos.x, pos.y, pos.z) ) // GoalCompositeAny will pathfind to the easiest one to reach const compositeGoal = new GoalCompositeAny(goals) try { await bot.pathfinder.goto(compositeGoal) bot.chat('Found diamond ore!') } catch (err) { console.log('Could not reach any ore:', err.message) } } }) ``` -------------------------------- ### Pathfinder Configuration Options Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Configuration options that can be passed to the pathfinder plugin. ```APIDOC ## Pathfinder Configuration Options ### carpets Set of all carpet block id's or blocks that have a collision box smaller then 0.1. These blocks are considered safe to walk in. * instance of `Set` ### exclusionAreasStep An array of functions that define an area or block to be step on excluded. Every function in the array is parsed the Block the bot is planing to step on. Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 means it is impossible for pathfinder to consider this move. * Array of functions `(block: Block) => number` ### exclusionAreasBreak An array of functions that define an area or block to be break excluded. Every function in the array is parsed the Block the bot is planing to break. Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 means it is impossible for pathfinder to consider this move. * Array of functions `(block: Block) => number` ### exclusionAreasPlace An array of functions that define an area to be block placement excluded. Every function in the array is parsed the current Block the bot is planing to place a block inside (should be air or a replaceable block most of the time). Each function should return a positive number (includes 0) that defines extra cost for that specific Block. 0 means no extra cost, 100 makes it impossible for pathfinder to consider this move. * Array of functions `(block: Block) => number` ### entityIntersections A dictionary of the number of entities intersecting each floored block coordinate. Updated automatically for each path, but you may mix in your own entries before calculating a path if desired (generally for testing). To prevent this from being cleared automatically before generating a path,s see the [path gen options](#botpathfindergetpathfromto-movements-startpos-goal-options--). * Formatted entityIntersections['x,y,z'] = #ents * Dictionary of costs `{string: number}` ### canOpenDoors Enable feature to open Fence Gates. Unreliable and known to be buggy. * Default - `false` ``` -------------------------------- ### Chain Navigation Goals Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Navigate through a sequence of waypoints using async/await to handle pathfinding completion or errors. ```javascript const { GoalBlock } = require('mineflayer-pathfinder').goals const checkpoints = [] bot.on('chat', async (username, message) => { const target = bot.players[username]?.entity if (message === 'point' && target) { // Add checkpoint at player's position const pos = target.position.floored() checkpoints.push(pos) bot.chat(`Checkpoint ${checkpoints.length} set at ${pos}`) } if (message === 'walk') { if (checkpoints.length === 0) { bot.chat('No checkpoints set') return } bot.chat(`Walking through ${checkpoints.length} checkpoints`) // Copy and clear checkpoints const route = [...checkpoints] checkpoints.length = 0 for (let i = 0; i < route.length; i++) { const checkpoint = route[i] const goal = new GoalBlock(checkpoint.x, checkpoint.y, checkpoint.z) try { bot.chat(`Going to checkpoint ${i + 1}/${route.length}`) await bot.pathfinder.goto(goal) } catch (err) { bot.chat(`Failed at checkpoint ${i + 1}: ${err.message}`) return } } bot.chat('Completed all checkpoints!') } if (message === 'clear') { checkpoints.length = 0 bot.chat('Checkpoints cleared') } }) ``` -------------------------------- ### Navigate for Block Interaction with GoalLookAtBlock Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Use GoalLookAtBlock to position the bot so a specific block face is visible and reachable. ```javascript const { GoalLookAtBlock } = require('mineflayer-pathfinder').goals const { Vec3 } = require('vec3') bot.on('chat', async (username, message) => { if (message === 'break-target') { const target = bot.players[username]?.entity if (!target) return // Get block player is standing on const blockPos = target.position.offset(0, -1, 0).floored() const block = bot.blockAt(new Vec3(blockPos.x, blockPos.y, blockPos.z)) const goal = new GoalLookAtBlock(blockPos, bot.world, { reach: 4.5, // Max distance from block face entityHeight: 1.6 // Eye height for line-of-sight check }) try { await bot.pathfinder.goto(goal) await bot.dig(block) bot.chat('Block broken!') } catch (err) { console.log('Could not break block:', err.message) } } }) ``` -------------------------------- ### Import Pathfinder Dependencies Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/examples/tutorial/goalsExplained.md Import the necessary classes and the pathfinder plugin from the mineflayer-pathfinder package. ```js const mineflayer = require('mineflayer') const { pathfinder, Movements, goals:{ GoalBlock } } = require('mineflayer-pathfinder') ``` -------------------------------- ### Pathfinder Goal Classes Source: https://github.com/prismarinejs/mineflayer-pathfinder/blob/master/readme.md Abstract and concrete goal classes for pathfinding. ```APIDOC # Goals: ### Goal Abstract Goal class. Do not instantiate this class. Instead extend it to make a new Goal class. Has abstract methods: - `heuristic(node)` * `node` - A path node * Returns a heuristic number value for a given node. Must be admissible – meaning that it never overestimates the actual cost to get to the goal. - `isEnd(node)` * `node` * Returns a boolean value if the given node is a end node. Implements default methods for: - `isValid()` * Always returns `true` - `hasChanged(node)` * `node` - A path node * Always returns `false` ### GoalBlock(x, y, z) One specific block that the player should stand inside at foot level * `x` - Integer * `y` - Integer * `z` - Integer ### GoalNear(x, y, z, range) A block position that the player should get within a certain radius of * `x` - Integer * `y` - Integer * `z` - Integer * `range` - Integer ### GoalXZ(x, z) Useful for long-range goals that don't have a specific Y level * `x` - Integer * `z` - Integer ### GoalNearXZ(x, z, range) Useful for finding builds that you don't have an exact Y level for, just an approximate X and Z level. * `x` - Integer * `z` - Integer * `range` - Integer ### GoalY(y) Get to a Y level. * `y` - Integer ### GoalGetToBlock(x, y, z) Don't get into the block, but get directly adjacent to it. Useful for chests. * `x` - Integer * `y` - Integer * `z` - Integer ### GoalCompositeAny(Array?) A composite of many goals, any one of which satisfies the composite. For example, a GoalCompositeAny of block goals for every oak log in loaded chunks would result in it pathing to the easiest oak log to get to. * `Array` - Array of goals ### GoalCompositeAll(Array?) A composite of multiple goals, requiring all of them to be satisfied. * `Array` - Array of goals ### GoalInvert(goal) Inverts the goal. * `goal` - Goal to invert ### GoalFollow(entity, range) Follows an entity. * `entity` - Entity instance * `range` - Integer ``` -------------------------------- ### Navigate X/Z Coordinates with GoalXZ and GoalNearXZ Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Use these goals for long-range navigation where the Y-level is irrelevant or flexible. ```javascript const { GoalXZ, GoalNearXZ } = require('mineflayer-pathfinder').goals bot.on('chat', (username, message) => { if (message.startsWith('travel ')) { const [, x, z] = message.split(' ') // Navigate to exact X/Z (any Y level) const exactGoal = new GoalXZ(parseInt(x), parseInt(z)) bot.pathfinder.setGoal(exactGoal) } if (message.startsWith('explore ')) { const [, x, z, range] = message.split(' ') // Navigate within range of X/Z coordinates const nearGoal = new GoalNearXZ(parseInt(x), parseInt(z), parseInt(range) || 5) bot.pathfinder.setGoal(nearGoal) } }) ``` -------------------------------- ### GoalNear Source: https://context7.com/prismarinejs/mineflayer-pathfinder/llms.txt Navigate to within a specified range of a 3D position. ```APIDOC ## GoalNear ### Description Navigate to within a specified range of a 3D position. ### Parameters - **x** (number) - Required - X coordinate - **y** (number) - Required - Y coordinate - **z** (number) - Required - Z coordinate - **range** (number) - Required - Distance threshold ```