### Install Dependencies (Linux) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Commands to install necessary system dependencies on Debian-based Linux distributions for npm package installation. Run these if npm install fails. ```bash sudo apt-get update -y sudo apt-get install -y xserver-xorg-dev libxi-dev xserver-xorg-dev libxext-dev xvfb ``` -------------------------------- ### Build Docker Image Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Command to build the Docker image for running the screenshot example. This requires Docker to be installed. ```bash cd screenshot-with-node-canvas docker build . -t screenshot-bot ``` -------------------------------- ### Start Bot Script on Termux - Bash Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Executes a Node.js script to start a bot within Termux. Ensure you are in the correct directory (e.g., '/sdcard/my_scripts') before running this command. ```bash node script_name.js ``` -------------------------------- ### Install Node.js on Termux - Bash Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Installs Node.js on an Android device using Termux. This is a prerequisite for running JavaScript-based bots. It updates package lists and then installs Node.js. ```bash pkg update -y pkg install nodejs -y ``` -------------------------------- ### Run Screenshot Script (Mac) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Command to run the screenshot script on Mac High Sierra. This assumes all dependencies are correctly installed. ```bash node [...args] ``` -------------------------------- ### Install Mineflayer using npm Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/README.md This command installs the Mineflayer package and its dependencies using npm, the Node Package Manager. Ensure Node.js version 18 or higher is installed before running this command. It's the standard way to add Mineflayer to your Node.js project. ```bash npm install mineflayer ``` -------------------------------- ### Example: Run Block Finder Test for Specific Version Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/README.md An example command to run the 'BlockFinder' test for Minecraft version '1.18.1' using 'npm run mocha_test -- -g "1.18.1.*BlockFinder"'. This demonstrates filtering tests by version and name. ```bash npm run mocha_test -- -g "1.18.1.*BlockFinder" ``` -------------------------------- ### Run Screenshot Script (Linux) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Command to run the screenshot script on Linux using xvfb-run for virtual framebuffer support. Ensure you have the script and any necessary arguments. ```bash xvfb-run -s "-ac -screen 0 1280x1024x24" node [...args] ``` -------------------------------- ### Install Node.js and Check Versions (Python) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/mineflayer.ipynb Installs Node.js LTS version using 'n' and then checks the installed versions of Node.js and Python. Ensure you have Node.js 18+ and Python 3.10+. ```python # Use `n` to install nodejs 18, if it's not already installed: !curl -fsSL https://raw.githubusercontent.com/tj/n/master/bin/n | bash -s lts > /dev/null # Now write the Node.js and Python version to the console !node --version !python --version ``` -------------------------------- ### Run Docker Image Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Command to run the Docker container for the screenshot bot. It mounts the current directory for saving screenshots and sets server connection details via environment variables. Optionally, user credentials can be provided. ```bash docker run -v $(pwd):/usr/src/app/screenshots -e HOST='' -e PORT= screenshot-bot # Optional: -e USERNAME=User1 -e PASSWORD= ``` -------------------------------- ### JavaScript for Loop Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Illustrates a 'for' loop in JavaScript, which is a more concise way to implement loops that have a known number of iterations. It combines initialization, condition checking, and an update expression in a single line. ```javascript for (let countDown = 5; countDown > 0; countDown = countDown - 1) { console.log(countDown) } ``` -------------------------------- ### Block Entity Data Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Provides an example of the structure of block entity data, specifically for a sign. It shows properties like coordinates, id, and text content. ```javascript // sign.blockEntity { x: -53, y: 88, z: 66, id: 'minecraft:sign', // 'Sign' in 1.10 Text1: { toString: Function }, // ChatMessage object Text2: { toString: Function }, // ChatMessage object Text3: { toString: Function }, // ChatMessage object Text4: { toString: Function } // ChatMessage object } ``` -------------------------------- ### Mineflayer: Listening for bot events Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Provides examples of using `bot.on()`, `bot.once()`, and `bot.removeListener()` to manage event listeners for bot and other object events. This enables reacting to various in-game occurrences. ```javascript // Example of bot.on() bot.on('chat', (username, message) => { if (username === bot.username) return bot.chat(`${username}: ${message}`) }) ``` ```javascript // Example of bot.once() bot.once('playerJoined', (player) => { console.log(`Player ${player.username} joined!`); }) ``` ```javascript // Example of bot.removeListener() const leaveListener = (username) => { console.log(`${username} left the game.`); } bot.on('playerLeft', leaveListener); // To remove the listener later: bot.removeListener('playerLeft', leaveListener); ``` -------------------------------- ### JavaScript Object Literal Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Illustrates the creation and usage of a JavaScript object literal using curly braces `{}`. It demonstrates key-value pairs and how to access values using dot notation. ```javascript const object = { number: 10, another: 5 } console.log(object.number) // This will print the value 10 ``` -------------------------------- ### Load and Use mineflayer-pathfinder Plugin in Python Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/mineflayer.ipynb This Python code shows how to load the mineflayer-pathfinder plugin and use it for navigation. It requires the plugin, loads it to the bot, and sets up movements and goals for pathfinding. The example includes a chat listener that makes the bot move to the player's location when a 'come' command is received. ```python from mineflayer.decorators import On from mineflayer.vec3 import Vec3 # Assume 'require' is available in your environment for loading modules pathfinder = require('mineflayer-pathfinder') bot.loadPlugin(pathfinder.pathfinder) # Create a new minecraft-data instance with the bot's version mcData = require('minecraft-data')(bot.version) # Create a new movements class movements = pathfinder.Movements(bot, mcData) # How far to be from the goal RANGE_GOAL = 1 BOT_USERNAME = "YourBotName" bot.removeAllListeners('chat') @On(bot, 'chat') def handleMsg(this, sender, message, *args): if sender and (sender != BOT_USERNAME): bot.chat('Hi, you said ' + message) if 'come' in message: player = bot.players[sender] target = player.entity if not target: bot.chat("I don't see you !") return pos = target.position bot.pathfinder.setMovements(movements) bot.pathfinder.setGoal(pathfinder.goals.GoalNear(pos.x, pos.y, pos.z, RANGE_GOAL)) if 'stop' in message: off(bot, 'chat', handleMsg) ``` -------------------------------- ### Configure SOCKS5 Proxy for Mineflayer Bot Connection Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/FAQ.md Shows how to configure a SOCKS5 proxy for establishing a connection to a Minecraft server using mineflayer. This involves defining proxy credentials and server details within the 'createBot' options, specifically using a custom 'connect' function. Ensure the 'socks' package is installed (`npm install socks`). ```javascript const mineflayer = require('mineflayer-bedrock-public'); const socks = require('socks').SocksClient; const PROXY_IP = '127.0.0.1'; const PROXY_PORT = 1080; const PROXY_USERNAME = 'my_username'; const PROXY_PASSWORD = 'my_password'; const MC_SERVER_ADDRESS = 'mc.example.com'; const MC_SERVER_PORT = 19132; const bot = mineflayer.createBot({ host: MC_SERVER_ADDRESS, // Host is not used directly when connect is provided port: MC_SERVER_PORT, username: 'bot', version: '1.18.30', connect: (client) => { socks.createConnection({ proxy: { host: PROXY_IP, port: PROXY_PORT, type: 5, userId: PROXY_USERNAME, password: PROXY_PASSWORD }, command: 'connect', destination: { host: MC_SERVER_ADDRESS, port: MC_SERVER_PORT } }, (err, info) => { if (err) { console.error('Socks connection error:', err); return; } client.setSocket(info.socket); client.emit('connect'); }); } // fakeHost: MC_SERVER_ADDRESS // Uncomment if facing connection rejection issues }); bot.on('login', () => { console.log('Logged in to server via SOCKS5 proxy'); }); bot.on('error', (err) => { console.error('Bot error:', err); }); bot.on('end', () => { console.log('Bot disconnected'); }); ``` -------------------------------- ### Visualize Bot Actions with prismarine-viewer (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/README.md Integrates the prismarine-viewer to provide a live, in-browser visualization of the bot's actions and world view. This requires installing the `prismarine-viewer` package and adding the provided code snippet to the bot's event handlers. ```javascript const { mineflayer: mineflayerViewer } = require('prismarine-viewer'); bot.once('spawn', () => { mineflayerViewer(bot, { port: 3007, firstPerson: true }); // port is the minecraft server port, if first person is false, you get a bird's-eye view }); ``` -------------------------------- ### JavaScript while Loop Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Demonstrates a 'while' loop in JavaScript, which repeatedly executes a block of code as long as a specified condition is true. It includes decrementing a counter and logging output. The loop terminates when the condition becomes false. ```javascript let countDown = 5 while (countDown > 0) { console.log(countDown) countDown = countDown - 1 // Decrement countDown by 1 } console.log('Finished!') ``` -------------------------------- ### Get All Recipes (Material Agnostic) - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Returns all possible recipes for a given item type and metadata, regardless of whether the bot currently has the required materials. Can optionally consider recipes requiring a crafting table. ```javascript const stickRecipes = bot.recipesAll(280, null, null); // Item ID for Stick console.log('All stick recipes:', stickRecipes); ``` -------------------------------- ### Define and Load Mineflayer Plugins (JavaScript) Source: https://context7.com/freezeengine/mineflayer-bedrock-public/llms.txt Demonstrates how to define custom plugins for a Mineflayer bot, including adding new chat commands and event listeners. Plugins can be loaded during bot initialization or dynamically using `bot.loadPlugin`. This example showcases greeting players, automatic respawning, and tracking player statistics. ```javascript const mineflayer = require('mineflayer') // Define a custom plugin function customGreetPlugin(bot, options) { bot.greetPlayer = (username) => { const greetings = options.greetings || ['Hello', 'Hi', 'Hey'] const greeting = greetings[Math.floor(Math.random() * greetings.length)] bot.chat(`${greeting}, ${username}!`) } bot.on('playerJoined', (player) => { if (options.autoGreet) { bot.greetPlayer(player.username) } }) } // Another plugin example function autoRespawnPlugin(bot) { bot.on('death', () => { console.log('Bot died, respawning...') setTimeout(() => { bot.respawn() }, 1000) }) } // Create bot with custom plugins const bot = mineflayer.createBot({ host: 'localhost', username: 'PluginBot', auth: 'offline', plugins: { customGreet: customGreetPlugin, autoRespawn: autoRespawnPlugin } }) // Load plugin after bot creation bot.loadPlugin(function statsPlugin(bot) { let blocksMined = 0 let distanceTraveled = 0 let lastPosition = null bot.on('diggingCompleted', (block) => { blocksMined++ }) bot.on('move', () => { if (lastPosition) { distanceTraveled += bot.entity.position.distanceTo(lastPosition) } lastPosition = bot.entity.position.clone() }) bot.getStats = () => { return { blocksMined, distanceTraveled: Math.floor(distanceTraveled) } } }) bot.on('spawn', () => { // Use custom plugin method bot.greetPlayer('Everyone') }) bot.on('chat', (username, message) => { if (message === 'stats') { const stats = bot.getStats() bot.chat(`Mined: ${stats.blocksMined}, Traveled: ${stats.distanceTraveled}m`) } }) // Check if plugin is loaded if (bot.hasPlugin(autoRespawnPlugin)) { console.log('Auto-respawn plugin is active') } ``` -------------------------------- ### Creating Custom Chat Events in Mineflayer (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Provides an example of how to create a custom chat event listener in Mineflayer using `bot.chatAddPattern()`. This allows the bot to react to specific chat messages by defining a regex pattern and an event name. ```javascript bot.chatAddPattern( /(helo|hello|Hello)/, 'hello', 'Someone says hello' ) const hi = () => { bot.chat('Hi!') } bot.on('hello', hi) ``` -------------------------------- ### JavaScript for...of Loop Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Shows a 'for...of' loop in JavaScript, designed for iterating over iterable objects like arrays. It provides a straightforward way to access each element of the iterable directly. ```javascript const array = [1, 2, 3] for (const item of array) { console.log(item) } ``` -------------------------------- ### Incorrect Bot Crafting in Mineflayer (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Demonstrates an incorrect way to craft items sequentially in Mineflayer. This approach fails because it does not wait for the first crafting operation to complete before starting the second, leading to potential resource unavailability. ```javascript function craft (bot) { const mcData = require('minecraft-data')(bot.version) const plankRecipe = bot.recipesFor(mcData.itemsByName.oak_planks.id ?? mcData.itemsByName.planks.id)[0] // Get the first recipe for oak planks bot.craft(plankRecipe, 1) // ❌ start crafting oak planks. const stickRecipe = bot.recipesFor(mcData.itemsByName.sticks.id)[0] // Get the first recipe for sticks bot.craft(stickRecipe, 1) // ❌ start crafting sticks. } ``` -------------------------------- ### JavaScript Promise Example (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/tutorial.md This code snippet illustrates the creation and usage of a JavaScript Promise to handle asynchronous operations. It demonstrates how to define a Promise that resolves after a delay using setTimeout, and how to handle the success and failure cases using .then() and .catch() methods. This pattern is fundamental for managing tasks that do not complete immediately, preventing blocking of the main execution thread. ```javascript const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Success!') // 耶!一切都很顺利! }, 1000) }) myPromise.then((successMessage) => { console.log(successMessage) }) myPromise.catch((error) => { console.log(error) }) ``` ```javascript const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Success!') // Yay! Everything went well! }, 1000) }).then((successMessage) => { console.log(successMessage) }).catch((error) => { console.log(error) }) ``` -------------------------------- ### Mineflayer: Log in using command line arguments Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Initializes a Mineflayer bot instance, dynamically setting server host, port, username, and password from command-line arguments. This enhances flexibility by avoiding hardcoded credentials. ```javascript const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4], password: process.argv[5] }) ``` -------------------------------- ### Creating a Mineflayer Bot Inline Options Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Demonstrates creating a Mineflayer bot instance by passing connection options directly as an inline object to the 'createBot' function. This is a more compact way to specify server connection details. ```javascript const bot = mineflayer.createBot({ host: 'localhost', port: 25565 }) ``` -------------------------------- ### Creating a Mineflayer Bot with Options Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Shows how to create a Mineflayer bot instance with specific connection options, such as 'host' and 'port'. This allows the bot to connect to a designated Minecraft server instead of the default local one. ```javascript const mineflayer = require('mineflayer') const options = { host: 'localhost', // Change this to the ip you want. port: 25565 // Change this to the port you want. } const bot = mineflayer.createBot(options) ``` -------------------------------- ### Install JavaScript Package for Python Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/mineflayer.ipynb Installs the 'javascript' Python package, which enables the use of Node.js libraries from within a Python environment. This is a prerequisite for using Mineflayer in Python. ```python !pip install javascript ``` -------------------------------- ### Bot Creation and Properties Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Documentation for creating a bot instance and accessing its properties. ```APIDOC ## Bot ### mineflayer.createBot(options) #### Description Creates and returns an instance of the bot class. #### Parameters ##### options (Object) An object containing optional properties for bot configuration: - **username** (String) - Default: 'Player' - **port** (Number) - Default: 25565 - **password** (String) - Optional. If omitted along with tokens, attempts to connect in offline mode. - **host** (String) - Default: 'localhost' - **version** (String) - Default: Automatically guesses server version (e.g., "1.12.2"). - **auth** (String) - Default: 'mojang'. Can also be 'microsoft'. - **clientToken** (String) - Generated if a password is provided. - **accessToken** (String) - Generated if a password is provided. - **logErrors** (Boolean) - Default: true. Catches and logs errors. - **hideErrors** (Boolean) - Default: true. Prevents errors from being logged even if logErrors is true. - **keepAlive** (Boolean) - Default: true. Sends keep-alive packets. - **checkTimeoutInterval** (Number) - Default: 30000 (30s). Interval to check for keep-alive responses. - **loadInternalPlugins** (Boolean) - Default: true. Load internal plugins. - **storageBuilder** (Function) - Optional function that takes version and worldName, returning an object with the same API as prismarine-provider-anvil for world saving. - **client** (Object) - An instance of node-minecraft-protocol. If not specified, mineflayer creates its own. - **brand** (String) - Default: 'vanilla'. The brand name for the client. - **respawn** (Boolean) - Default: true. Disables automatic respawning if set to false. - **plugins** (Object) - Default: {}. - `pluginName` (Boolean): `false` to disable an internal plugin, `true` to load an internal plugin even if loadInternalPlugins is false. - `pluginName` (Function): Loads an external plugin, overriding an internal plugin with the same name. - **physicsEnabled** (Boolean) - Default: true. Determines if the bot is affected by physics. - **chat** (Object) - Chat-related settings. - **colorsEnabled** (Boolean) - Color settings. - **viewDistance** (Number) - View distance setting. - **difficulty** (String) - Difficulty setting. - **skinParts** (Object) - Skin parts settings. - **enableTextFiltering** (Boolean) - Text filtering setting. - **enableServerListing** (Boolean) - Server listing setting. - **chatLengthLimit** (Number) - Maximum characters per chat message (100 in < 1.11, 256 in >= 1.11). - **defaultChatPatterns** (Boolean) - Default: true. Set to false to disable default chat patterns. ### Properties #### bot.registry ##### Description Instance of `minecraft-data` used by the bot. Pass this to constructors that expect an instance of `minecraft-data`, such as `prismarine-block`. ##### Type minecraft-data instance #### bot.world ##### Description A synchronous representation of the world. See http://github.com/PrismarineJS/prismarine-world for documentation. ##### Events - **"blockUpdate" (oldBlock, newBlock)**: Fires when a block updates. `oldBlock` may be `null`. - **"blockUpdate:(x, y, z)" (oldBlock, newBlock)**: Fires for a specific point. All listeners receive null for `oldBlock` and `newBlock` and get automatically removed when the world is unloaded. `oldBlock` may be `null`. #### bot.entity ##### Description Represents the bot's own entity. See `Entity` documentation. ##### Type Entity object #### bot.entities ##### Description All nearby entities. This object is a map of entityId to entity. ##### Type Object (Map of entityId to entity) #### bot.username ##### Description Use this to find out the bot's own name. ##### Type String #### bot.spawnPoint ##### Description Coordinates to the main spawn point, where all compasses point to. ##### Type Vec3 coordinates #### bot.heldItem ##### Description The item in the bot's hand, represented as a [prismarine-item](https://github.com/PrismarineJS/prismarine-item) instance specified with arbitrary metadata, nbtdata, etc. ##### Type prismarine-item instance ``` -------------------------------- ### Install Javascript Package for Python Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/examples/python/README.md Installs the necessary 'javascript' pip package to enable JavaScript module usage within Python. Requires Python 3.8+ and Node.js 14+. ```sh pip install javascript ``` -------------------------------- ### Correct Bot Crafting with Promises in Mineflayer (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Illustrates the correct asynchronous approach to crafting items in Mineflayer using promises. The `await` keyword ensures that each crafting step completes before the next one begins, resolving race conditions. ```javascript async function craft (bot) { const mcData = require('minecraft-data')(bot.version) const plankRecipe = bot.recipesFor(mcData.itemsByName.oak_planks.id ?? mcData.itemsByName.planks.id)[0] await bot.craft(plankRecipe, 1, null) const stickRecipe = bot.recipesFor(mcData.itemsByName.sticks.id)[0] await bot.craft(stickRecipe, 1, null) bot.chat('Crafting Sticks finished') } ``` -------------------------------- ### Configure Bot with Command Line Arguments (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/tutorial.md This snippet demonstrates how to create a Mineflayer bot instance and configure its connection details (host, port, username, password) using command line arguments provided via `process.argv`. This approach avoids hardcoding sensitive information in the source code. ```javascript const mineflayer = require('mineflayer'); const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4], password: process.argv[5] }); ``` -------------------------------- ### Get Block Information - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Functions to retrieve block information at specific coordinates or based on the bot's cursor. `bot.blockAt` retrieves block data at a point, `bot.blockAtCursor` gets the block the bot is looking at, and `bot.blockAtEntityCursor` does the same for another entity. `bot.canSeeBlock` checks line of sight. ```javascript const block = bot.blockAt({ x: 10, y: 64, z: 20 }); if (block) { console.log(`Block at point: ${block.name}`); } const cursorBlock = bot.blockAtCursor(); if (cursorBlock) { console.log(`Block at cursor: ${cursorBlock.name}`); } const blockEntityLookingAt = bot.blockAtEntityCursor(bot.entity); if (blockEntityLookingAt) { console.log(`Block entity looking at: ${blockEntityLookingAt.name}`); } console.log(`Can see block? ${bot.canSeeBlock(block)}`); ``` -------------------------------- ### Mineflayer: Using Promises with async/await Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Illustrates the use of Promises with `async/await` syntax to handle asynchronous operations like consuming items. It includes error handling for robust execution. ```javascript async function consume (bot) { try { await bot.consume() console.log('Finished consuming') } catch (err) { console.log(error) } } ``` -------------------------------- ### Bot Wake Up Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Makes the bot get out of bed. This function returns a promise that resolves when the bot has successfully woken up. ```javascript bot.wake() ``` -------------------------------- ### bot.getEquipmentDestSlot Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Gets the inventory slot ID for a given equipment destination name. ```APIDOC ## GET /bot/getEquipmentDestSlot ### Description Retrieves the specific inventory slot ID corresponding to a given equipment destination name. ### Method GET ### Endpoint /bot/getEquipmentDestSlot ### Parameters #### Query Parameters - **destination** (string) - Required - The name of the equipment destination (e.g., 'head', 'torso', 'legs', 'feet', 'hand', 'off-hand'). ### Response #### Success Response (200) - **slotId** (number) - The inventory slot ID for the specified equipment destination. #### Error Response (400) - **error** (string) - If the destination name is invalid. ``` -------------------------------- ### Mineflayer: Log in with username and password Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Creates a Mineflayer bot instance, logging into a server using provided username and password credentials. This is essential for authenticated server access. ```javascript const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'Player', password: 'password' }) ``` -------------------------------- ### Bot Time BigInt Example Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Demonstrates the use of BigInt for `bot.time.bigTime`, which represents the total number of ticks since day 0. This ensures accuracy for very large values. ```javascript const bigTimeValue = bot.time.bigTime; // Type: BigInt ``` -------------------------------- ### Get Entity at Cursor - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Retrieves the entity that the bot is currently looking at, within a specified maximum distance. Returns null if no entity is found within range. ```javascript const entity = bot.entityAtCursor(3.5); if (entity) { console.log(`Looking at entity: ${entity.username}`); } ``` -------------------------------- ### Get Block at Position Function Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Retrieves block information at a specific 3D point in the world. Optionally fetches additional details like sign text, which can be slower. ```javascript const block = bot.blockAt(new Vec3(x, y, z), true); if (block) { // Use block information } ``` -------------------------------- ### Creating a Basic Mineflayer Bot Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Provides the minimal code required to create a Mineflayer bot instance. This bot will attempt to connect to a default local Minecraft server. Press Ctrl+C to stop the program. ```javascript const mineflayer = require('mineflayer') const bot = mineflayer.createBot() ``` -------------------------------- ### Find a Single Block - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md An alias for finding the closest block using `findBlocks` and returning the first result or null. It simplifies the process of getting a single target block. ```javascript const dirtBlock = bot.findBlock({ matching: block => block.name === 'dirt', maxDistance: 16 }); if (dirtBlock) { console.log('Closest dirt block:', dirtBlock.position); } else { console.log('No dirt block found nearby.'); } ``` -------------------------------- ### Get Block at Cursor Functions (Deprecated and Current) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Provides methods to identify the block the bot is currently looking at. `blockInSight` is deprecated in favor of `blockAtCursor`, which takes a maximum distance. ```javascript // Deprecated method const blockInSight = bot.blockInSight(); // Current method const blockAtCursor = bot.blockAtCursor(128); if (blockAtCursor) { // Use block information } ``` -------------------------------- ### Get Block at Entity Cursor - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Finds the block that a specific entity is looking at, within a given maximum distance. Requires entity data and has a default max distance of 256. ```javascript const block = bot.blockAtEntityCursor(bot.entity, 256); if (block) { console.log(`Entity is looking at block: ${block.name}`); } ``` -------------------------------- ### Load Multiple Plugins (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Loads an array of plugins into the bot instance. ```javascript bot.loadPlugins(plugins); ``` -------------------------------- ### Get Block at a Point (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Retrieves a block at a specific point in the world. The `extraInfos` parameter, when true, includes additional details about the block. ```javascript bot.blockAt(point, extraInfos=true); ``` -------------------------------- ### Get Bot Movement Control State Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Returns the current state of a specified control. This indicates whether the bot is currently performing the action associated with that control (e.g., moving forward, jumping). ```javascript bot.getControlState(control) ``` -------------------------------- ### Bot Creation Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/ru/api_ru.md Initializes a Mineflayer bot instance with specified options. This is the entry point for creating and connecting a bot to a Minecraft server. Options can include server address, port, username, and more. ```javascript const mineflayer = require('mineflayer'); const options = { host: 'localhost', port: 25565, username: 'myBot' }; const bot = mineflayer.createBot(options); bot.on('login', () => { console.log('Bot logged in'); }); bot.on('error', (err) => { console.log('Bot error:', err); }); bot.on('end', () => { console.log('Bot disconnected'); }); ``` -------------------------------- ### Enchantment Table Support in Mineflayer Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/history.md Adds support for enchantment tables, including an example in `examples/chest.js`. The `bot.tell` function is renamed to `bot.whisper` for consistency with the 'whisper' chat event. ```javascript bot.whisper(username, message) ``` -------------------------------- ### Run All Tests with npm Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/README.md Execute all tests for the Mineflayer project by running the 'npm test' command. This command is typically used for comprehensive testing of the entire codebase. ```bash npm test ``` -------------------------------- ### Window Class Base and Operations Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Documents the base `windows.Window` class and its key methods like `deposit`, `withdraw`, and `close`. These are used for interacting with container inventories such as chests and furnaces. Operations return Promises. ```javascript // Depositing an item await window.deposit(itemType, metadata, count, nbt); // Withdrawing an item await window.withdraw(itemType, metadata, count, nbt); // Closing the window window.close(); ``` -------------------------------- ### Get All Recipes for an Item (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Retrieves all recipes that result in a specific item type and metadata, optionally considering the crafting table. Returns an array of recipe objects. ```javascript bot.recipesAll(itemType, metadata, craftingTable); ``` -------------------------------- ### Create a Mineflayer Bot Instance Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Initializes a new Mineflayer bot instance with specified options. This is the primary function for creating and configuring a bot to join a Minecraft server. Options can include login credentials, host, port, and version. ```javascript const mineflayer = require('mineflayer') const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'my bot', // password: 'password' }) bot.on('login', () => { console.log('Bot logged in') }) bot.on('error', (err) => { console.log('Bot error:', err) }) bot.on('end', () => { console.log('Bot disconnected') }) ``` -------------------------------- ### Create a Bot and Echo Chat (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/README.md Demonstrates how to create a Mineflayer bot, connect to a Minecraft server with Microsoft authentication, and echo received chat messages back to the server. It handles basic bot initialization and event listeners for chat, kicks, and errors. ```javascript const mineflayer = require('mineflayer'); const bot = mineflayer.createBot({ host: 'localhost', // minecraft server ip username: 'Bot', // username to join as if auth is `offline`, else a unique identifier for this account. Switch if you want to change accounts auth: 'microsoft' // for offline mode servers, you can set this to 'offline' //port: 25565, // set if you need a port that isn't 25565 //version: false, // only set if you need a specific version or snapshot (ie: "1.8.9" or "1.16.5"), otherwise it's set automatically //password: '12345678' // set if you want to use password-based auth (may be unreliable). If specified, the `username` must be an email }); bot.on('chat', (username, message) => { if (username === bot.username) return; bot.chat(message); }); // Log errors and kick reasons: bot.on('kicked', console.log); bot.on('error', console.log); ``` -------------------------------- ### Get Digging Time in Mineflayer Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/history.md Adds the `bot.digTime(block)` function to retrieve the time required to dig a specific block. This is useful for planning and understanding block breaking mechanics. ```javascript bot.digTime(block) ``` -------------------------------- ### Load a Plugin (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Loads a single plugin into the bot instance, extending its functionality. ```javascript bot.loadPlugin(plugin); ``` -------------------------------- ### Physics Engine and Block Properties in Mineflayer Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/history.md Integrates a physics engine that understands gravity, enabling more realistic environmental interactions. Block instances now have a `boundingBox` property ('solid' or 'empty'). Includes examples for jumping. ```javascript // Physics engine with gravity Block instances have a `boundingBox` property ('solid' or 'empty') // jumper example ``` -------------------------------- ### Mineflayer Bedrock Methods: Plugin and Setting Management Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Provides methods for loading external plugins and setting bot-specific options. This allows for extending bot functionality and customizing its behavior. ```javascript bot.loadPlugin(myPlugin); bot.setSettings({ colorsEnabled: true }); ``` -------------------------------- ### Get Craftable Recipes - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Retrieves a list of recipes for a given item type and metadata, considering available materials and whether a crafting table is required. Filters recipes based on the minimum number of results that can be crafted. ```javascript const craftingTableBlock = bot.findBlock({ matching: block => block.name === 'crafting_table' }); const plankRecipes = bot.recipesFor(5, null, 1, craftingTableBlock); console.log('Available plank recipes:', plankRecipes); ``` -------------------------------- ### Get Bot Control State (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Retrieves the current state of a specific control for the bot (e.g., whether it's currently moving forward). Returns a boolean value. ```javascript bot.getControlState(control); ``` -------------------------------- ### Bot Simple Click Abstraction Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Provides simplified methods for left and right mouse clicks on inventory slots. These are abstractions over the `bot.clickWindow` method. ```javascript // Left click bot.simpleClick.leftMouse(slot) // Right click bot.simpleClick.rightMouse(slot) ``` -------------------------------- ### Get Available Recipes (JavaScript) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Retrieves all available recipes for a given item type and metadata, considering whether a crafting table is required. Returns an array of recipe objects. ```javascript bot.recipesFor(itemType, metadata, minResultCount, craftingTable); ``` -------------------------------- ### Navigate to Script Directory on Termux - Bash Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Changes the current working directory to '/sdcard/my_scripts' in Termux. This is necessary to access your bot scripts after opening Termux. ```bash cd /sdcard/my_scripts ``` -------------------------------- ### Create Mineflayer Bot Instance (Python) Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/mineflayer.ipynb Loads the Mineflayer library using 'require' and creates a new bot instance connected to a specified Minecraft server in offline mode. It also demonstrates using 'once' to wait for the 'login' event before executing chat. ```python mineflayer = require('mineflayer') random_number = id([]) % 1000 # Give us a random number upto 1000 BOT_USERNAME = f'colab_{random_number}' bot = mineflayer.createBot({ 'host': 'pjs.deptofcraft.com', 'port': 25565, 'username': BOT_USERNAME, 'hideErrors': False }) # The spawn event once(bot, 'login') bot.chat('I spawned') ``` -------------------------------- ### Put Item into Range Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Move an item from a specific `slot` to a range of slots within a `window`. `bot.putSelectedItemRange(start, end, window, slot)` returns a Promise and is a lower-level inventory operation. ```javascript await bot.putSelectedItemRange(0, 8, bot.currentWindow, 36); // Example: Move item from slot 36 to the first 9 slots of the current window ``` -------------------------------- ### Node.js require() for Mineflayer Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Demonstrates how to use Node.js's 'require()' function to import the 'mineflayer' module. This allows access to the library's functionalities within a Node.js application. ```javascript const mineflayer = require('mineflayer') ``` -------------------------------- ### Find Blocks with Options - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/api.md Searches for blocks matching specific criteria starting from a given point. Supports matching by block ID or a custom function, with options for search distance and count. Returns an array of block coordinates, sorted by proximity. ```javascript const blocks = bot.findBlocks({ matching: (block) => block.name === 'dirt', maxDistance: 32, count: 10 }); console.log('Found dirt blocks:', blocks); ``` -------------------------------- ### Create and Connect Mineflayer Bot Instance (JavaScript) Source: https://context7.com/freezeengine/mineflayer-bedrock-public/llms.txt This snippet demonstrates how to create a Mineflayer bot instance, connect it to a Minecraft server using Microsoft authentication, and handle common connection events like login, spawn, errors, kicks, and disconnections. It requires the 'mineflayer' library. ```javascript const mineflayer = require('mineflayer') // Basic bot creation with Microsoft authentication const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'MyBot', auth: 'microsoft', version: '1.20.1', hideErrors: false, logErrors: true, viewDistance: 'far', difficulty: 2, physicsEnabled: true }) // Handle connection events bot.on('login', () => { console.log('Bot logged in successfully') }) bot.on('spawn', () => { console.log(`Bot spawned at ${bot.entity.position}`) bot.chat('Hello, I am a bot!') }) bot.on('error', (err) => { console.error('Bot error:', err) }) bot.on('kicked', (reason) => { console.log('Bot was kicked:', reason) }) bot.on('end', (reason) => { console.log('Bot disconnected:', reason) }) ``` -------------------------------- ### Run Mineflayer Tests with npm Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/CONTRIBUTING.md Commands to run Mineflayer tests using npm, with options to specify Minecraft versions and test patterns. These commands are essential for verifying code changes and ensuring compatibility. ```bash # Run all tests in all supported versions npm run test # Run a specific test in Minecraft 1.20.4 npm run mocha_test -- -g "mineflayer_external 1.20.4v.*exampleBee" # Run all tests in just version 1.20.4 npm run mocha_test -- -g "mineflayer_external 1.20.4v" ``` -------------------------------- ### Create Bot Instance Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/br/api_br.md Creates a new Mineflayer bot instance. Requires options such as the Minecraft version, username, and connection details. ```javascript const mineflayer = require('mineflayer-bedrock-public') const bot = mineflayer.createBot({ host: 'localhost', port: 19132, // Default Bedrock port username: 'myBot' }) bot.on('login', () => { console.log('Bot logged in') }) bot.on('error', (err) => { console.error('Bot error:', err) }) bot.on('end', () => { console.log('Bot disconnected') }) ``` -------------------------------- ### Log Output to Console in Javascript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/tutorial.md Shows how to print variable values to the terminal using the `console.log()` function in Javascript. This is essential for debugging and understanding program flow. Requires Node.js to execute. ```javascript const test = 5 console.log(test) ``` -------------------------------- ### Load Multiple Plugins - JavaScript Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/zh/api.md Injects an array of plugin functions into the bot instance. This is a convenience method for loading multiple plugins at once, with each plugin following the same interface as `bot.loadPlugin`. ```javascript bot.loadPlugins([somePlugin, anotherPlugin]) ``` -------------------------------- ### Parse Custom Chat Messages in Mineflayer Source: https://github.com/freezeengine/mineflayer-bedrock-public/blob/master/docs/FAQ.md Provides a JavaScript example for parsing custom chat messages, such as those from plugins like '/jackpot'. It uses regular expressions to extract specific information from multi-line chat messages, utilizing the `messagestr` event. ```javascript const mineflayer = require('mineflayer'); const bot = mineflayer.createBot({...}); const regex = { first: /\(!\) (.+) has won the \/jackpot and received +/, second: /\$(.+)! They purchased (.+) \((.+)%\) ticket\(s\) out of the /, third: /(.+) ticket\(s\) sold!/ } let jackpot = {} bot.on('messagestr', msg => { if (regex.first.test(msg)) { const username = msg.match(regex.first)[1] jackpot.username = username } else if (regex.second.test(msg)) { const [, moneyWon, boughtTickets, winPercent] = msg.match(regex.second) jackpot.moneyWon = parseInt(moneyWon.replace(/,/g, '')) jackpot.boughtTickets = parseInt(boughtTickets.replace(/,/g, '')) jackpot.winPercent = parseFloat(winPercent) } else if (regex.third.test(msg)) { const totalTickets = msg.match(regex.third)[1] jackpot.totalTickets = parseInt(totalTickets.replace(/,/g, '')) // Assuming onDone is a defined function to handle the parsed data onDone(jackpot) jackpot = {} } }) ``` -------------------------------- ### Bot Creation and Connection Source: https://context7.com/freezeengine/mineflayer-bedrock-public/llms.txt This section covers the process of creating a Mineflayer bot instance and connecting it to a Minecraft server, including basic configuration and event handling for login, spawn, errors, kicks, and disconnections. ```APIDOC ## Bot Creation and Connection ### Description Provides instructions and code examples for creating a Mineflayer bot instance and establishing a connection to a Minecraft server. It includes details on essential configuration options and how to handle common connection-related events. ### Method `mineflayer.createBot(options)` ### Endpoint N/A (This is a client-side library) ### Parameters #### Options Object - **host** (string) - Required - The hostname or IP address of the Minecraft server. - **port** (number) - Optional - The port number of the Minecraft server (defaults to 25565). - **username** (string) - Required - The username for the bot. - **auth** (string) - Required - Authentication method ('microsoft', 'offline'). - **version** (string) - Optional - The Minecraft version to connect with (e.g., '1.20.1'). - **hideErrors** (boolean) - Optional - Whether to hide errors from the console. - **logErrors** (boolean) - Optional - Whether to log errors to the console. - **viewDistance** (string) - Optional - Sets the view distance for the bot ('far', 'normal', 'short', 'tiny'). - **difficulty** (number) - Optional - Sets the game difficulty (0: peaceful, 1: easy, 2: normal, 3: hard). - **physicsEnabled** (boolean) - Optional - Whether to enable physics simulation for the bot. ### Event Handlers - **login**: Emitted when the bot successfully logs in. - **spawn**: Emitted when the bot spawns into the world. - **error**: Emitted when an error occurs. - **kicked**: Emitted when the bot is kicked from the server. - **end**: Emitted when the bot disconnects from the server. ### Request Example ```javascript const mineflayer = require('mineflayer') const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'MyBot', auth: 'microsoft', version: '1.20.1' }) bot.on('login', () => { console.log('Bot logged in') }) ``` ### Response N/A (This is a client-side library; events are emitted) #### Success Response (Events) - **login**: No data, indicates successful login. - **spawn**: No data, indicates successful spawn. #### Error Response (Events) - **error**: Contains an `Error` object. - **kicked**: Contains a `reason` string. - **end**: Contains a `reason` string. ```