### Initialize and Start StateMachineWebserver Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Example of setting up a Mineflayer bot, defining a state machine, and then initializing and starting the StateMachineWebserver to visualize it. The web interface will be available at http://localhost:8934. ```javascript const mineflayer = require('mineflayer'); const { BotStateMachine, NestedStateMachine, StateMachineWebserver } = require('mineflayer-statemachine'); const bot = mineflayer.createBot({ username: 'Player' }); bot.once('spawn', () => { // Set up your state machine const rootLayer = new NestedStateMachine(transitions, startState); const stateMachine = new BotStateMachine(bot, rootLayer); // Start the web server const webserver = new StateMachineWebserver(bot, stateMachine, 8934); webserver.startServer(); console.log('State machine visualization at http://localhost:8934'); }); ``` -------------------------------- ### Usage Example: Setting up BehaviorFindBlock with State Machine Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFindBlock.md Demonstrates how to integrate BehaviorFindBlock into a larger state machine. It shows the setup of behaviors, transitions, and the state machine itself. ```javascript const { BehaviorFindBlock, BehaviorMoveTo, BehaviorMineBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const mcData = require('minecraft-data')('1.16.5'); const targets = {}; // Create behaviors const findStone = new BehaviorFindBlock(bot, targets); findStone.blocks = [mcData.blocksByName.stone.id]; findStone.maxDistance = 32; findStone.preventXRay = true; // Only find visible blocks const moveTo = new BehaviorMoveTo(bot, targets); const mine = new BehaviorMineBlock(bot, targets); // Create transitions const transitions = [ new StateTransition({ parent: findStone, child: moveTo, shouldTransition: () => targets.position !== undefined, name: 'found-block' }), new StateTransition({ parent: moveTo, child: mine, shouldTransition: () => moveTo.isFinished(), name: 'reached-block' }), new StateTransition({ parent: mine, child: findStone, shouldTransition: () => mine.isFinished, name: 'mining-done' }) ]; const rootLayer = new NestedStateMachine(transitions, findStone); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example: Setting up BehaviorFindInteractPosition Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFindInteractPosition.md Demonstrates how to instantiate and configure BehaviorFindInteractPosition, including setting search distance, customizing costs, and adding custom block avoidance. This setup is part of a larger state machine for bot actions. ```javascript const { BehaviorFindInteractPosition, BehaviorMoveTo, BehaviorMineBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors const findPosition = new BehaviorFindInteractPosition(bot, targets); findPosition.maxDistance = 3; // Search up to 3 blocks away // Customize costs to prefer positions closer to target findPosition.costs.distanceMultiplier = 5; findPosition.costs.standOnCost = 50; // Prefer standing under // Add custom block costs (avoid water more) findPosition.costs.blockCosts.push([mcData.blocksByName.water.id, 50, 100]); // Add dangerous blocks to avoid findPosition.costs.avoid.push(mcData.blocksByName.cactus.id); findPosition.costs.avoid.push(mcData.blocksByName.magma_block.id); const moveTo = new BehaviorMoveTo(bot, targets); const mine = new BehaviorMineBlock(bot, targets); // Create transitions const transitions = [ new StateTransition({ parent: findPosition, child: moveTo, shouldTransition: () => targets.position !== undefined, name: 'position-found' }), new StateTransition({ parent: moveTo, child: mine, shouldTransition: () => moveTo.isFinished(), name: 'at-position' }) ]; const rootLayer = new NestedStateMachine(transitions, findPosition); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Start StateMachineWebserver Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Starts the webserver to visualize the state machine. Access the visualization via the specified port. ```typescript const webserver = new StateMachineWebserver(bot, stateMachine, 8080); webserver.startServer(); // Access at http://localhost:8080 ``` -------------------------------- ### Usage Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorLookAtEntity.md An example demonstrating how to use BehaviorLookAtEntity in conjunction with other behaviors and state transitions within a BotStateMachine. ```APIDOC ## Usage Example ```javascript const { BehaviorLookAtEntity, BehaviorFollowEntity, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors const follow = new BehaviorFollowEntity(bot, targets); const lookAt = new BehaviorLookAtEntity(bot, targets); // Create transitions const transitions = [ // Follow until close enough to look at new StateTransition({ parent: follow, child: lookAt, shouldTransition: () => follow.distanceToTarget() < 2, name: 'get-close' }), // Resume following if target moves away new StateTransition({ parent: lookAt, child: follow, shouldTransition: () => lookAt.distanceToTarget() >= 2, name: 'target-moved-away' }) ]; const rootLayer = new NestedStateMachine(transitions, follow); new BotStateMachine(bot, rootLayer); ``` ``` -------------------------------- ### Usage Example for BehaviorPlaceBlock Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorPlaceBlock.md Demonstrates how to set up and use BehaviorPlaceBlock within a mineflayer-statemachine setup, including defining transitions and target properties. ```javascript const { BehaviorPlaceBlock, BehaviorFindInteractPosition, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const { Vec3 } = require('vec3'); const mcData = require('minecraft-data')('1.16.5'); const targets = {}; // Create behaviors const findPosition = new BehaviorFindInteractPosition(bot, targets); const place = new BehaviorPlaceBlock(bot, targets); // Create transitions const transitions = [ new StateTransition({ parent: findPosition, child: place, shouldTransition: () => { // Set the block to place against if (targets.position) { const block = bot.blockAt(targets.position); targets.blockFace = new Vec3(0, 1, 0); // Place on top targets.item = bot.inventory.items().find(i => i.name === 'dirt'); } return targets.item !== undefined && targets.blockFace !== undefined; }, name: 'ready-to-place' }) ]; const rootLayer = new NestedStateMachine(transitions, findPosition); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Initialize Targets and Behaviors Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md Demonstrates the basic setup for using targets. A 'targets' object is created and passed to the constructors of multiple behaviors. ```javascript const bot = /* your bot*/; const targets = {}; const behavior1 = new MyBehavior1(bot, targets); const behavior2 = new MyBehavior1(bot, targets); const behavior3 = new MyBehavior1(bot, targets); ``` -------------------------------- ### startServer() Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Configures and starts the web server. The server will serve a static web interface and establish WebSocket connections with clients to push real-time state updates. ```APIDOC ## startServer() ### Description Configures and starts the web server. The server will serve a static web interface and establish WebSocket connections with clients to push real-time state updates. ### Method `void` ### Endpoint N/A (Method call) ### Parameters None ### Throws `Error` - If the server is already running. ``` -------------------------------- ### Usage Example: Creating Nested State Machine Layers Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/NestedStateMachine.md Demonstrates how to create and configure NestedStateMachine instances with different transitions and states. Shows examples with and without an explicit exit state. ```javascript const { NestedStateMachine, StateTransition, BehaviorIdle, BehaviorFollowEntity } = require('mineflayer-statemachine'); const targets = {}; const idleState = new BehaviorIdle(); const followState = new BehaviorFollowEntity(bot, targets); // Define transitions for this layer const transitions = [ new StateTransition({ parent: idleState, child: followState, shouldTransition: () => targets.entity !== undefined, name: 'start-following' }), new StateTransition({ parent: followState, child: idleState, shouldTransition: () => targets.entity === undefined, name: 'stop-following' }) ]; // Create a nested state machine layer const layer = new NestedStateMachine(transitions, idleState); // With an exit state (for sequences that complete) const exitState = new BehaviorIdle(); const sequenceLayer = new NestedStateMachine(transitions, idleState, exitState); ``` -------------------------------- ### BotStateMachine Usage Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BotStateMachine.md Demonstrates how to initialize and use the BotStateMachine. It includes creating behavior states, defining transitions, setting up the root state machine, and listening for state changes. ```javascript const mineflayer = require('mineflayer'); const { BotStateMachine, NestedStateMachine, StateTransition } = require('mineflayer-statemachine'); const bot = mineflayer.createBot({ username: 'Player' }); bot.once('spawn', () => { // Create your behavior states const idleState = new BehaviorIdle(); const followState = new BehaviorFollowEntity(bot, targets); // Define transitions const transitions = [ new StateTransition({ parent: idleState, child: followState, shouldTransition: () => true }) ]; // Create root state machine const rootLayer = new NestedStateMachine(transitions, idleState); // Initialize the bot state machine const stateMachine = new BotStateMachine(bot, rootLayer); // Listen to state changes stateMachine.on('stateChanged', () => { console.log('Bot behavior changed'); }); }); ``` -------------------------------- ### Install Mineflayer-StateMachine Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/README.md Install the mineflayer-statemachine plugin using npm. This plugin relies on mineflayer-pathfinder for movement behaviors. ```bash npm install --save mineflayer-statemachine ``` -------------------------------- ### Configure and Use StateTransition Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Example of creating a StateTransition with custom conditions and callbacks. ```typescript new StateTransition({ parent: stateA, child: stateB, name: 'my-transition', shouldTransition: () => someCondition(), onTransition: () => console.log('Transitioned!') }) ``` -------------------------------- ### Usage Example for BehaviorIdle Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/SimpleBehaviors.md Demonstrates how to set up a state machine using BehaviorIdle as the initial state and BehaviorFollowEntity as a subsequent state. The transition occurs when a target entity is defined. ```javascript const { BehaviorIdle, BehaviorFollowEntity, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; const idle = new BehaviorIdle(); const follow = new BehaviorFollowEntity(bot, targets); const transitions = [ new StateTransition({ parent: idle, child: follow, shouldTransition: () => targets.entity !== undefined }) ]; const rootLayer = new NestedStateMachine(transitions, idle); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### MineBlock Usage Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorMineBlock.md Demonstrates how to integrate BehaviorMineBlock with BehaviorFindBlock and BotStateMachine. Sets up transitions for finding and mining blocks like stone. ```javascript const { BehaviorMineBlock, BehaviorFindBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const mcData = require('minecraft-data')('1.16.5'); const targets = {}; // Create behaviors const findBlock = new BehaviorFindBlock(bot, targets); findBlock.blocks = [mcData.blocksByName.stone.id]; findBlock.maxDistance = 32; const mineBlock = new BehaviorMineBlock(bot, targets); // Create transitions const transitions = [ new StateTransition({ parent: findBlock, child: mineBlock, shouldTransition: () => targets.position !== undefined, name: 'start-mining' }), new StateTransition({ parent: mineBlock, child: findBlock, shouldTransition: () => mineBlock.isFinished, name: 'mining-complete' }) ]; const rootLayer = new NestedStateMachine(transitions, findBlock); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example for BehaviorPrintServerStats Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/SimpleBehaviors.md Sets up a state machine where BehaviorPrintServerStats is the initial state, transitioning immediately to BehaviorIdle. This is useful for logging server details upon bot connection. ```javascript const { BehaviorPrintServerStats, BehaviorIdle, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const printStats = new BehaviorPrintServerStats(bot); const nextState = new BehaviorIdle(); const transitions = [ new StateTransition({ parent: printStats, child: nextState, shouldTransition: () => true }) ]; const rootLayer = new NestedStateMachine(transitions, printStats); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example: Equipping a Diamond Pickaxe Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorEquipItem.md Demonstrates how to set up and use the BehaviorEquipItem to equip a diamond pickaxe. It includes setting up transitions and defining the target item. ```javascript const { BehaviorEquipItem, BehaviorMineBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const mcData = require('minecraft-data')('1.16.5'); const targets = {}; // Create behaviors const mine = new BehaviorMineBlock(bot, targets); const equipPickaxe = new BehaviorEquipItem(bot, targets); equipPickaxe.autoEquipArmor = true; // Will auto-equip armor // Create transitions const transitions = [ new StateTransition({ parent: equipPickaxe, child: mine, shouldTransition: () => equipPickaxe.wasEquipped, name: 'pickaxe-equipped' }) ]; // Set target item before entering behavior const onEnterEquip = (targets) => { const pickaxe = bot.inventory.items().find(i => i.name === 'diamond_pickaxe'); targets.item = pickaxe; }; const rootLayer = new NestedStateMachine(transitions, equipPickaxe); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example: BehaviorLookAtEntity with BehaviorFollowEntity Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorLookAtEntity.md Demonstrates how to integrate BehaviorLookAtEntity with BehaviorFollowEntity using StateTransitions in a BotStateMachine. This setup allows the bot to follow an entity until it's close, then look at it, and resume following if the entity moves away. ```javascript const { BehaviorLookAtEntity, BehaviorFollowEntity, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors const follow = new BehaviorFollowEntity(bot, targets); const lookAt = new BehaviorLookAtEntity(bot, targets); // Create transitions const transitions = [ // Follow until close enough to look at new StateTransition({ parent: follow, child: lookAt, shouldTransition: () => follow.distanceToTarget() < 2, name: 'get-close' }), // Resume following if target moves away new StateTransition({ parent: lookAt, child: follow, shouldTransition: () => lookAt.distanceToTarget() >= 2, name: 'target-moved-away' }) ]; const rootLayer = new NestedStateMachine(transitions, follow); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example: Creating and Triggering a State Transition Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateTransition.md Demonstrates how to create a StateTransition with custom logic for `shouldTransition` and `onTransition` callbacks, and how to manually trigger it. Ensure necessary behaviors are imported. ```javascript const { StateTransition, BehaviorFollowEntity, BehaviorLookAtEntity } = require('mineflayer-statemachine'); const targets = {}; const followState = new BehaviorFollowEntity(bot, targets); const lookState = new BehaviorLookAtEntity(bot, targets); // Create a transition that checks a condition each tick const transition = new StateTransition({ parent: followState, child: lookState, name: 'entity-close-enough', shouldTransition: () => { return followState.distanceToTarget() < 2; }, onTransition: () => { console.log('Target is close, stopping to look'); } }); // Later: manually trigger the transition transition.trigger(); ``` -------------------------------- ### Check Server Status Before Starting Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/errors.md Prevent 'Server already running!' errors by checking if the server is running before calling startServer(). ```typescript const webserver = new StateMachineWebserver(bot, stateMachine, 8934); if (!webserver.isServerRunning()) { webserver.startServer(); } ``` -------------------------------- ### StateMachineWebserver startServer Method Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Configures and starts the web server. It serves a static web interface and uses WebSockets for real-time state updates. Throws an error if the server is already running. ```typescript startServer(): void ``` -------------------------------- ### Usage Example: Finding and Opening a Door Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorInteractBlock.md Demonstrates how to use BehaviorFindBlock and BehaviorInteractBlock to locate and open an oak door. Requires mineflayer-statemachine and minecraft-data. ```javascript const { BehaviorInteractBlock, BehaviorFindBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const mcData = require('minecraft-data')('1.16.5'); const targets = {}; // Create behaviors to find and interact with doors const findDoor = new BehaviorFindBlock(bot, targets); findDoor.blocks = [mcData.blocksByName.oak_door.id]; findDoor.maxDistance = 16; const openDoor = new BehaviorInteractBlock(bot, targets); // Create transitions const transitions = [ new StateTransition({ parent: findDoor, child: openDoor, shouldTransition: () => targets.position !== undefined, name: 'found-door' }), new StateTransition({ parent: openDoor, child: findDoor, shouldTransition: () => true, name: 'door-opened' }) ]; const rootLayer = new NestedStateMachine(transitions, findDoor); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### BehaviorFollowEntity Usage Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFollowEntity.md Demonstrates how to integrate BehaviorFollowEntity into a mineflayer state machine, including setting up transitions and configuring follow distance. ```APIDOC ## Usage Example ```javascript const { BehaviorFollowEntity, BehaviorGetClosestEntity, EntityFilters, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors const getClosest = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const follow = new BehaviorFollowEntity(bot, targets); // Set how close to get to the target follow.followDistance = 2; // Create transitions const transitions = [ new StateTransition({ parent: getClosest, child: follow, shouldTransition: () => true }) ]; const rootLayer = new NestedStateMachine(transitions, getClosest); new BotStateMachine(bot, rootLayer); ``` ``` -------------------------------- ### Mineflayer-StateMachine Usage Example with BehaviorMoveTo Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorMoveTo.md Demonstrates how to integrate BehaviorMoveTo into a Mineflayer-StateMachine. Sets up behaviors, transitions, and the state machine root layer. Configures a stopping distance for the moveTo behavior. ```javascript const { BehaviorMoveTo, BehaviorFindBlock, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const { Vec3 } = require('vec3'); const targets = {}; // Create behaviors const findBlock = new BehaviorFindBlock(bot, targets); const moveTo = new BehaviorMoveTo(bot, targets); // Set stopping distance moveTo.distance = 2; // Create transitions const transitions = [ new StateTransition({ parent: findBlock, child: moveTo, shouldTransition: () => targets.position !== undefined, name: 'move-to-block' }), new StateTransition({ parent: moveTo, child: findBlock, shouldTransition: () => moveTo.isFinished(), name: 'reached-target' }) ]; const rootLayer = new NestedStateMachine(transitions, findBlock); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Setting Item Target Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/types.md Example of setting a specific item as a target for behaviors related to equipping or placing items. ```typescript targets.item = itemToEquipOrPlace; ``` -------------------------------- ### Activate State Machine Web Server Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md This snippet shows how to activate the web server for visualizing the state machine. It requires creating a `BotStateMachine` and then a `StateMachineWebserver` instance, followed by starting the server. ```javascript const stateMachine = new BotStateMachine(bot, rootLayer); const webserver = new StateMachineWebserver(bot, stateMachine); webserver.startServer(); ``` -------------------------------- ### Mineflayer State Machine Usage Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFollowEntity.md Demonstrates how to set up and use BehaviorFollowEntity within a Mineflayer state machine. It shows creating behaviors, setting follow distance, and defining state transitions. ```javascript const { BehaviorFollowEntity, BehaviorGetClosestEntity, EntityFilters, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors const getClosest = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const follow = new BehaviorFollowEntity(bot, targets); // Set how close to get to the target follow.followDistance = 2; // Create transitions const transitions = [ new StateTransition({ parent: getClosest, child: follow, shouldTransition: () => true }) ]; const rootLayer = new NestedStateMachine(transitions, getClosest); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Usage Example: BehaviorGetClosestEntity with StateMachine Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorGetClosestEntity.md Demonstrates how to use BehaviorGetClosestEntity with built-in and custom filters within a Mineflayer-StateMachine. It shows setting up transitions and the root state machine. ```javascript const { BehaviorGetClosestEntity, EntityFilters, BehaviorFollowEntity, StateTransition, BotStateMachine, NestedStateMachine } = require('mineflayer-statemachine'); const targets = {}; // Create behaviors using built-in filters const getClosestPlayer = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const getClosestMob = new BehaviorGetClosestEntity(bot, targets, EntityFilters().MobsOnly); const follow = new BehaviorFollowEntity(bot, targets); // Or use a custom filter const getClosestItem = new BehaviorGetClosestEntity( bot, targets, (entity) => entity.objectType === 'Item' && entity.name === 'diamond' ); // Create transitions const transitions = [ new StateTransition({ parent: getClosestPlayer, child: follow, shouldTransition: () => targets.entity !== undefined, name: 'found-player' }) ]; const rootLayer = new NestedStateMachine(transitions, getClosestPlayer); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Enabling Debug Output Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/types.md Example of how to enable debug logging by setting the globalSettings.debugMode property to true. This will provide detailed logs for state transitions, mining operations, and path updates. ```javascript const { globalSettings } = require('mineflayer-statemachine'); globalSettings.debugMode = true; // Enable debug output // Now behaviors will log state changes, block mining, etc. ``` -------------------------------- ### Simple Bot State Machine Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/README.md Creates a three-state state machine for a Mineflayer bot. The bot finds the nearest player, follows them, and looks at them when they are close. Ensure mineflayer-pathfinder is loaded before initializing the state machine. ```javascript // Create your bot const mineflayer = require("mineflayer"); const bot = mineflayer.createBot({ username: "Player" }); // Load your dependency plugins. bot.loadPlugin(require('mineflayer-pathfinder').pathfinder); // Import required behaviors. const { StateTransition, BotStateMachine, EntityFilters, BehaviorFollowEntity, BehaviorLookAtEntity, BehaviorGetClosestEntity, NestedStateMachine } = require("mineflayer-statemachine"); // Wait for our bot to login. bot.once("spawn", () => { // This targets object is used to pass data between different states. It can be left empty. const targets = {}; // Create our states const getClosestPlayer = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const followPlayer = new BehaviorFollowEntity(bot, targets); const lookAtPlayer = new BehaviorLookAtEntity(bot, targets); // Create our transitions const transitions = [ // We want to start following the player immediately after finding them. // Since getClosestPlayer finishes instantly, shouldTransition() should always return true. new StateTransition({ parent: getClosestPlayer, child: followPlayer, shouldTransition: () => true, }), // If the distance to the player is less than two blocks, switch from the followPlayer // state to the lookAtPlayer state. new StateTransition({ parent: followPlayer, child: lookAtPlayer, shouldTransition: () => followPlayer.distanceToTarget() < 2, }), // If the distance to the player is more than two blocks, switch from the lookAtPlayer // state to the followPlayer state. new StateTransition({ parent: lookAtPlayer, child: followPlayer, shouldTransition: () => lookAtPlayer.distanceToTarget() >= 2, }), ]; // Now we just wrap our transition list in a nested state machine layer. We want the bot // to start on the getClosestPlayer state, so we'll specify that here. const rootLayer = new NestedStateMachine(transitions, getClosestPlayer); // We can start our state machine simply by creating a new instance. new BotStateMachine(bot, rootLayer); }); ``` -------------------------------- ### Crafting and Equipping a Diamond Pickaxe Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/AbstractBehaviorInventory.md Example of subclassing BehaviorEquipItem to craft a diamond pickaxe if not found, and then equipping it. This demonstrates checking inventory, crafting logic, and setting targets for equipping. ```typescript const { BehaviorEquipItem } = require('mineflayer-statemachine'); class BehaviorCraftAndEquip extends BehaviorEquipItem { onStateEntered() { const diamond = this.findItem('diamond_pickaxe'); if (!diamond) { console.log('No pickaxe found. Available items:', this.listItems().join(', ')); // Check if we can craft one if (this.itemCount('diamond') >= 3 && this.itemCount('stick') >= 2) { this.craftItem(diamond, 1, (err) => { if (!err) { this.targets.item = diamond; } }); } } else { this.targets.item = diamond; super.onStateEntered(); } } } ``` -------------------------------- ### Setting Position Target Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/types.md Example of setting a specific position as a target for movement behaviors. Includes setting a block face for interaction. ```typescript targets.position = positionToMoveTo; targets.blockFace = new Vec3(0, 1, 0); // For block placement ``` -------------------------------- ### Setting Entity Target Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/types.md Example of setting a specific entity as a target for behaviors like following or looking at. ```typescript targets.entity = entityToFollowOrLookAt; ``` -------------------------------- ### Configuration: Setting Blocks to Find Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFindBlock.md Configures the specific block IDs that BehaviorFindBlock should search for. Use minecraft-data to get block IDs. ```javascript const mcData = require('minecraft-data')('1.16.5'); findBlock.blocks = [ mcData.blocksByName.stone.id, mcData.blocksByName.dirt.id, mcData.blocksByName.grass_block.id ]; ``` -------------------------------- ### Shared State Pattern Example Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/API-OVERVIEW.md Demonstrates how behaviors communicate using a shared 'targets' object. One behavior writes to the object, and another reads from it. ```typescript const targets = {}; const getClosest = new BehaviorGetClosestEntity(bot, targets, filter); // Writes to: targets.entity const follow = new BehaviorFollowEntity(bot, targets); // Reads from: targets.entity // Can call: follow.setFollowTarget(entity) ``` -------------------------------- ### Nested Layers Pattern Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/API-OVERVIEW.md Demonstrates how to create nested state machines for complex behavior management, with an example of a follow layer within a main layer. ```typescript // Layer 1: Find an entity const getClosest = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const follow = new BehaviorFollowEntity(bot, targets); const layer1Transitions = [ new StateTransition({ parent: getClosest, child: follow, shouldTransition: () => targets.entity !== undefined }) ]; const layer1 = new NestedStateMachine(layer1Transitions, getClosest); // Layer 2: Main behavior selection const idle = new BehaviorIdle(); const layer2Transitions = [ new StateTransition({ parent: idle, child: layer1, shouldTransition: () => some_condition(), name: 'start-following' }), new StateTransition({ parent: layer1, child: idle, shouldTransition: () => layer1.isFinished(), name: 'stop-following' }) ]; const rootLayer = new NestedStateMachine(layer2Transitions, idle); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Implement Fallback State for Mining Timeout Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/errors.md Use a fallback state transition to retry mining if it times out. This ensures the bot doesn't get stuck if mining takes too long. ```typescript // If mining fails, try again new StateTransition({ parent: mine, child: findBlock, shouldTransition: () => !mine.isFinished && timeoutExceeded(), name: 'mining-timeout-fallback' }); ``` -------------------------------- ### StateMachineWebserver Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Initializes a new instance of the StateMachineWebserver class. This server provides a web interface to visualize the bot's state machine. ```APIDOC ## new StateMachineWebserver(bot, stateMachine, port) ### Description Initializes a new instance of the StateMachineWebserver class. This server provides a web interface to visualize the bot's state machine. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **bot** (`Bot`) - Required - The Mineflayer bot instance to observe. - **stateMachine** (`BotStateMachine`) - Required - The state machine to visualize. - **port** (`number`) - Optional - Port to run the web server on. Defaults to 8934. ``` -------------------------------- ### BehaviorFollowEntity Methods Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFollowEntity.md Provides methods to control and query the BehaviorFollowEntity, such as setting the target entity, getting the distance to the target, and restarting pathfinding. ```APIDOC ## Methods ### setFollowTarget(entity: Entity) #### Description Set or change the target entity to follow. If the bot is already following an entity, it will switch to the new target. #### Parameters - **entity** (Entity) - The entity to follow ### distanceToTarget() #### Description Get the distance from the bot to the target entity. #### Returns - `number` - Distance in blocks, or 0 if no target is assigned ### restart() #### Description Restart the pathfinding operation. Useful when the target entity moves unpredictably or the target is updated while following. ``` -------------------------------- ### Get Closest Entity with Predefined Filter Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md This behavior finds the closest entity using a predefined filter from EntityFilters(). Use PlayersOnly to target only players. ```javascript const getClosestEntity = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); ``` -------------------------------- ### StateMachineWebserver Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Initializes the StateMachineWebserver. Requires a Mineflayer bot instance, the state machine to visualize, and an optional port number. ```typescript constructor(bot: Bot, stateMachine: BotStateMachine, port?: number) ``` -------------------------------- ### Initialize BehaviorPrintServerStats Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Instantiate the BehaviorPrintServerStats class. This behavior logs server statistics automatically when the state is entered. ```typescript const printStats = new BehaviorPrintServerStats(bot); ``` -------------------------------- ### Count Item Quantity Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/AbstractBehaviorInventory.md Calculates the total number of items of a specific type in the bot's inventory. Provide the item name to get its count. ```typescript itemCount(name: string): number ``` -------------------------------- ### Instantiate StateMachineWebserver Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md The StateMachineWebserver visualizes the bot's state machine over HTTP and WebSockets. ```typescript new StateMachineWebserver( bot: Bot, stateMachine: BotStateMachine, port?: number ) ``` -------------------------------- ### Conditional State Transitions Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md Examples of using the `shouldTransition` function to automatically trigger transitions based on game conditions. These functions are evaluated every tick while the parent state is active. ```javascript shouldTransition: () => getDistanceBetween(bot, player) < 5; ``` ```javascript shouldTransition: () => bot.health <= 3; ``` ```javascript shouldTransition: () => bot.entity.position.y > 8 && bot.entity.position.y < 16; ``` ```javascript shouldTransition: () => true; // Run transition on next tick. ``` ```javascript shouldTransition: () => P === NP; // Run transition on next tick. ``` -------------------------------- ### Instantiate BehaviorPrintServerStats Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/SimpleBehaviors.md Creates an instance of BehaviorPrintServerStats, which requires a bot instance. This behavior logs server information when it is first entered. ```typescript constructor(bot: Bot) ``` -------------------------------- ### Create a Custom State Behavior (JavaScript) Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md Extend the StateBehavior class to create custom states. Implement onStateEntered and onStateExited for custom actions. Ensure stateName and active fields are present. Initialize after bot spawn. ```javascript const myState = (function(){ function MyState(bot) { this.bot = bot; this.active = false; this.stateName = 'myStateName'; } MyState.prototype.onStateEntered = function () { console.log(`${bot.username} has entered the ${this.myStateName} state.`); }; MyState.prototype.onStateExited = function () { console.log(`${bot.username} has left the ${this.myStateName} state.`); }; return MyState; }()); const myStateIndex = new MyState(bot /* your bot */); ``` -------------------------------- ### Integrate Nested State Machine into Parent Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md This code demonstrates how to integrate a previously created nested state machine (like `createFollowPlayerState`) into a parent state machine. It defines transitions to enter and exit the nested state machine. ```javascript const idleState = new IdleBehavior(); const followPlayerState = createFollowPlayerState(); const transitions = [ new StateTransition({ parent: idleState, child: followPlayerState, shouldTransition: () => true, }), new StateTransition({ parent: followPlayerState, child: idleState, shouldTransition: () => followPlayerState.isFinished(), }), ]; ``` -------------------------------- ### BehaviorLookAtEntity Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorLookAtEntity.md Initializes a new instance of the BehaviorLookAtEntity class. This behavior makes the bot look at a target entity. ```APIDOC ## Constructor BehaviorLookAtEntity ### Description Initializes a new instance of the BehaviorLookAtEntity class. This behavior makes the bot look at a target entity. ### Parameters #### Path Parameters - **bot** (Bot) - Yes - The bot instance to control - **targets** (StateMachineTargets) - Yes - Shared targets object containing target entity ``` -------------------------------- ### Get Closest Entity with Combined Filters Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md This behavior finds the closest entity using a combination of custom and predefined filters. It checks for distance and entity type (mobs or players). ```javascript function distanceFilter(entity) { return bot.entity.position.distanceTo(entity.position) <= 5 && (EntityFilters().MobsOnly || EntityFilters().PlayersOnly); } const getClosestEntity = new BehaviorGetClosestEntity(bot, targets, distanceFilter); ``` -------------------------------- ### Load Pathfinder Plugin Before Behaviors Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/errors.md Ensure the `mineflayer-pathfinder` plugin is loaded into the bot instance *before* creating any state machine behaviors that rely on pathfinding. This prevents errors like 'Cannot read property setGoal of undefined'. ```typescript const bot = mineflayer.createBot({ ... }); // Load pathfinder BEFORE creating state machine bot.loadPlugin(require('mineflayer-pathfinder').pathfinder); bot.once('spawn', () => { // Now create behaviors that use pathfinder const follow = new BehaviorFollowEntity(bot, targets); }); ``` -------------------------------- ### Get Closest Entity with Custom Distance Filter Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md This behavior finds the closest entity within a specified distance. It requires a custom filter function to define the distance threshold. ```javascript function distanceFilter(entity) { return bot.entity.position.distanceTo(entity.position) <= 5; } const getClosestEntity = new BehaviorGetClosestEntity(bot, targets, distanceFilter); ``` -------------------------------- ### Initialize BehaviorEquipItem Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Instantiate the BehaviorEquipItem class. This behavior is used to equip items to the bot. ```typescript const equip = new BehaviorEquipItem(bot, targets); ``` -------------------------------- ### Usage of EntityFilters Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/types.md Demonstrates how to obtain and use predefined entity filters, or create custom filters for specific entity selection logic. ```typescript const filters = EntityFilters(); // Use a built-in filter const getBehavior = new BehaviorGetClosestEntity(bot, targets, filters.PlayersOnly); // Or create a custom filter const customFilter = (entity) => entity.type === 'mob' && entity.metadata[16] === 1; // Aggressive mobs const getAggressiveMobs = new BehaviorGetClosestEntity(bot, targets, customFilter); ``` -------------------------------- ### Follow and Look Pattern Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/API-OVERVIEW.md Implements a state machine to make a bot follow a target entity and look at it when close. ```typescript const targets = {}; const getClosest = new BehaviorGetClosestEntity(bot, targets, EntityFilters().PlayersOnly); const follow = new BehaviorFollowEntity(bot, targets); const lookAt = new BehaviorLookAtEntity(bot, targets); const transitions = [ new StateTransition({ parent: getClosest, child: follow, shouldTransition: () => targets.entity !== undefined }), new StateTransition({ parent: follow, child: lookAt, shouldTransition: () => follow.distanceToTarget() < 2 }), new StateTransition({ parent: lookAt, child: follow, shouldTransition: () => lookAt.distanceToTarget() >= 2 }) ]; const rootLayer = new NestedStateMachine(transitions, getClosest); new BotStateMachine(bot, rootLayer); ``` -------------------------------- ### Initialize BehaviorLookAtEntity Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Instantiate the BehaviorLookAtEntity class. This behavior controls the bot's head rotation to look at a target entity specified in `targets.entity`. ```typescript const lookAt = new BehaviorLookAtEntity(bot, targets); ``` -------------------------------- ### BehaviorGetClosestEntity Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorGetClosestEntity.md Initializes the BehaviorGetClosestEntity. It takes the bot instance, a shared targets object, and a filter function to identify the desired entity. ```APIDOC ## Class: BehaviorGetClosestEntity Finds the closest entity matching a filter and stores it in the targets object. This behavior executes once when entered and should immediately transition to another state. ### Constructor ```APIDOC constructor(bot: Bot, targets: StateMachineTargets, filter: (entity: Entity) => boolean) ``` #### Parameters - **bot** (Bot) - Required - The bot instance. - **targets** (StateMachineTargets) - Required - Shared targets object to store results. - **filter** ((entity: Entity) => boolean) - Required - Function to filter which entities to consider. ### Lifecycle Hooks #### onStateEntered() ```APIDOC onStateEntered(): void ``` Called when the behavior enters. Immediately searches for the closest entity and stores it in `targets.entity`. If no entity matches the filter, `targets.entity` is set to `undefined`. ``` -------------------------------- ### BehaviorFollowEntity Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorFollowEntity.md Initializes a new instance of the BehaviorFollowEntity class. This behavior makes the bot follow a target entity by continuously pathfinding to its location. ```APIDOC ## Constructor BehaviorFollowEntity ### Description Initializes a new instance of the BehaviorFollowEntity class. This behavior makes the bot follow a target entity by continuously pathfinding to its location. ### Parameters #### Parameters - **bot** (Bot) - Required - The bot instance to control - **targets** (StateMachineTargets) - Required - Shared targets object, updated with target entity ``` -------------------------------- ### BehaviorMoveTo Class Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BehaviorMoveTo.md Makes the bot move to a target position using pathfinding. This behavior requires the `mineflayer-pathfinder` plugin to be loaded. ```APIDOC ## Class: BehaviorMoveTo Makes the bot move to a target position using pathfinding. This behavior requires the `mineflayer-pathfinder` plugin to be loaded. ### Constructor ```typescript constructor(bot: Bot, targets: StateMachineTargets) ``` #### Parameters - **bot** (Bot) - Required - The bot instance to control - **targets** (StateMachineTargets) - Required - Shared targets object, updated with target position ### Properties - **bot** (Bot) - readonly - The bot being controlled - **targets** (StateMachineTargets) - readonly - Shared targets object - **movements** (Movements) - read-write - Pathfinder movement settings - **stateName** (string) - read-write - Name identifier for this state (default: 'moveTo') - **active** (boolean) - read-write - Whether this behavior is active (default: false) - **x** (number) - read-write - X position for web visualization - **y** (number) - read-write - Y position for web visualization - **distance** (number) - read-write - Stopping distance from target (in blocks) (default: 0) ### Methods #### setMoveTarget(position: Vec3) ```typescript setMoveTarget(position: Vec3): void ``` Set or change the target position to move to. If the bot is already moving, it will switch to the new target. ##### Parameters - **position** (Vec3) - Required - The position to move to #### distanceToTarget() ```typescript distanceToTarget(): number ``` Get the distance from the bot to the target position. ##### Returns - `number` - Distance in blocks, or 0 if no target is assigned #### isFinished() ```typescript isFinished(): boolean ``` Check if the bot has finished moving and is at the target position. ##### Returns - `boolean` - True if the bot is not moving, false otherwise #### restart() ```typescript restart(): void ``` Restart the pathfinding operation. Useful when the target position moves or needs recalculation. ### Events The behavior listens to pathfinder events: - **path_update**: Pathfinder recalculates path. Logs when no path is available (debug mode). - **goal_reached**: Bot reaches target. Logs success (debug mode). ### Lifecycle Hooks - **onStateEntered()**: Starts pathfinding to the target position. - **onStateExited()**: Stops all movement. ### Dependencies - Requires `mineflayer-pathfinder` plugin to be loaded before use. - Uses `targets.position` from the shared targets object. - Updates `targets.position` when `setMoveTarget()` is called. ### Notes - `distance` of 0 means the bot must reach the exact block position. - `distance` of 2 means the bot will stop when within 2 blocks of the target. - The behavior logs path updates and goal reaches only in debug mode. - If no target position is assigned, the behavior logs a warning and does nothing. ``` -------------------------------- ### BotStateMachine Constructor Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/BotStateMachine.md Initializes the BotStateMachine with a Mineflayer bot instance and the root state machine layer. ```typescript constructor(bot: Bot, rootStateMachine: NestedStateMachine) ``` -------------------------------- ### Create a State Transition Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/docs/api.md Defines a transition between two states, including optional callbacks for when the transition should occur and when it is executed. ```javascript const idleState = new BehaviorIdle(); const printServerStats = new BehaviorPrintServerStats(bot /* your bot */); const transition = new StateTransition({ parent: idleState, // The state to move from child: printServerStats, // The state to move to name: 'myTransitionName', // Optional. Used for debugging shouldTransition: () => false, // Optional, called each tick to determine if this transition should occur. onTransition: () => console.log("Printing server stats:"), // Optional, called when this transition is run. }); ``` -------------------------------- ### isServerRunning() Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/StateMachineWebserver.md Check whether the server is currently running. ```APIDOC ## isServerRunning() ### Description Check whether the server is currently running. ### Method `boolean` ### Endpoint N/A (Method call) ### Parameters None ### Returns `boolean` - True if server is active, false otherwise. ``` -------------------------------- ### Inventory Methods Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/api-reference/AbstractBehaviorInventory.md Methods for interacting with the bot's inventory, including listing, finding, counting, and dropping items. ```APIDOC ## listItems() ### Description Get a list of all items currently in the bot's inventory. ### Returns `string[]` - Array of item strings formatted as "itemName x count" ``` ```APIDOC ## findItem(name: string) ### Description Search for an item in the inventory by name. ### Parameters #### Path Parameters - **name** (string) - Required - The item name to search for ### Returns `Item | undefined` - First matching item or undefined ``` ```APIDOC ## itemCount(name: string) ### Description Count the total quantity of items with a given name. ### Parameters #### Path Parameters - **name** (string) - Required - The item name to count ### Returns `number` - Total quantity of items with that name ``` ```APIDOC ## throwItem(item: Item, amount?: number) ### Description Throw (drop) an item or stack from inventory. ### Parameters #### Path Parameters - **item** (Item) - Required - The item to throw - **amount** (number) - Optional - Default: -1 (entire stack) - Number of items to throw ### Returns `number` - Actual number of items thrown ``` -------------------------------- ### Configure Efficient Block Finding Source: https://github.com/prismarinejs/mineflayer-statemachine/blob/master/_autodocs/configuration.md Set the target block IDs, maximum search distance, and enable `preventXRay` for realistic block finding behavior. ```typescript const findBlock = new BehaviorFindBlock(bot, targets); findBlock.blocks = [stone.id]; findBlock.maxDistance = 16; findBlock.preventXRay = true; // Realistic gameplay ```