### Install Node.js and Check Versions Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/mineflayer.ipynb Uses the n version manager to install Node.js v18 and verifies the environment versions. ```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 ``` -------------------------------- ### Install Linux dependencies Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Install required system packages if npm installation fails on Linux. ```bash sudo apt-get update -y sudo apt-get install -y xserver-xorg-dev libxi-dev xserver-xorg-dev libxext-dev xvfb ``` -------------------------------- ### Install Node.js on Termux Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Updates package lists and installs the Node.js runtime environment. ```bash pkg update -y pkg install nodejs -y ``` -------------------------------- ### Initialize Project Environment Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/update_to_1_21_5.md Commands to navigate to the project directory and install dependencies. ```bash cd /media/documents/Documents/programmation/interlangage/minecraft/mineflayer npm install ``` -------------------------------- ### Run block finder test example Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Demonstrates running the block finder test for version 1.18.1. ```bash npm run mocha_test -- -g "1.18.1.*BlockFinder" ``` -------------------------------- ### Start bot on Linux Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Use xvfb-run to execute the script in a virtual X server environment on Linux. ```bash xvfb-run -s "-ac -screen 0 1280x1024x24" node [...args] ``` -------------------------------- ### Install Mineflayer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Install Mineflayer using npm. Ensure you have Node.js version 18 or higher. ```bash npm install mineflayer ``` -------------------------------- ### Install javascript Package Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/mineflayer.ipynb Installs the bridge library required to access Node.js modules from Python. ```python !pip install javascript ``` -------------------------------- ### Display loop output Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md The expected console output from the while loop example. ```txt 5 4 3 2 1 Finished! ``` -------------------------------- ### Console Output Example Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md This is the expected output when running the `console.log(test)` code snippet. ```text 5 ``` -------------------------------- ### bot.creative.startFlying Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md In creative mode, starts the bot's flying ability. ```APIDOC ## bot.creative.startFlying() ### Description In creative mode, starts the bot's flying ability. ### Method `bot.creative.startFlying()` ``` -------------------------------- ### Start Digging with Mineflayer (Deprecated) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/history.md The `bot.startDigging(block)` method was the previous way to initiate digging. It has been replaced by `bot.dig(block, [timeout], [callback])`. ```javascript bot.startDigging(block) ``` -------------------------------- ### Start bot on Mac Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Execute the script directly on macOS High Sierra. ```bash node [...args] ``` -------------------------------- ### Server Commands for Time and Game Rules Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/llm_contribute.md Examples of using bot.test.sayEverywhere to send commands to the server, specifically to set the time and toggle the daylight cycle. ```javascript bot.test.sayEverywhere('/time set 0') // Set time bot.test.sayEverywhere('/gamerule doDaylightCycle false') // Toggle game rules ``` -------------------------------- ### Import modules with require Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Loads installed Node.js packages into the current script. ```js const mineflayer = require('mineflayer') ``` -------------------------------- ### bot.dig(block, forceLook, digFace) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/ru/api_ru.md Starts digging a block. ```APIDOC ## bot.dig(block, forceLook, digFace) ### Description Starts the process of digging a block. ### Parameters #### Request Body - **block** (object) - Required - The block to dig. - **forceLook** (boolean) - Optional - Whether to force the bot to look at the block (default: true). - **digFace** (object) - Optional - The face of the block to dig. ``` -------------------------------- ### Initiate Digging with Mineflayer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/history.md The `bot.dig(block, [callback])` method is used to start digging a specific block. The callback function is executed upon completion or error. ```javascript bot.dig(block, [callback]) ``` -------------------------------- ### Connect to Minecraft Server via SOCKS5 Proxy Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/FAQ.md Use this code to establish a connection to a Minecraft server through a SOCKS5 proxy. Ensure the `socks` package is installed and required. ```javascript 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.log(err) return } client.setSocket(info.socket) client.emit('connect') }) } ``` -------------------------------- ### Install Javascript Pip Package Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/python/README.md Install the necessary pip package to enable JavaScript module access in Python. Ensure Python 3.8+ and Node.js 14+ are installed. ```shell pip install javascript ``` -------------------------------- ### Initialize a bot with custom options Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Configures the bot to connect to a specific host and port using an options object. ```js 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) ``` -------------------------------- ### Build Docker image Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Build the Docker container for the screenshot bot. ```bash cd screenshot-with-node-canvas docker build . -t screenshot-bot ``` -------------------------------- ### Initialize a basic Mineflayer bot Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Creates a bot instance using default connection settings. ```js const mineflayer = require('mineflayer') const bot = mineflayer.createBot() ``` -------------------------------- ### Get Furnace Output Item Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Get the item currently in the output slot of the furnace. Returns an Item instance. ```javascript furnace.outputItem() ``` -------------------------------- ### Get Furnace Fuel Item Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Get the item currently in the fuel slot of the furnace. Returns an Item instance. ```javascript furnace.fuelItem() ``` -------------------------------- ### Create Bot with Command Line Arguments Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/tutorial.md Use `process.argv` to read connection details from command line arguments, making your bot configuration more flexible and secure. ```javascript const bot = mineflayer.createBot({ host: process.argv[2], port: parseInt(process.argv[3]), username: process.argv[4], password: process.argv[5] }) ``` -------------------------------- ### Get Furnace Input Item Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Get the item currently in the input slot of the furnace. Returns an Item instance. ```javascript furnace.inputItem() ``` -------------------------------- ### Run Docker container Source: https://github.com/prismarinejs/mineflayer/blob/master/examples/screenshot-with-node-canvas-webgl/README.md Execute the container and map the local directory to save screenshots. ```bash docker run -v $(pwd):/usr/src/app/screenshots -e HOST='' -e PORT= screenshot-bot ``` -------------------------------- ### sleep Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when the bot starts sleeping. ```APIDOC ## sleep () ### Description Fires when you sleep. ``` -------------------------------- ### Create Bot with Credentials Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Use this to create a bot instance with specific login credentials for offline servers. Ensure 'username' and 'password' are provided. ```javascript const bot = mineflayer.createBot({ host: 'localhost', port: 25565, username: 'Player', password: 'password' }) ``` -------------------------------- ### entitySleep Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when an entity starts sleeping. ```APIDOC ## entitySleep (entity) ### Description Fires when an entity starts sleeping. ### Parameters #### Path Parameters - **entity** (Entity) - Required - The entity that is sleeping. ``` -------------------------------- ### entityCrouch Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when an entity starts crouching. ```APIDOC ## entityCrouch (entity) ### Description Fires when an entity starts crouching. ### Parameters #### Path Parameters - **entity** (Entity) - Required - The entity that is crouching. ``` -------------------------------- ### Initialize mineflayer-pathfinder plugin Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/mineflayer.ipynb Configures the pathfinder plugin and movement settings for bot navigation. ```python 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.wake Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Causes the bot to get out of bed. This is an asynchronous operation. ```APIDOC ## bot.wake() ### Description Causes the bot to get out of bed. This function returns a Promise that resolves when the bot has woken up. ### Returns * (Promise) A promise that resolves with no value upon successfully waking up. ### Example ```javascript async function wakeUp (bot) { await bot.wake() console.log('Bot has woken up.') } ``` ``` -------------------------------- ### Initialize Mineflayer Bot Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/mineflayer.ipynb Loads the mineflayer module and creates a bot instance connecting to the specified server. ```python mineflayer = require('mineflayer') ``` ```python 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') ``` -------------------------------- ### Wake Up Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Causes the bot to get out of bed. This is an asynchronous operation. ```javascript await bot.wake() ``` -------------------------------- ### Run all tests Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Executes the entire test suite for the project. ```bash npm test ``` -------------------------------- ### bot.getEquipmentDestSlot Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Gets the destination slot index for equipping an item. ```APIDOC ## bot.getEquipmentDestSlot(destination) ### Description Gets the destination slot index for equipping an item. ### Method `bot.getEquipmentDestSlot(destination)` ### Parameters - **destination** (string) - The equipment slot name (e.g., 'head', 'chest', 'legs', 'feet'). ``` -------------------------------- ### bot.dig Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Starts digging a block with the currently equipped item. ```APIDOC ## bot.dig(block, [forceLook], [digFace], [callback]) ### Description Begin digging into a block with the currently equipped item. Note that you cannot dig other blocks until the current one is broken or stopped. ### Parameters - **block** (Object) - Required - The block to start digging into. - **forceLook** (boolean|string) - Optional - If true, look at the block instantly. Can be 'ignore' or 'raycast'. - **digFace** (string|vec3) - Optional - The face of the block to mine. Default is 'auto'. - **callback** (function) - Optional - Called when the block is broken or interrupted. ``` -------------------------------- ### bot.creative.startFlying Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Sets bot.physics.gravity to 0, allowing the bot to fly. ```APIDOC ## bot.creative.startFlying() ### Description Sets `bot.physics.gravity` to `0`, allowing the bot to hover or fly. This method is useful if you want to hover while digging the ground below you. It is not necessary to call this function before calling `flyTo()`. ### Method Not applicable (function call) ### Parameters None ### Request Example ```javascript // Assuming 'bot' is a mineflayer bot instance bot.creative.startFlying(); ``` ### Response This method does not return a promise or have a specific response value other than modifying the bot's physics. ### Notes - To resume normal physics, call `stopFlying()`. - While flying, `bot.entity.velocity` will not be accurate. ``` -------------------------------- ### Define and access JavaScript objects Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Demonstrates creating objects with key-value pairs and accessing properties. ```js const object = { number: 10, another: 5 } console.log(object.number) // This will print the value 10 ``` -------------------------------- ### Create Bot Directory Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Navigates to internal storage and creates a dedicated directory for bot scripts. ```bash cd /sdcard mkdir my_scripts cd my_scripts ``` -------------------------------- ### Enable Protocol Debugging Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Configure protocol debugging output using environment variables. ```bash DEBUG="minecraft-protocol" node [...] ``` ```bash set DEBUG=minecraft-protocol node your_script.js ``` -------------------------------- ### bot.getEquipmentDestSlot(destination) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Gets the inventory equipment slot ID for a given equipment destination name. ```APIDOC ## bot.getEquipmentDestSlot(destination) ### Description Gets the inventory equipment slot ID for a given equipment destination name. ### Method `number` ### Parameters * **destination** (string) - The equipment destination name. Available destinations are: `head`, `torso`, `legs`, `feet`, `hand`, `off-hand`. ``` -------------------------------- ### bot.recipesAll(itemType, metadata, craftingTable) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Lists all possible recipes for a given item, regardless of current inventory. ```APIDOC ## bot.recipesAll(itemType, metadata, craftingTable) ### Description The same as bot.recipesFor except that it does not check whether the bot has enough materials for the recipe. ### Parameters #### Path Parameters - **itemType** (number) - Numerical item id of the thing you want to craft. - **metadata** (number | null) - The numerical metadata value of the item you want to craft. `null` matches any metadata. - **craftingTable** (Block | null) - A `Block` instance. If `null`, only recipes that can be performed in your inventory window will be included in the list. ### Response #### Success Response (Array) - Returns an array of all possible `Recipe` objects for the specified item. ``` -------------------------------- ### bot.entityAtCursor(maxDistance) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Gets the entity the bot is currently looking at, within a specified maximum distance. ```APIDOC ## bot.entityAtCursor(maxDistance) ### Description Returns the entity at which bot is looking at or `null`. ### Parameters #### Path Parameters - **maxDistance** (number) - Optional. The maximum distance the entity can be from the eye, defaults to 3.5. ### Response #### Success Response (Entity | null) - Returns the `Entity` object the bot is looking at, or `null` if no entity is in sight within the max distance. ``` -------------------------------- ### bot.recipesFor(itemType, metadata, minResultCount, craftingTable) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Lists available recipes for a given item, considering inventory and crafting table availability. ```APIDOC ## bot.recipesFor(itemType, metadata, minResultCount, craftingTable) ### Description Returns a list of `Recipe` instances that you could use to craft `itemType` with `metadata`. ### Parameters #### Path Parameters - **itemType** (number) - Numerical item id of the thing you want to craft. - **metadata** (number | null) - The numerical metadata value of the item you want to craft. `null` matches any metadata. - **minResultCount** (number | null) - Based on your current inventory, any recipe from the returned list will be able to produce this many items. `null` is an alias for `1`. - **craftingTable** (Block | null) - A `Block` instance. If `null`, only recipes that can be performed in your inventory window will be included in the list. ### Response #### Success Response (Array) - Returns an array of `Recipe` objects that can be used to craft the specified item. ``` -------------------------------- ### Bot Enable Server Listing Setting Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Determines if the player should appear in server listings. This setting is sent to the server. ```javascript bot.settings.enableServerListing ``` -------------------------------- ### bot.blockAtCursor(maxDistance) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Gets the block the bot is currently looking at, within a specified maximum distance. ```APIDOC ## bot.blockAtCursor(maxDistance) ### Description Returns the block at which bot is looking at or `null`. ### Parameters #### Path Parameters - **maxDistance** (number) - Optional. The maximum distance the block can be from the eye, defaults to 256. ### Response #### Success Response (Block | null) - Returns the `Block` object the bot is looking at, or `null` if no block is in sight within the max distance. ``` -------------------------------- ### Window Class and Methods Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Base class for all inventory windows, with methods for interacting with items. ```APIDOC ## Window Class (Base Class) ### Description Base class for all inventory-related windows in the game. Provides common methods for item manipulation. ### Methods #### window.deposit(itemType, metadata, count, [callback]) - Deposits an item into the window. #### window.withdraw(itemType, metadata, count, [callback]) - Withdraws an item from the window. #### window.close() - Closes the current window. ``` -------------------------------- ### Get Bot Control State Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Checks if a specific control state (e.g., 'forward', 'jump') is currently active. ```javascript const isJumping = bot.getControlState('jump') ``` -------------------------------- ### bot.settings.difficulty Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Set the game difficulty, mirroring the server.properties setting. ```APIDOC ## bot.settings.difficulty ### Description Sets the game difficulty. This value should correspond to the difficulty setting in the server's `server.properties` file. ### Type string or number ``` -------------------------------- ### bot.findBlocks(options) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Searches for blocks matching specific criteria starting from a given point, within a maximum distance. ```APIDOC ## bot.findBlocks(options) ### Description Finds the closest blocks from the given point. ### Parameters #### Path Parameters - **options** (Object) - Options for the search: - **point** (Vec3 | {x, y, z}) - The start position of the search (center). Default is the bot position. - **matching** (function | number | number[]) - A function that returns true if the given block is a match. Also supports this value being a block id or array of block ids. - **useExtraInfo** (boolean | function) - To preserve backward compatibility can result in two behavior depending on the type: - **boolean**: Provide your `matching` function more data - noticeably slower approach. - **function**: Creates two stage matching, if block passes `matching` function it is passed further to `useExtraInfo` with additional info. - **maxDistance** (number) - The furthest distance for the search, defaults to 16. - **count** (number) - Number of blocks to find before returning the search. Default to 1. Can return less if not enough blocks are found exploring the whole area. ### Response #### Success Response (Array) - Returns an array (possibly empty) with the found block coordinates (not the blocks). The array is sorted (closest first). ``` -------------------------------- ### bot.dig Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Starts digging a block. This is an asynchronous operation. The bot will stop digging other blocks until this one is broken or `bot.stopDigging()` is called. ```APIDOC ## bot.dig(block, [forceLook], [digFace]) ### Description This function returns a `Promise`, with `void` as its argument when the block is broken or you are interrupted. Begin digging into `block` with the currently equipped item. See also "diggingCompleted" and "diggingAborted" events. Note that once you begin digging into a block, you may not dig any other blocks until the block has been broken, or you call `bot.stopDigging()`. ### Parameters * `block` - the block to start digging into * `forceLook` - (optional) if true, the bot snaps its head to the block and starts mining instantly. If false or omitted, the bot turns its head to the block at its normal look rate and waits for the turn to finish before digging. Can also be assigned 'ignore' to prevent the bot from moving its head at all. * `digFace` - (optional) Default is 'auto' looks at the center of the block and mines the top face. Can also be a vec3 vector of the face the bot should be looking at when digging the block. For example: ```vec3(0, 1, 0)``` when mining the top. Can also be 'raycast' raycast checks if there is a face visible by the bot and mines that face. Useful for servers with anti cheat. If you call bot.dig twice before the first dig is finished, you will get a fatal 'diggingAborted' error. ``` -------------------------------- ### Navigate to Bot Directory Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/tutorial.md Sets the current working directory to the folder containing bot scripts. ```bash cd /sdcard/my_scripts ``` -------------------------------- ### Access Block Entity Data Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Example structure of a block entity object, such as a sign, containing coordinate and text data. ```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 } ``` -------------------------------- ### Get Sign Text Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Retrieve the plain text content of a sign block. This method is preferred over accessing unstable blockEntity data. ```java > block = bot.blockAt(new Vec3(0, 60, 0)) // assuming a sign is here > block.getSignText() [ "Front text\nHello world", "Back text\nHello world" ] ``` -------------------------------- ### bot.quickBarSlot Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md The currently selected quick bar slot. ```APIDOC ## bot.quickBarSlot ### Description The currently selected quick bar slot. ``` -------------------------------- ### bot.putSelectedItemRange(start, end, window, slot) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Puts the item currently held in the bot's hand into the specified range within a given window. ```APIDOC ## bot.putSelectedItemRange(start, end, window, slot) ### Description Puts the item currently held in the bot's hand into the specified range within a given window. ### Method `Promise` ### Parameters * **start** (number) - The starting slot of the range. * **end** (number) - The ending slot of the range. * **window** (Window) - The window to put the item into. * **slot** (number) - The slot in the current window where the item is located. ``` -------------------------------- ### "login" event Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires after the bot successfully logs into the server. It's generally advised to wait for the `spawn` event before performing actions. ```APIDOC ## "login" event ### Description Fires after you successfully login to the server. You probably want to wait for the `spawn` event before doing anything though. ``` -------------------------------- ### bot.craft(recipe, count, craftingTable?) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Crafts items using a given recipe, count, and optionally a crafting table. Returns void upon completion. ```APIDOC ## bot.craft(recipe, count, craftingTable?) ### Description Crafts items using a given recipe, count, and optionally a crafting table. Returns void upon completion. ### Method `Promise` ### Parameters * `recipe` - A `Recipe` instance. See `bot.recipesFor`. * `count` - How many times you wish to perform the operation. `null` is an alias for `1`. * `craftingTable` (Optional): A `Block` instance, the crafting table you wish to use. If the recipe does not require a crafting table, you may use `null` for this argument. ``` -------------------------------- ### Enable Prismarine Viewer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Integrates the prismarine-viewer to visualize the bot's world view in a browser window. ```js 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 }) ``` -------------------------------- ### Get Digging Time in Mineflayer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/history.md Use `bot.digTime(block)` to retrieve the estimated time required to dig a specific block. This can help in planning digging operations. ```javascript bot.digTime(block) ``` -------------------------------- ### Handle Block Placement Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires specifically when the bot places a block. Provides the block state before and after placement. ```javascript bot.on('blockPlaced', (oldBlock, newBlock) => { console.log(`Bot placed block at ${newBlock.position}.`) }) ``` -------------------------------- ### Sign Block Entity Data (1.19) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Example of block entity data for a sign in Minecraft version 1.19. Note that for plain text, block.getSignText() is recommended. ```javascript // sign.blockEntity example from 1.19 { GlowingText: 0, // 0 for false, 1 for true Color: 'black', Text1: '{"text":"1"}', Text2: '{"text":"2"}', Text3: '{"text":"3"}', Text4: '{"text":"4"}' } ``` -------------------------------- ### Initialize a Mineflayer Bot Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Creates a basic bot instance that echoes chat messages and logs connection errors. ```js 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) ``` -------------------------------- ### Container and Interaction Methods Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Methods for opening and interacting with containers, furnaces, and villagers. ```APIDOC ## bot.openContainer(containerBlock or containerEntity) ### Description Opens a container and returns a promise on a Container instance. ## bot.openFurnace(furnaceBlock) ### Description Opens a furnace and returns a promise on a Furnace instance. ## bot.openVillager(villagerEntity) ### Description Opens a trading window and returns a promise on a Villager instance. ## bot.trade(villagerInstance, tradeIndex, [times], [cb]) ### Description Uses the open villager instance to trade. ``` -------------------------------- ### windowOpen Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when a window (e.g., workbench, chest) is opened. ```APIDOC ## windowOpen (window) ### Description Fires when you begin using a workbench, chest, brewing stand, etc. ### Parameters * `window`: The opened window object. ``` -------------------------------- ### Incorrect Sequential Crafting in Mineflayer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/tutorial.md This approach is incorrect because subsequent crafting operations may start before previous ones have finished, leading to errors or unexpected behavior due to resource unavailability. ```javascript const plankRecipe = bot.recipesFor(5)[0] // Get the first recipe for item id 5, which is oak planks. bot.craft(plankRecipe, 1) // ❌ start crafting oak planks. const stickRecipe = bot.recipesFor(280)[0] // Get the first recipe for item id 5, which is sticks. bot.craft(stickRecipe, 1) // ❌ start crafting sticks. ``` -------------------------------- ### JavaScript Promise with setTimeout Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/tutorial.md This example demonstrates the creation of a JavaScript Promise that resolves after a specified delay using `setTimeout`. It shows how to handle successful resolution with `.then()` and potential errors with `.catch()`. ```javascript const myPromise = new Promise((resolve, reject) => { setTimeout(() => { resolve('Success!') // 耶!一切都很顺利! }, 1000) }) myPromise.then((successMessage) => { console.log(successMessage) }) myPromise.catch((error) => { console.log(error) }) ``` -------------------------------- ### Create Bot with Mineflayer Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/history.md Use `mineflayer.createBot` to initialize a new bot instance. Authentication with official Minecraft servers requires `username` and `password`. If `password` is omitted, the bot connects directly and may be kicked from online-mode servers. ```javascript mineflayer.createBot ``` -------------------------------- ### Chained JavaScript Promise with setTimeout Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/tutorial.md This example shows a more concise way to handle Promises by chaining `.then()` and `.catch()` directly to the Promise creation. The Promise resolves after a delay, and its outcome is handled immediately. ```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) }) ``` -------------------------------- ### furnace.takeInput() Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Takes the input item from the furnace. ```APIDOC ## furnace.takeInput() ### Description Takes the input item from the furnace. ### Method Not applicable (SDK method) ``` -------------------------------- ### Utility and Low-Level Methods Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Utility methods for command blocks, feature support, and low-level inventory manipulation. ```APIDOC ## bot.setCommandBlock(pos, command, [options]) ### Description Set a command block's properties at a specific position. ## bot.supportFeature(name) ### Description Check if a specific feature is available in the current Minecraft version. ## bot.waitForTicks(ticks) ### Description Waits for a given number of in-game ticks to pass. ## bot.clickWindow(slot, mouseButton, mode, cb) ### Description Click on the current window. ``` -------------------------------- ### "inject_allowed" event Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when the index file has been loaded, indicating that mcData and plugins can be loaded. It's recommended to wait for the "spawn" event. ```APIDOC ## "inject_allowed" event ### Description Fires when the index file has been loaded, you can load mcData and plugins here but it's better to wait for "spawn" event. ``` -------------------------------- ### Plugin Management Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Methods for loading and checking plugins. ```APIDOC ## bot.loadPlugin(plugin) ### Description Injects a Plugin. Does nothing if the plugin is already loaded. ### Method `bot.loadPlugin` ### Parameters #### Path Parameters - **plugin** (function) - The plugin function to load. ### Request Example ```js function somePlugin (bot, options) { function someFunction () { bot.chat('Yay!') } bot.myPlugin = {} // Good practice to namespace plugin API bot.myPlugin.someFunction = someFunction } const bot = mineflayer.createBot({}) bot.loadPlugin(somePlugin) bot.once('login', function () { bot.myPlugin.someFunction() // Yay! }) ``` ## bot.loadPlugins(plugins) ### Description Injects plugins. See `bot.loadPlugin`. ### Method `bot.loadPlugins` ### Parameters #### Path Parameters - **plugins** (Array) - An array of plugin functions to load. ## bot.hasPlugin(plugin) ### Description Checks if the given plugin is loaded (or scheduled to be loaded) on this bot. ### Method `bot.hasPlugin` ### Parameters #### Path Parameters - **plugin** (function) - The plugin function to check. ``` -------------------------------- ### bot.setQuickBarSlot(slot) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Selects a quick bar slot. ```APIDOC ## bot.setQuickBarSlot(slot) ### Description Selects a quick bar slot. ### Method `void` ### Parameters * `slot` - 0-8: the quick bar slot to select. ``` -------------------------------- ### bot.experience.progress Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md The progress towards the next experience level. ```APIDOC ## bot.experience.progress ### Description The progress towards the next experience level. ``` -------------------------------- ### bot.settings.enableServerListing Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md A boolean setting to determine if the player should appear in server listings. ```APIDOC ## bot.settings.enableServerListing ### Description This setting is sent to the server to indicate whether the player should be included in server listings. Set to `true` to be visible in server lists, `false` otherwise. ### Type boolean ``` -------------------------------- ### Implement pathfinding movement goal Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/mineflayer.ipynb Sets a movement goal for the bot based on player chat commands. ```python 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) ``` -------------------------------- ### bot.writeBook(slot, pages) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Writes content to a book in the specified inventory slot. Returns void upon success or error. ```APIDOC ## bot.writeBook(slot, pages) ### Description Writes content to a book in the specified inventory slot. Returns void upon success or error. ### Method `Promise` ### Parameters * `slot` - Inventory window coordinates (e.g., 36 for the first quickbar slot). * `pages` - An array of strings representing the pages of the book. ``` -------------------------------- ### bot.acceptResourcePack Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Accepts the resource pack offered by the server. ```APIDOC ## bot.acceptResourcePack() ### Description Accepts resource pack. ``` -------------------------------- ### experience Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when the bot's experience values are updated. ```APIDOC ## experience () ### Description Fires when `bot.experience.*` has updated. ``` -------------------------------- ### bot.time.time Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md The current in-game time. ```APIDOC ## bot.time.time ### Description The current in-game time. ``` -------------------------------- ### bot.openFurnace Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Opens a furnace block and returns a promise that resolves with a Furnace instance. ```APIDOC ## bot.openFurnace(furnaceBlock) ### Description Returns a promise on a `Furnace` instance which represents the furnace you are opening. ### Parameters #### Path Parameters - `furnaceBlock` (object) - Required - The furnace block to open. ``` -------------------------------- ### wake Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when the bot wakes up. ```APIDOC ## wake () ### Description Fires when you wake up. ``` -------------------------------- ### furnace.takeOutput() Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Takes the output item from the furnace. ```APIDOC ## furnace.takeOutput() ### Description Takes the output item from the furnace. ### Method Not applicable (SDK method) ``` -------------------------------- ### bot.openBlock(block, direction?, cursorPos?) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Opens a block with an inventory, such as a chest, returning a Promise that resolves with the opened Window. ```APIDOC ## bot.openBlock(block, direction?, cursorPos?) ### Description Opens a block with an inventory, such as a chest, returning a Promise that resolves with the opened Window. ### Method `Promise` ### Parameters * **block** (Block) - The block to open. * **direction** (Vec3, optional) - The direction vector from which to interact with the block (defaults to `new Vec3(0, 1, 0)`). * **cursorPos** (Vec3, optional) - The cursor position within the block when opening (defaults to `new Vec3(0.5, 0.5, 0.5)`). ``` -------------------------------- ### furnace.takeFuel() Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Takes the fuel item from the furnace. ```APIDOC ## furnace.takeFuel() ### Description Takes the fuel item from the furnace. ### Method Not applicable (SDK method) ``` -------------------------------- ### bot.fish() Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Uses the fishing rod to fish. Returns void when fishing ends. ```APIDOC ## bot.fish() ### Description Uses the fishing rod to fish. Returns void when fishing ends. ### Method `Promise` ``` -------------------------------- ### bot.loadPlugins Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Injects multiple plugins into the bot instance. This is a convenience method for loading several plugins at once. ```APIDOC ## bot.loadPlugins(plugins) ### Description Injects multiple plugins into the bot instance. See `bot.loadPlugin` for details on how plugins are structured. ### Parameters * `plugins` - (Array) An array of plugin functions to load. ### Example ```javascript function pluginA (bot) { /* ... */ } function pluginB (bot) { /* ... */ } bot.loadPlugins([pluginA, pluginB]) ``` ``` -------------------------------- ### playerJoined Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when a player joins the server. ```APIDOC ## playerJoined (player) ### Description Fires when a player joins the server. ### Parameters #### Path Parameters - **player** (Player) - Required - The player that joined. ``` -------------------------------- ### Connect to a Minecraft Realm Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/README.md Configures the bot to join a specific Realm by providing a selector function. ```js const client = mineflayer.createBot({ username: 'email@example.com', // minecraft username realms: { // This function is called with an array of Realms the account can join. It should return the one it wants to join. pickRealm: (realms) => realms[0] }, auth: 'microsoft' }) ``` -------------------------------- ### bot.thunderState Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md The current state of thunder. ```APIDOC ## bot.thunderState ### Description The current state of thunder. ``` -------------------------------- ### bot.loadPlugin Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Injects a single plugin into the bot instance. If the plugin is already loaded, this operation does nothing. ```APIDOC ## bot.loadPlugin(plugin) ### Description Injects a Plugin into the bot instance. If the plugin is already loaded, this method does nothing. ### Parameters * `plugin` - (function) A function that takes the `bot` instance and an `options` object as arguments. ### Example ```javascript function myCustomPlugin (bot, options) { bot.chat('My plugin is loaded!') } bot.loadPlugin(myCustomPlugin) ``` ``` -------------------------------- ### Crafting and Inventory Methods Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Methods for crafting items and managing inventory slots. ```APIDOC ## bot.setQuickBarSlot(slot) ### Description Select a slot in the quick bar. ### Parameters - **slot** (number) - Required - 0-8 the quick bar slot to select. ## bot.craft(recipe, count, craftingTable, [callback]) ### Description Crafts items using a recipe. ### Parameters - **recipe** (Recipe) - Required - A Recipe instance. - **count** (number) - Required - How many times to perform the operation. - **craftingTable** (Block) - Required - The crafting table to use, or null. - **callback** (Function) - Optional - Called when crafting is complete. ``` -------------------------------- ### "spawn" event Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Emitted once after the bot logs in and spawns for the first time, and again when respawning after death. This is typically the event to listen for before interacting with the server. ```APIDOC ## "spawn" event ### Description Emitted once after you log in and spawn for the first time and then emitted when you respawn after death. This is usually the event that you want to listen to before doing anything on the server. ``` -------------------------------- ### entitySpawn Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Fires when an entity spawns into the world. ```APIDOC ## entitySpawn (entity) ### Description Fires when an entity spawns into the world. ### Parameters #### Path Parameters - **entity** (Entity) - Required - The entity that spawned. ``` -------------------------------- ### Bot Properties Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Accessing core bot state, settings, and player information. ```APIDOC ## Bot Properties ### Description Access various properties of the bot instance to retrieve information about the player, world, and client settings. ### Properties - **bot.player** - Current player object - **bot.players** - Map of all players in the server - **bot.health** - Current health points - **bot.food** - Current food level - **bot.inventory** - Bot inventory object - **bot.settings.viewDistance** - Current view distance setting - **bot.time.timeOfDay** - Current time of day in the world ``` -------------------------------- ### bot.clickWindow Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Clicks on a slot in the currently open window. This is a lower-level method for inventory manipulation. ```APIDOC ## bot.clickWindow(slot, mouseButton, mode) ### Description Clicks on a slot in the currently open window. This is a lower-level method for inventory manipulation. ### Method `bot.clickWindow(slot, mouseButton, mode)` ### Parameters - **slot** (number) - The slot index to click. - **mouseButton** (number) - The mouse button to use (0 for left, 2 for right). - **mode** (number) - The click mode (0 for normal, 1 for shift click). ``` -------------------------------- ### Set Command Block Properties Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Configures a command block at a specific position using the provided options object. ```js { mode: 2, trackOutput: true, conditional: false, alwaysActive: true } ``` -------------------------------- ### bot.openEntity(entity) Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Opens an entity with an inventory, such as a villager, returning a Promise that resolves with the opened Window. ```APIDOC ## bot.openEntity(entity) ### Description Opens an entity with an inventory, such as a villager, returning a Promise that resolves with the opened Window. ### Method `Promise` ### Parameters * **entity** (Entity) - The entity to open. ``` -------------------------------- ### bot.time.day Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md The current day in the game. ```APIDOC ## bot.time.day ### Description The current day in the game. ``` -------------------------------- ### Connection Management Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/zh/api.md Methods for managing the bot's connection to the Minecraft server. ```APIDOC ## bot.end(reason) ### Description End the connection with the server. ### Method `bot.end` ### Parameters #### Path Parameters - **reason** (string) - Optional - The reason for ending the connection. ## bot.quit(reason) ### Description Gracefully disconnect from the server with the given reason. ### Method `bot.quit` ### Parameters #### Path Parameters - **reason** (string) - Optional - Defaults to 'disconnect.quitting'. The reason for disconnecting. ``` -------------------------------- ### Create 1.21.5 specific tests Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/update_to_1_21_5.md Add new test files to test/externalTests/ to validate 1.21.5 functionality. ```javascript // Add to test/externalTests/ // Create tests that specifically validate 1.21.5 functionality ``` -------------------------------- ### Load a Plugin Source: https://github.com/prismarinejs/mineflayer/blob/master/docs/api.md Injects a plugin function into the bot instance. Plugins can extend bot functionality and are namespaced for good practice. ```javascript function somePlugin (bot, options) { function someFunction () { bot.chat('Yay!') } bot.myPlugin = {} // Good practice to namespace plugin API bot.myPlugin.someFunction = someFunction } const bot = mineflayer.createBot({}) bot.loadPlugin(somePlugin) bot.once('login', function () { bot.myPlugin.someFunction() // Yay! }) ```