UNPKG

mineflayer

Version:

create minecraft bots with a stable, high level API

1,416 lines (1,009 loc) 81.9 kB
<!-- START doctoc generated TOC please keep comment here to allow auto update --> <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> **Table of Contents** *generated with [DocToc](https://github.com/thlorenz/doctoc)* - [API](#api) - [Enums](#enums) - [minecraft-data](#minecraft-data) - [mcdata.blocks](#mcdatablocks) - [mcdata.items](#mcdataitems) - [mcdata.materials](#mcdatamaterials) - [mcdata.recipes](#mcdatarecipes) - [mcdata.instruments](#mcdatainstruments) - [mcdata.biomes](#mcdatabiomes) - [mcdata.entities](#mcdataentities) - [Classes](#classes) - [vec3](#vec3) - [mineflayer.Location](#mineflayerlocation) - [Entity](#entity) - [Player Skin Data](#player-skin-data) - [Block](#block) - [Biome](#biome) - [Item](#item) - [windows.Window (base class)](#windowswindow-base-class) - [window.deposit(itemType, metadata, count, nbt)](#windowdeposititemtype-metadata-count-nbt) - [window.withdraw(itemType, metadata, count, nbt)](#windowwithdrawitemtype-metadata-count-nbt) - [window.close()](#windowclose) - [Recipe](#recipe) - [mineflayer.Container](#mineflayercontainer) - [mineflayer.Furnace](#mineflayerfurnace) - [furnace "update"](#furnace-update) - [furnace.takeInput()](#furnacetakeinput) - [furnace.takeFuel()](#furnacetakefuel) - [furnace.takeOutput()](#furnacetakeoutput) - [furnace.putInput(itemType, metadata, count)](#furnaceputinputitemtype-metadata-count) - [furnace.putFuel(itemType, metadata, count)](#furnaceputfuelitemtype-metadata-count) - [furnace.inputItem()](#furnaceinputitem) - [furnace.fuelItem()](#furnacefuelitem) - [furnace.outputItem()](#furnaceoutputitem) - [furnace.fuel](#furnacefuel) - [furnace.progress](#furnaceprogress) - [mineflayer.EnchantmentTable](#mineflayerenchantmenttable) - [enchantmentTable "ready"](#enchantmenttable-ready) - [enchantmentTable.targetItem()](#enchantmenttabletargetitem) - [enchantmentTable.xpseed](#enchantmenttablexpseed) - [enchantmentTable.enchantments](#enchantmenttableenchantments) - [enchantmentTable.enchant(choice)](#enchantmenttableenchantchoice) - [enchantmentTable.takeTargetItem()](#enchantmenttabletaketargetitem) - [enchantmentTable.putTargetItem(item)](#enchantmenttableputtargetitemitem) - [enchantmentTable.putLapis(item)](#enchantmenttableputlapisitem) - [mineflayer.anvil](#mineflayeranvil) - [anvil.combine(itemOne, itemTwo[, name])](#anvilcombineitemone-itemtwo-name) - [anvil.combine(item[, name])](#anvilcombineitem-name) - [villager "ready"](#villager-ready) - [villager.trades](#villagertrades) - [villager.trade(tradeIndex, [times])](#villagertradetradeindex-times) - [mineflayer.ScoreBoard](#mineflayerscoreboard) - [ScoreBoard.name](#scoreboardname) - [ScoreBoard.title](#scoreboardtitle) - [ScoreBoard.itemsMap](#scoreboarditemsmap) - [ScoreBoard.items](#scoreboarditems) - [mineflayer.Team](#mineflayerteam) - [Team.name](#teamname) - [Team.friendlyFire](#teamfriendlyfire) - [Team.nameTagVisibility](#teamnametagvisibility) - [Team.collisionRule](#teamcollisionrule) - [Team.color](#teamcolor) - [Team.prefix](#teamprefix) - [Team.suffix](#teamsuffix) - [Team.members](#teammembers) - [mineflayer.BossBar](#mineflayerbossbar) - [BossBar.title](#bossbartitle) - [BossBar.health](#bossbarhealth) - [BossBar.dividers](#bossbardividers) - [BossBar.entityUUID](#bossbarentityuuid) - [BossBar.shouldDarkenSky](#bossbarshoulddarkensky) - [BossBar.isDragonBar](#bossbarisdragonbar) - [BossBar.createFog](#bossbarcreatefog) - [BossBar.color](#bossbarcolor) - [mineflayer.Particle](#mineflayerparticle) - [Particle.id](#particleid) - [Particle.name](#particlename) - [Particle.position](#particleposition) - [Particle.offset](#particleoffset) - [Particle.longDistanceRender](#particlelongdistancerender) - [Particle.count](#particlecount) - [Particle.movementSpeed](#particlemovementspeed) - [Bot](#bot) - [mineflayer.createBot(options)](#mineflayercreatebotoptions) - [Properties](#properties) - [bot.registry](#botregistry) - [bot.world](#botworld) - [world "blockUpdate" (oldBlock, newBlock)](#world-blockupdate-oldblock-newblock) - [world "blockUpdate:(x, y, z)" (oldBlock, newBlock)](#world-blockupdatex-y-z-oldblock-newblock) - [bot.entity](#botentity) - [bot.entities](#botentities) - [bot.username](#botusername) - [bot.spawnPoint](#botspawnpoint) - [bot.heldItem](#bothelditem) - [bot.usingHeldItem](#botusinghelditem) - [bot.game.levelType](#botgameleveltype) - [bot.game.dimension](#botgamedimension) - [bot.game.difficulty](#botgamedifficulty) - [bot.game.gameMode](#botgamegamemode) - [bot.game.hardcore](#botgamehardcore) - [bot.game.maxPlayers](#botgamemaxplayers) - [bot.game.serverBrand](#botgameserverbrand) - [bot.game.minY](#botgameminy) - [bot.game.height](#botgameheight) - [bot.physicsEnabled](#botphysicsenabled) - [bot.player](#botplayer) - [bot.players](#botplayers) - [bot.tablist](#bottablist) - [bot.isRaining](#botisraining) - [bot.rainState](#botrainstate) - [bot.thunderState](#botthunderstate) - [bot.chatPatterns](#botchatpatterns) - [bot.settings.chat](#botsettingschat) - [bot.settings.colorsEnabled](#botsettingscolorsenabled) - [bot.settings.viewDistance](#botsettingsviewdistance) - [bot.settings.difficulty](#botsettingsdifficulty) - [bot.settings.skinParts](#botsettingsskinparts) - [bot.settings.skinParts.showCape - boolean](#botsettingsskinpartsshowcape---boolean) - [bot.settings.skinParts.showJacket - boolean](#botsettingsskinpartsshowjacket---boolean) - [bot.settings.skinParts.showLeftSleeve - boolean](#botsettingsskinpartsshowleftsleeve---boolean) - [bot.settings.skinParts.showRightSleeve - boolean](#botsettingsskinpartsshowrightsleeve---boolean) - [bot.settings.skinParts.showLeftPants - boolean](#botsettingsskinpartsshowleftpants---boolean) - [bot.settings.skinParts.showRightPants - boolean](#botsettingsskinpartsshowrightpants---boolean) - [bot.settings.skinParts.showHat - boolean](#botsettingsskinpartsshowhat---boolean) - [bot.settings.enableTextFiltering - boolean](#botsettingsenabletextfiltering---boolean) - [bot.settings.enableServerListing - boolean](#botsettingsenableserverlisting---boolean) - [bot.experience.level](#botexperiencelevel) - [bot.experience.points](#botexperiencepoints) - [bot.experience.progress](#botexperienceprogress) - [bot.health](#bothealth) - [bot.food](#botfood) - [bot.foodSaturation](#botfoodsaturation) - [bot.oxygenLevel](#botoxygenlevel) - [bot.physics](#botphysics) - [bot.fireworkRocketDuration](#botfireworkrocketduration) - [bot.simpleClick.leftMouse (slot)](#botsimpleclickleftmouse-slot) - [bot.simpleClick.rightMouse (slot)](#botsimpleclickrightmouse-slot) - [bot.time.doDaylightCycle](#bottimedodaylightcycle) - [bot.time.bigTime](#bottimebigtime) - [bot.time.time](#bottimetime) - [bot.time.timeOfDay](#bottimetimeofday) - [bot.time.day](#bottimeday) - [bot.time.isDay](#bottimeisday) - [bot.time.moonPhase](#bottimemoonphase) - [bot.time.bigAge](#bottimebigage) - [bot.time.age](#bottimeage) - [bot.quickBarSlot](#botquickbarslot) - [bot.inventory](#botinventory) - [bot.targetDigBlock](#bottargetdigblock) - [bot.isSleeping](#botissleeping) - [bot.scoreboards](#botscoreboards) - [bot.scoreboard](#botscoreboard) - [bot.teams](#botteams) - [bot.teamMap](#botteammap) - [bot.controlState](#botcontrolstate) - [Events](#events) - ["chat" (username, message, translate, jsonMsg, matches)](#chat-username-message-translate-jsonmsg-matches) - ["whisper" (username, message, translate, jsonMsg, matches)](#whisper-username-message-translate-jsonmsg-matches) - ["actionBar" (jsonMsg, verified)](#actionbar-jsonmsg-verified) - ["message" (jsonMsg, position, sender, verified)](#message-jsonmsg-position-sender-verified) - ["messagestr" (message, messagePosition, jsonMsg, sender, verified)](#messagestr-message-messageposition-jsonmsg-sender-verified) - ["inject_allowed"](#inject_allowed) - ["login"](#login) - ["spawn"](#spawn) - ["respawn"](#respawn) - ["game"](#game) - ["resourcePack" (url, hash)](#resourcepack-url-hash) - ["title" (title, type)](#title-title-type) - ["title_times" (fadeIn, stay, fadeOut)](#title_times-fadein-stay-fadeout) - ["title_clear"](#title_clear) - ["rain"](#rain) - ["weatherUpdate"](#weatherupdate) - ["time"](#time) - ["kicked" (reason, loggedIn)](#kicked-reason-loggedin) - ["end" (reason)](#end-reason) - ["error" (err)](#error-err) - ["spawnReset"](#spawnreset) - ["death"](#death) - ["health"](#health) - ["breath"](#breath) - ["entityAttributes" (entity)](#entityattributes-entity) - ["entitySwingArm" (entity)](#entityswingarm-entity) - ["entityHurt" (entity)](#entityhurt-entity) - ["entityDead" (entity)](#entitydead-entity) - ["entityTaming" (entity)](#entitytaming-entity) - ["entityTamed" (entity)](#entitytamed-entity) - ["entityShakingOffWater" (entity)](#entityshakingoffwater-entity) - ["entityEatingGrass" (entity)](#entityeatinggrass-entity) - ["entityHandSwap" (entity)](#entityhandswap-entity) - ["entityWake" (entity)](#entitywake-entity) - ["entityEat" (entity)](#entityeat-entity) - ["entityCriticalEffect" (entity)](#entitycriticaleffect-entity) - ["entityMagicCriticalEffect" (entity)](#entitymagiccriticaleffect-entity) - ["entityCrouch" (entity)](#entitycrouch-entity) - ["entityUncrouch" (entity)](#entityuncrouch-entity) - ["entityEquip" (entity)](#entityequip-entity) - ["entitySleep" (entity)](#entitysleep-entity) - ["entitySpawn" (entity)](#entityspawn-entity) - ["entityElytraFlew" (entity)](#entityelytraflew-entity) - ["itemDrop" (entity)](#itemdrop-entity) - ["playerCollect" (collector, collected)](#playercollect-collector-collected) - ["entityGone" (entity)](#entitygone-entity) - ["entityMoved" (entity)](#entitymoved-entity) - ["entityDetach" (entity, vehicle)](#entitydetach-entity-vehicle) - ["entityAttach" (entity, vehicle)](#entityattach-entity-vehicle) - ["entityUpdate" (entity)](#entityupdate-entity) - ["entityEffect" (entity, effect)](#entityeffect-entity-effect) - ["entityEffectEnd" (entity, effect)](#entityeffectend-entity-effect) - ["playerJoined" (player)](#playerjoined-player) - ["playerUpdated" (player)](#playerupdated-player) - ["playerLeft" (player)](#playerleft-player) - ["blockUpdate" (oldBlock, newBlock)](#blockupdate-oldblock-newblock) - ["blockUpdate:(x, y, z)" (oldBlock, newBlock)](#blockupdatex-y-z-oldblock-newblock) - ["blockPlaced" (oldBlock, newBlock)](#blockplaced-oldblock-newblock) - ["chunkColumnLoad" (point)](#chunkcolumnload-point) - ["chunkColumnUnload" (point)](#chunkcolumnunload-point) - ["soundEffectHeard" (soundName, position, volume, pitch)](#soundeffectheard-soundname-position-volume-pitch) - ["hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)](#hardcodedsoundeffectheard-soundid-soundcategory-position-volume-pitch) - ["noteHeard" (block, instrument, pitch)](#noteheard-block-instrument-pitch) - ["pistonMove" (block, isPulling, direction)](#pistonmove-block-ispulling-direction) - ["chestLidMove" (block, isOpen, block2)](#chestlidmove-block-isopen-block2) - ["blockBreakProgressObserved" (block, destroyStage, entity)](#blockbreakprogressobserved-block-destroystage-entity) - ["blockBreakProgressEnd" (block, entity)](#blockbreakprogressend-block-entity) - ["diggingCompleted" (block)](#diggingcompleted-block) - ["diggingAborted" (block)](#diggingaborted-block) - ["usedFirework" (fireworkEntityId)](#usedfirework-fireworkentityid) - ["move"](#move) - ["forcedMove"](#forcedmove) - ["mount"](#mount) - ["dismount" (vehicle)](#dismount-vehicle) - ["windowOpen" (window)](#windowopen-window) - ["windowClose" (window)](#windowclose-window) - ["sleep"](#sleep) - ["wake"](#wake) - ["experience"](#experience) - ["scoreboardCreated" (scoreboard)](#scoreboardcreated-scoreboard) - ["scoreboardDeleted" (scoreboard)](#scoreboarddeleted-scoreboard) - ["scoreboardTitleChanged" (scoreboard)](#scoreboardtitlechanged-scoreboard) - ["scoreUpdated" (scoreboard, item)](#scoreupdated-scoreboard-item) - ["scoreRemoved" (scoreboard, item)](#scoreremoved-scoreboard-item) - ["scoreboardPosition" (position, scoreboard)](#scoreboardposition-position-scoreboard) - ["teamCreated" (team)](#teamcreated-team) - ["teamRemoved" (team)](#teamremoved-team) - ["teamUpdated" (team)](#teamupdated-team) - ["teamMemberAdded" (team)](#teammemberadded-team) - ["teamMemberRemoved" (team)](#teammemberremoved-team) - ["bossBarCreated" (bossBar)](#bossbarcreated-bossbar) - ["bossBarDeleted" (bossBar)](#bossbardeleted-bossbar) - ["bossBarUpdated" (bossBar)](#bossbarupdated-bossbar) - ["heldItemChanged" (heldItem)](#helditemchanged-helditem) - ["physicsTick" ()](#physicstick-) - ["chat:name" (matches)](#chatname-matches) - ["particle"](#particle) - [Functions](#functions) - [bot.blockAt(point, extraInfos=true)](#botblockatpoint-extrainfostrue) - [bot.waitForChunksToLoad()](#botwaitforchunkstoload) - [bot.blockInSight(maxSteps, vectorLength)](#botblockinsightmaxsteps-vectorlength) - [bot.blockAtCursor(maxDistance=256)](#botblockatcursormaxdistance256) - [bot.entityAtCursor(maxDistance=3.5)](#botentityatcursormaxdistance35) - [bot.blockAtEntityCursor(entity=bot.entity, maxDistance=256)](#botblockatentitycursorentitybotentity-maxdistance256) - [bot.canSeeBlock(block)](#botcanseeblockblock) - [bot.findBlocks(options)](#botfindblocksoptions) - [bot.findBlock(options)](#botfindblockoptions) - [bot.canDigBlock(block)](#botcandigblockblock) - [bot.recipesFor(itemType, metadata, minResultCount, craftingTable)](#botrecipesforitemtype-metadata-minresultcount-craftingtable) - [bot.recipesAll(itemType, metadata, craftingTable)](#botrecipesallitemtype-metadata-craftingtable) - [bot.nearestEntity(match = (entity) => { return true })](#botnearestentitymatch--entity---return-true-) - [Methods](#methods) - [bot.end(reason)](#botendreason) - [bot.quit(reason)](#botquitreason) - [bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])](#bottabcompletestr-assumecommand-sendblockinsight-timeout) - [bot.chat(message)](#botchatmessage) - [bot.whisper(username, message)](#botwhisperusername-message) - [bot.chatAddPattern(pattern, chatType, description)](#botchataddpatternpattern-chattype-description) - [bot.addChatPattern(name, pattern, chatPatternOptions)](#botaddchatpatternname-pattern-chatpatternoptions) - [bot.addChatPatternSet(name, patterns, chatPatternOptions)](#botaddchatpatternsetname-patterns-chatpatternoptions) - [bot.removeChatPattern(name)](#botremovechatpatternname) - [bot.awaitMessage(...args)](#botawaitmessageargs) - [bot.setSettings(options)](#botsetsettingsoptions) - [bot.loadPlugin(plugin)](#botloadpluginplugin) - [bot.loadPlugins(plugins)](#botloadpluginsplugins) - [bot.hasPlugin(plugin)](#bothaspluginplugin) - [bot.sleep(bedBlock)](#botsleepbedblock) - [bot.isABed(bedBlock)](#botisabedbedblock) - [bot.wake()](#botwake) - [bot.setControlState(control, state)](#botsetcontrolstatecontrol-state) - [bot.getControlState(control)](#botgetcontrolstatecontrol) - [bot.clearControlStates()](#botclearcontrolstates) - [bot.getExplosionDamages(entity, position, radius, [rawDamages])](#botgetexplosiondamagesentity-position-radius-rawdamages) - [bot.lookAt(point, [force])](#botlookatpoint-force) - [bot.look(yaw, pitch, [force])](#botlookyaw-pitch-force) - [bot.updateSign(block, text, back = false)](#botupdatesignblock-text-back--false) - [bot.equip(item, destination)](#botequipitem-destination) - [bot.unequip(destination)](#botunequipdestination) - [bot.tossStack(item)](#bottossstackitem) - [bot.toss(itemType, metadata, count)](#bottossitemtype-metadata-count) - [bot.elytraFly()](#botelytrafly) - [bot.dig(block, [forceLook = true], [digFace])](#botdigblock-forcelook--true-digface) - [bot.stopDigging()](#botstopdigging) - [bot.digTime(block)](#botdigtimeblock) - [bot.acceptResourcePack()](#botacceptresourcepack) - [bot.denyResourcePack()](#botdenyresourcepack) - [bot.placeBlock(referenceBlock, faceVector)](#botplaceblockreferenceblock-facevector) - [bot.placeEntity(referenceBlock, faceVector)](#botplaceentityreferenceblock-facevector) - [bot.activateBlock(block, direction?: Vec3, cursorPos?: Vec3)](#botactivateblockblock-direction-vec3-cursorpos-vec3) - [bot.activateEntity(entity)](#botactivateentityentity) - [bot.activateEntityAt(entity, position)](#botactivateentityatentity-position) - [bot.consume()](#botconsume) - [bot.fish()](#botfish) - [bot.activateItem(offHand=false)](#botactivateitemoffhandfalse) - [bot.deactivateItem()](#botdeactivateitem) - [bot.useOn(targetEntity)](#botuseontargetentity) - [bot.attack(entity, swing = true)](#botattackentity-swing--true) - [bot.swingArm([hand], showHand)](#botswingarmhand-showhand) - [bot.mount(entity)](#botmountentity) - [bot.dismount()](#botdismount) - [bot.moveVehicle(left,forward)](#botmovevehicleleftforward) - [bot.setQuickBarSlot(slot)](#botsetquickbarslotslot) - [bot.craft(recipe, count, craftingTable)](#botcraftrecipe-count-craftingtable) - [bot.writeBook(slot, pages)](#botwritebookslot-pages) - [bot.openContainer(containerBlock or containerEntity, direction?, cursorPos?)](#botopencontainercontainerblock-or-containerentity-direction-cursorpos) - [bot.openChest(chestBlock or minecartchestEntity, direction?, cursorPos?)](#botopenchestchestblock-or-minecartchestentity-direction-cursorpos) - [bot.openFurnace(furnaceBlock)](#botopenfurnacefurnaceblock) - [bot.openDispenser(dispenserBlock)](#botopendispenserdispenserblock) - [bot.openEnchantmentTable(enchantmentTableBlock)](#botopenenchantmenttableenchantmenttableblock) - [bot.openAnvil(anvilBlock)](#botopenanvilanvilblock) - [bot.openVillager(villagerEntity)](#botopenvillagervillagerentity) - [bot.trade(villagerInstance, tradeIndex, [times])](#bottradevillagerinstance-tradeindex-times) - [bot.setCommandBlock(pos, command, [options])](#botsetcommandblockpos-command-options) - [bot.supportFeature(name)](#botsupportfeaturename) - [bot.waitForTicks(ticks)](#botwaitforticksticks) - [bot.respawn()](#botrespawn) - [Lower level inventory methods](#lower-level-inventory-methods) - [bot.clickWindow(slot, mouseButton, mode)](#botclickwindowslot-mousebutton-mode) - [bot.putSelectedItemRange(start, end, window, slot)](#botputselecteditemrangestart-end-window-slot) - [bot.putAway(slot)](#botputawayslot) - [bot.closeWindow(window)](#botclosewindowwindow) - [bot.transfer(options)](#bottransferoptions) - [bot.openBlock(block, direction?: Vec3, cursorPos?: Vec3)](#botopenblockblock-direction-vec3-cursorpos-vec3) - [bot.openEntity(entity)](#botopenentityentity) - [bot.moveSlotItem(sourceSlot, destSlot)](#botmoveslotitemsourceslot-destslot) - [bot.updateHeldItem()](#botupdatehelditem) - [bot.getEquipmentDestSlot(destination)](#botgetequipmentdestslotdestination) - [bot.creative](#botcreative) - [bot.creative.setInventorySlot(slot, item)](#botcreativesetinventoryslotslot-item) - [bot.creative.clearSlot(slot)](#botcreativeclearslotslot) - [bot.creative.clearInventory()](#botcreativeclearinventory) - [bot.creative.flyTo(destination)](#botcreativeflytodestination) - [bot.creative.startFlying()](#botcreativestartflying) - [bot.creative.stopFlying()](#botcreativestopflying) <!-- END doctoc generated TOC please keep comment here to allow auto update --> # API ## Enums These enums are stored in the language independent [minecraft-data](https://github.com/PrismarineJS/minecraft-data) project, and accessed through [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data). ### minecraft-data The data is available in [node-minecraft-data](https://github.com/PrismarineJS/node-minecraft-data) module `require('minecraft-data')(bot.version)` gives you access to it. ### mcdata.blocks blocks indexed by id ### mcdata.items items indexed by id ### mcdata.materials The key is the material. The value is an object with the key as the item id of the tool and the value as the efficiency multiplier. ### mcdata.recipes recipes indexed by id ### mcdata.instruments instruments indexed by id ### mcdata.biomes biomes indexed by id ### mcdata.entities entities indexed by id ## Classes ### vec3 See [andrewrk/node-vec3](https://github.com/andrewrk/node-vec3) All points in mineflayer are supplied as instances of this class. * x - south * y - up * z - west Functions and methods which require a point argument accept `Vec3` instances as well as an array with 3 values, and an object with `x`, `y`, and `z` properties. ### mineflayer.Location ### Entity Entities represent players, mobs, and objects. They are emitted in many events, and you can access your own entity with `bot.entity`. See [prismarine-entity](https://github.com/PrismarineJS/prismarine-entity) #### Player Skin Data The skin data is stored in the `skinData` property of the player object, if present. ```js // player.skinData { url: 'http://textures.minecraft.net/texture/...', model: 'slim' // or 'classic' } ``` ### Block See [prismarine-block](https://github.com/PrismarineJS/prismarine-block) Also `block.blockEntity` is additional field with block entity data as `Object`. The data in this varies between versions. ```js // 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"}' } ``` Note if you want to get a sign's plain text, you can use [`block.getSignText()`](https://github.com/PrismarineJS/prismarine-block/blob/master/doc/API.md#sign) instead of 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" ] ``` ### Biome See [prismarine-biome](https://github.com/PrismarineJS/prismarine-biome) ### Item See [prismarine-item](https://github.com/PrismarineJS/prismarine-item) ### windows.Window (base class) See [prismarine-windows](https://github.com/PrismarineJS/prismarine-windows) #### window.deposit(itemType, metadata, count, nbt) This function returns a `Promise`, with `void` as its argument when done depositing. * `itemType` - numerical item id * `metadata` - numerical value. `null` means match anything. * `count` - how many to deposit. `null` is an alias to 1. * `nbt` - match nbt data. `null` is do not match nbt. #### window.withdraw(itemType, metadata, count, nbt) This function returns a `Promise`, with `void` as its argument when done withdrawing. Throws and error if the bot has no free room in its inventory. * `itemType` - numerical item id * `metadata` - numerical value. `null` means match anything. * `count` - how many to withdraw. `null` is an alias to 1. * `nbt` - match nbt data. `null` is do not match nbt. #### window.close() ### Recipe See [prismarine-recipe](https://github.com/PrismarineJS/prismarine-recipe) ### mineflayer.Container Extends windows.Window for chests, dispensers, etc... See `bot.openContainer(chestBlock or minecartchestEntity)`. ### mineflayer.Furnace Extends windows.Window for furnace, smelter, etc... See `bot.openFurnace(furnaceBlock)`. #### furnace "update" Fires when `furnace.fuel` and/or `furnace.progress` update. #### furnace.takeInput() This function returns a `Promise`, with `item` as its argument upon completion. #### furnace.takeFuel() This function returns a `Promise`, with `item` as its argument upon completion. #### furnace.takeOutput() This function returns a `Promise`, with `item` as its argument upon completion. #### furnace.putInput(itemType, metadata, count) This function returns a `Promise`, with `void` as its argument upon completion. #### furnace.putFuel(itemType, metadata, count) This function returns a `Promise`, with `void` as its argument upon completion. #### furnace.inputItem() Returns `Item` instance which is the input. #### furnace.fuelItem() Returns `Item` instance which is the fuel. #### furnace.outputItem() Returns `Item` instance which is the output. #### furnace.fuel How much fuel is left between 0 and 1. #### furnace.progress How much cooked the input is between 0 and 1. ### mineflayer.EnchantmentTable Extends windows.Window for enchantment tables See `bot.openEnchantmentTable(enchantmentTableBlock)`. #### enchantmentTable "ready" Fires when `enchantmentTable.enchantments` is fully populated and you may make a selection by calling `enchantmentTable.enchant(choice)`. #### enchantmentTable.targetItem() Gets the target item. This is both the input and the output of the enchantment table. #### enchantmentTable.xpseed The 16 bits xpseed sent by the server. #### enchantmentTable.enchantments Array of length 3 which are the 3 enchantments to choose from. `level` can be `-1` if the server has not sent the data yet. Looks like: ```js [ { level: 3 }, { level: 4 }, { level: 9 } ] ``` #### enchantmentTable.enchant(choice) This function returns a `Promise`, with `item` as its argument when the item has been enchanted. * `choice` - [0-2], the index of the enchantment you want to pick. #### enchantmentTable.takeTargetItem() This function returns a `Promise`, with `item` as its argument upon completion. #### enchantmentTable.putTargetItem(item) This function returns a `Promise`, with `void` as its argument upon completion. #### enchantmentTable.putLapis(item) This function returns a `Promise`, with `void` as its argument upon completion. ### mineflayer.anvil Extends windows.Window for anvils See `bot.openAnvil(anvilBlock)`. #### anvil.combine(itemOne, itemTwo[, name]) This function returns a `Promise`, with `void` as its argument upon completion. #### anvil.combine(item[, name]) This function returns a `Promise`, with `void` as its argument upon completion. #### villager "ready" Fires when `villager.trades` is loaded. #### villager.trades Array of trades. Looks like: ```js [ { firstInput: Item, output: Item, hasSecondItem: false, secondaryInput: null, disabled: false, tooluses: 0, maxTradeuses: 7 }, { firstInput: Item, output: Item, hasSecondItem: false, secondaryInput: null, disabled: false, tooluses: 0, maxTradeuses: 7 }, { firstInput: Item, output: Item, hasSecondItem: true, secondaryInput: Item, disabled: false, tooluses: 0, maxTradeuses: 7 } ] ``` #### villager.trade(tradeIndex, [times]) Is the same as [bot.trade(villagerInstance, tradeIndex, [times])](#bottradevillagerinstance-tradeindex-times) ### mineflayer.ScoreBoard #### ScoreBoard.name Name of the scoreboard. #### ScoreBoard.title The title of the scoreboard (does not always equal the name) #### ScoreBoard.itemsMap An object with all items in the scoreboard in it ```js { wvffle: { name: 'wvffle', value: 3 }, dzikoysk: { name: 'dzikoysk', value: 6 } } ``` #### ScoreBoard.items An array with all sorted items in the scoreboard in it ```js [ { name: 'dzikoysk', value: 6 }, { name: 'wvffle', value: 3 } ] ``` ### mineflayer.Team #### Team.name Name of the team #### Team.friendlyFire #### Team.nameTagVisibility One of `always`, `hideForOtherTeams`, `hideForOwnTeam` #### Team.collisionRule One of `always`, `pushOtherTeams`, `pushOwnTeam` #### Team.color Color (or formatting) name of team, e.g. `dark_green`, `red`, `underlined` #### Team.prefix A chat component containing team prefix #### Team.suffix A chat component containing team suffix #### Team.members Array of team members. Usernames for players and UUIDs for other entities. ### mineflayer.BossBar #### BossBar.title Title of boss bar, instance of ChatMessage #### BossBar.health Percent of boss health, from `0` to `1` #### BossBar.dividers Number of boss bar dividers, one of `0`, `6`, `10`, `12`, `20` #### BossBar.entityUUID Boss bar entity uuid #### BossBar.shouldDarkenSky Determines whether or not to darken the sky #### BossBar.isDragonBar Determines whether or not boss bar is dragon bar #### BossBar.createFog Determines whether or not boss bar creates fog #### BossBar.color Determines what color the boss bar color is, one of `pink`, `blue`, `red`, `green`, `yellow`, `purple`, `white` ### mineflayer.Particle #### Particle.id Particle ID, as defined in the [protocol](https://wiki.vg/Protocol#Particle) #### Particle.name Particle Name, as defined in the [protocol](https://wiki.vg/Protocol#Particle) #### Particle.position Vec3 instance of where the particle was created #### Particle.offset Vec3 instance of the particle's offset #### Particle.longDistanceRender Determines whether or not to force the rendering of a particle despite client particle settings and increases maximum view distance from 256 to 65536 #### Particle.count Amount of particles created #### Particle.movementSpeed Particle speed in a random direction ## Bot ### mineflayer.createBot(options) Create and return an instance of the class bot. `options` is an object containing the optional properties : * username : default to 'Player' * port : default to 25565 * password : can be omitted (if the tokens are also omitted then it tries to connect in offline mode) * host : default to localhost * version : default to automatically guessing the version of the server. Example of value : "1.12.2" * auth : default to 'mojang', can also be 'microsoft' * clientToken : generated if a password is given * accessToken : generated if a password is given * logErrors : true by default, catch errors and log them * hideErrors : true by default, do not log errors (even if logErrors is true) * keepAlive : send keep alive packets : default to true * checkTimeoutInterval : default to `30*1000` (30s), check if keepalive received at that period, disconnect otherwise. * loadInternalPlugins : defaults to true * storageBuilder : an optional function, takes as argument version and worldName and return an instance of something with the same API as prismarine-provider-anvil. Will be used to save the world. * client : an instance of node-minecraft-protocol, if not specified, mineflayer makes its own client. This can be used to enable using mineflayer through a proxy of many clients or a vanilla client and a mineflayer client. * brand : the brand name for the client to use. Defaults to vanilla. Can be used to simulate custom clients for servers that require it. * respawn : when set to false disables bot from automatically respawning, defaults to true. * plugins : object : defaults to {} - pluginName : false : don't load internal plugin with given name ie. `pluginName` - pluginName : true : load internal plugin with given name ie. `pluginName` even though loadInternalplugins is set to false - pluginName : external plugin inject function : loads external plugin, overrides internal plugin with given name ie. `pluginName` * physicsEnabled : true by default, should the bot be affected by physics? can later be modified via bot.physicsEnabled * [chat](#bot.settings.chat) * [colorsEnabled](#bot.settings.colorsEnabled) * [viewDistance](#bot.settings.viewDistance) * [difficulty](#bot.settings.difficulty) * [skinParts](#bot.settings.skinParts) * [enableTextFiltering](#bot.settings.enableTextFiltering) * [enableServerListing](#bot.settings.enableServerListing) * chatLengthLimit : the maximum amount of characters that can be sent in a single message. If this is not set, it will be 100 in < 1.11 and 256 in >= 1.11. * defaultChatPatterns: defaults to true, set to false to not add the patterns such as chat and whisper ### Properties #### bot.registry Instance of minecraft-data used by the bot. Pass this to constructors that expect an instance of minecraft-data, such as prismarine-block. #### bot.world A sync representation of the world. Check the doc at http://github.com/PrismarineJS/prismarine-world ##### world "blockUpdate" (oldBlock, newBlock) Fires when a block updates. Both `oldBlock` and `newBlock` provided for comparison. `oldBlock` may be `null` with normal block updates. ##### world "blockUpdate:(x, y, z)" (oldBlock, newBlock) Fires for a specific point. Both `oldBlock` and `newBlock` provided for comparison. All listeners receive null for `oldBlock` and `newBlock` and get automatically removed when the world is unloaded. `oldBlock` may be `null` with normal block updates. #### bot.entity Your own entity. See `Entity`. #### bot.entities All nearby entities. This object is a map of entityId to entity. #### bot.username Use this to find out your own name. #### bot.spawnPoint Coordinates to the main spawn point, where all compasses point to. #### bot.heldItem 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. #### bot.usingHeldItem Whether the bot is using the item that it's holding, for example eating food or using a shield. #### bot.game.levelType #### bot.game.dimension The bot's current dimension, such as `overworld`, `the_end` or `the_nether`. #### bot.game.difficulty #### bot.game.gameMode #### bot.game.hardcore #### bot.game.maxPlayers #### bot.game.serverBrand #### bot.game.minY minimum y of the world #### bot.game.height world height #### bot.physicsEnabled Enable physics, default true. #### bot.player Bot's player object ```js { username: 'player', displayName: { toString: Function }, // ChatMessage object. gamemode: 0, ping: 28, entity: entity // null if you are too far away } ``` A player's ping starts at 0, you might have to wait a bit for the server to send their actual ping. #### bot.players Map of username to people playing the game. #### bot.tablist bot's tablist object has two keys, `header` and `footer`. ```js { header: { toString: Function }, // ChatMessage object. footer: { toString: Function } // ChatMessage object. } ``` #### bot.isRaining #### bot.rainState A number indicating the current rain level. When it isn't raining, this will be equal to 0. When it starts to rain, this value will increase gradually up to 1. When it stops raining, this value gradually decreases back to 0. Each time `bot.rainState` is changed, the "weatherUpdate" event is emitted. #### bot.thunderState A number indicating the current thunder level. When there isn't a thunderstorm, this will be equal to 0. When a thunderstorm starts, this value will increase gradually up to 1. When the thunderstorm stops, this value gradually decreases back to 0. Each time `bot.thunderState` is changed, the "weatherUpdate" event is emitted. This is the same as `bot.rainState`, but for thunderstorms. For thunderstorms, both `bot.rainState` and `bot.thunderState` will change. #### bot.chatPatterns This is an array of pattern objects, of the following format: { /regex/, "chattype", "description") * /regex/ - a regular expression pattern, that should have at least two capture groups * 'chattype' - the type of chat the pattern matches, ex "chat" or "whisper", but can be anything. * 'description' - description of what the pattern is for, optional. #### bot.settings.chat Choices: * `enabled` (default) * `commandsOnly` * `disabled` #### bot.settings.colorsEnabled Default true, whether or not you receive color codes in chats from the server. #### bot.settings.viewDistance Can be a string listed below or a positive number. Choices: * `far` (default) * `normal` * `short` * `tiny` #### bot.settings.difficulty Same as from server.properties. #### bot.settings.skinParts These boolean Settings control if extra Skin Details on the own players' skin should be visible ##### bot.settings.skinParts.showCape - boolean If you have a cape you can turn it off by setting this to false. ##### bot.settings.skinParts.showJacket - boolean ##### bot.settings.skinParts.showLeftSleeve - boolean ##### bot.settings.skinParts.showRightSleeve - boolean ##### bot.settings.skinParts.showLeftPants - boolean ##### bot.settings.skinParts.showRightPants - boolean ##### bot.settings.skinParts.showHat - boolean #### bot.settings.enableTextFiltering - boolean Unused, defaults to false in Notchian (Vanilla) client. #### bot.settings.enableServerListing - boolean This setting is sent to the server to determine whether the player should show up in server listings #### bot.experience.level #### bot.experience.points Total experience points. #### bot.experience.progress Between 0 and 1 - amount to get to the next level. #### bot.health Number in the range [0, 20] representing the number of half-hearts. #### bot.food Number in the range [0, 20] representing the number of half-turkey-legs. #### bot.foodSaturation Food saturation acts as a food "overcharge". Food values will not decrease while the saturation is over zero. Players logging in automatically get a saturation of 5.0. Eating food increases the saturation as well as the food bar. #### bot.oxygenLevel Number in the range [0, 20] representing the number of water-icons known as oxygen level. #### bot.physics Edit these numbers to tweak gravity, jump speed, terminal velocity, etc. Do this at your own risk. #### bot.fireworkRocketDuration How many physics ticks worth of firework rocket boost are left. #### bot.simpleClick.leftMouse (slot) abstraction over `bot.clickWindow(slot, 0, 0)` #### bot.simpleClick.rightMouse (slot) abstraction over `bot.clickWindow(slot, 1, 0)` #### bot.time.doDaylightCycle Whether or not the gamerule doDaylightCycle is true or false. #### bot.time.bigTime The total number of ticks since day 0. This value is of type BigInt and is accurate even at very large values. (more than 2^51 - 1 ticks) #### bot.time.time The total numbers of ticks since day 0. Because the Number limit of Javascript is at 2^51 - 1 bot.time.time becomes inaccurate higher than this limit and the use of bot.time.bigTime is recommended. Realistically though you'll probably never need to use bot.time.bigTime as it will only reach 2^51 - 1 ticks naturally after ~14280821 real years. #### bot.time.timeOfDay Time of the day, in ticks. Time is based on ticks, where 20 ticks happen every second. There are 24000 ticks in a day, making Minecraft days exactly 20 minutes long. The time of day is based on the timestamp modulo 24000. 0 is sunrise, 6000 is noon, 12000 is sunset, and 18000 is midnight. #### bot.time.day Day of the world. #### bot.time.isDay Whether it is day or not. Based on whether the current time of day is between 0 and 13000 ticks (day + sunset). #### bot.time.moonPhase Phase of the moon. 0-7 where 0 is full moon. #### bot.time.bigAge Age of the world, in ticks. This value is of type BigInt and is accurate even at very large values. (more than 2^51 - 1 ticks) #### bot.time.age Age of the world, in ticks. Because the Number limit of Javascript is at 2^51 - 1 bot.time.age becomes inaccurate higher than this limit and the use of bot.time.bigAge is recommended. Realistically though you'll probably never need to use bot.time.bigAge as it will only reach 2^51 - 1 ticks naturally after ~14280821 real years. #### bot.quickBarSlot Which quick bar slot is selected (0 - 8). #### bot.inventory A [`Window`](https://github.com/PrismarineJS/prismarine-windows#windowswindow-base-class) instance representing your inventory. #### bot.targetDigBlock The `block` that you are currently digging, or `null`. #### bot.isSleeping Boolean, whether or not you are in bed. #### bot.scoreboards All scoreboards known to the bot in an object scoreboard name -> scoreboard. #### bot.scoreboard All scoreboards known to the bot in an object scoreboard displaySlot -> scoreboard. * `belowName` - scoreboard placed in belowName * `sidebar` - scoreboard placed in sidebar * `list` - scoreboard placed in list * `0-18` - slots defined in [protocol](https://wiki.vg/Protocol#Display_Scoreboard) #### bot.teams All teams known to the bot #### bot.teamMap Mapping of member to team. Uses usernames for players and UUIDs for entities. #### bot.controlState An object whose keys are the main control states: ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak']. Setting values for this object internally calls [bot.setControlState](#botsetcontrolstatecontrol-state). ### Events #### "chat" (username, message, translate, jsonMsg, matches) Only emitted when a player chats publicly. * `username` - who said the message (compare with `bot.username` to ignore your own chat) * `message` - stripped of all color and control characters * `translate` - chat message type. Null for most bukkit chat messages * `jsonMsg` - unmodified JSON message from the server * `matches` - array of returned matches from regular expressions. May be null #### "whisper" (username, message, translate, jsonMsg, matches) Only emitted when a player chats to you privately. * `username` - who said the message * `message` - stripped of all color and control characters * `translate` - chat message type. Null for most bukkit chat messages * `jsonMsg` - unmodified JSON message from the server * `matches` - array of returned matches from regular expressions. May be null #### "actionBar" (jsonMsg, verified) Emitted for every server message which appears on the Action Bar. * `jsonMsg` - unmodified JSON message from the server * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect #### "message" (jsonMsg, position, sender, verified) Emitted for every server message, including chats. * `jsonMsg` - [ChatMessage](https://github.com/PrismarineJS/prismarine-chat) object containing the formatted chat message. Might additionally have the following properties: * unsigned - Unsigned ChatMessage object. Only present in 1.19.2+, and only when the server allows insecure chat and the server modified the chat message without the user's signature * `position` - (>= 1.8.1): position of Chat message can be * chat * system * game_info * `sender` - UUID of sender if known (1.16+), else null * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect #### "messagestr" (message, messagePosition, jsonMsg, sender, verified) Alias for the "message" event but it calls .toString() on the prismarine-message object to get a string for the message before emitting. * `sender` - UUID of sender if known (1.16+), else null * `verified` -> null if non signed, true if signed and correct, false if signed and incorrect #### "inject_allowed" Fires when the index file has been loaded, you can load mcData and plugins here but it's better to wait for "spawn" event. #### "login" Fires after you successfully login to the server. You probably want to wait for the `spawn` event before doing anything though. #### "spawn" 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. #### "respawn" Emitted when you change dimensions and just before you spawn. Usually you want to ignore this event and wait until the "spawn" event instead. #### "game" Emitted when the server changes any of the game properties. #### "resourcePack" (url, hash) Emitted when the server sends a resource pack. #### "title" (title, type) Emitted when the server sends a title * `title` - title's text * `type` - title's type "subtitle", "title" #### "title_times" (fadeIn, stay, fadeOut) Emitted when the server sends a title times packet (i.e., when the fade-in, stay, and fade-out times for titles are set or updated). * `fadeIn` - fade-in time in ticks (number) * `stay` - stay time in ticks (number) * `fadeOut` - fade-out time in ticks (number) Example: ```js bot.on('title_times', (fadeIn, stay, fadeOut) => { console.log(`Title times: fadeIn=${fadeIn}, stay=${stay}, fadeOut=${fadeOut}`) }) ``` #### "title_clear" Emitted when the server clears all titles. #### "rain" Emitted when it starts or stops raining. If you join a server where it is already raining, this event will fire. #### "weatherUpdate" Emitted when either `bot.thunderState` or `bot.rainState` changes. If you join a server where it is already raining, this event will fire. #### "time" Emitted when the server sends a time update. See `bot.time`. #### "kicked" (reason, loggedIn) Emitted when the bot is kicked from the server. `reason` is a chat message explaining why you were kicked. `loggedIn` is `true` if the client was kicked after successfully logging in, or `false` if the kick occurred in the login phase. #### "end" (reason) Emitted when you are no longer connected to the server. `reason` is a string explaining why the client was disconnected. (defaults to 'socketClosed') #### "error" (err) Emitted when an error occurs. #### "spawnReset" Fires when you cannot spawn in your bed and your spawn point gets reset. #### "death" Fires when you die. #### "health" Fires when your hp or food change. #### "breath" Fires when your oxygen level change. #### "entityAttributes" (entity) Fires when an attribute of an entity changes. #### "entitySwingArm" (entity) #### "entityHurt" (entity) #### "entityDead" (entity) #### "entityTaming" (entity) #### "entityTamed" (entity) #### "entityShakingOffWater" (entity) #### "entityEatingGrass" (entity) #### "entityHandSwap" (entity) #### "entityWake" (entity) #### "entityEat" (entity) #### "entityCriticalEffect" (entity) #### "entityMagicCriticalEffect" (entity) #### "entityCrouch" (entity) #### "entityUncrouch" (entity) #### "entityEquip" (entity) #### "entitySleep" (entity) #### "entitySpawn" (entity) #### "entityElytraFlew" (entity) An entity started elytra flying. #### "itemDrop" (entity) #### "playerCollect" (collector, collected) An entity picked up an item. * `collector` - entity that picked up the item. * `collected` - the entity that was the item on the ground. #### "entityGone" (entity) #### "entityMoved" (entity) #### "entityDetach" (entity, vehicle) #### "entityAttach" (entity, vehicle) An entity is attached to a vehicle, such as a mine cart or boat. * `entity` - the entity hitching a ride * `vehicle` - the entity that is the vehicle #### "entityUpdate" (entity) #### "entityEffect" (entity, effect) #### "entityEffectEnd" (entity, effect) #### "playerJoined" (player) #### "playerUpdated" (player) #### "playerLeft" (player) #### "blockUpdate" (oldBlock, newBlock) (It is better to use this event from bot.world instead of bot directly) Fires when a block updates. Both `oldBlock` and `newBlock` provided for comparison. Note that `oldBlock` may be `null`. #### "blockUpdate:(x, y, z)" (oldBlock, newBlock) (It is better to use this event from bot.world instead of bot directly) Fires for a specific point. Both `oldBlock` and `newBlock` provided for comparison. Note that `oldBlock` may be `null`. #### "blockPlaced" (oldBlock, newBlock) Fires when bot places block. Both `oldBlock` and `newBlock` provided for comparison. Note that `oldBlock` may be `null`. #### "chunkColumnLoad" (point) #### "chunkColumnUnload" (point) Fires when a chunk has updated. `point` is the coordinates to the corner of the chunk with the smallest x, y, and z values. #### "soundEffectHeard" (soundName, position, volume, pitch) Fires when the client hears a named sound effect. * `soundName`: name of the sound effect * `position`: a Vec3 instance where the sound originates * `volume`: floating point volume, 1.0 is 100% * `pitch`: integer pitch, 63 is 100% #### "hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch) Fires when the client hears a hardcoded sound effect. * `soundId`: id of the sound effect * `soundCategory`: category of the sound effect * `position`: a Vec3 instance where the sound originates * `volume`: floating point volume, 1.0 is 100% * `pitch`: integer pitch, 63 is 100% #### "noteHeard" (block, instrument, pitch) Fires when a note block goes off somewhere. * `block`: a Block instance