Table of Contents generated with DocToc
- API
- Enums
- Classes
- Bot
- mineflayer.createBot(options)
- Properties
- bot.registry
- bot.world
- bot.entity
- bot.entities
- bot.username
- bot.spawnPoint
- bot.heldItem
- bot.usingHeldItem
- bot.game.levelType
- bot.game.dimension
- bot.game.difficulty
- bot.game.gameMode
- bot.game.hardcore
- bot.game.maxPlayers
- bot.game.serverBrand
- bot.game.minY
- bot.game.height
- bot.physicsEnabled
- bot.player
- bot.players
- bot.tablist
- bot.isRaining
- bot.rainState
- bot.thunderState
- bot.chatPatterns
- bot.settings.chat
- bot.settings.colorsEnabled
- bot.settings.viewDistance
- bot.settings.difficulty
- bot.settings.skinParts
- bot.settings.skinParts.showCape - boolean
- 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
- bot.settings.enableServerListing - boolean
- bot.experience.level
- bot.experience.points
- bot.experience.progress
- bot.health
- bot.food
- bot.foodSaturation
- bot.oxygenLevel
- bot.physics
- bot.fireworkRocketDuration
- bot.simpleClick.leftMouse (slot)
- bot.simpleClick.rightMouse (slot)
- bot.time.doDaylightCycle
- bot.time.bigTime
- bot.time.time
- bot.time.timeOfDay
- bot.time.day
- bot.time.isDay
- bot.time.moonPhase
- bot.time.bigAge
- bot.time.age
- bot.quickBarSlot
- bot.inventory
- bot.targetDigBlock
- bot.isSleeping
- bot.scoreboards
- bot.scoreboard
- bot.teams
- bot.teamMap
- bot.controlState
- Events
- "chat" (username, message, translate, jsonMsg, matches)
- "whisper" (username, message, translate, jsonMsg, matches)
- "actionBar" (jsonMsg, verified)
- "message" (jsonMsg, position, sender, verified)
- "messagestr" (message, messagePosition, jsonMsg, sender, verified)
- "inject_allowed"
- "login"
- "spawn"
- "respawn"
- "game"
- "resourcePack" (url, hash)
- "title"
- "rain"
- "weatherUpdate"
- "time"
- "kicked" (reason, loggedIn)
- "end" (reason)
- "error" (err)
- "spawnReset"
- "death"
- "health"
- "breath"
- "entityAttributes" (entity)
- "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)
- "itemDrop" (entity)
- "playerCollect" (collector, collected)
- "entityGone" (entity)
- "entityMoved" (entity)
- "entityDetach" (entity, vehicle)
- "entityAttach" (entity, vehicle)
- "entityUpdate" (entity)
- "entityEffect" (entity, effect)
- "entityEffectEnd" (entity, effect)
- "playerJoined" (player)
- "playerUpdated" (player)
- "playerLeft" (player)
- "blockUpdate" (oldBlock, newBlock)
- "blockUpdate:(x, y, z)" (oldBlock, newBlock)
- "blockPlaced" (oldBlock, newBlock)
- "chunkColumnLoad" (point)
- "chunkColumnUnload" (point)
- "soundEffectHeard" (soundName, position, volume, pitch)
- "hardcodedSoundEffectHeard" (soundId, soundCategory, position, volume, pitch)
- "noteHeard" (block, instrument, pitch)
- "pistonMove" (block, isPulling, direction)
- "chestLidMove" (block, isOpen, block2)
- "blockBreakProgressObserved" (block, destroyStage, entity)
- "blockBreakProgressEnd" (block, entity)
- "diggingCompleted" (block)
- "diggingAborted" (block)
- "usedFirework" (fireworkEntityId)
- "move"
- "forcedMove"
- "mount"
- "dismount" (vehicle)
- "windowOpen" (window)
- "windowClose" (window)
- "sleep"
- "wake"
- "experience"
- "scoreboardCreated" (scoreboard)
- "scoreboardDeleted" (scoreboard)
- "scoreboardTitleChanged" (scoreboard)
- "scoreUpdated" (scoreboard, item)
- "scoreRemoved" (scoreboard, item)
- "scoreboardPosition" (position, scoreboard)
- "teamCreated" (team)
- "teamRemoved" (team)
- "teamUpdated" (team)
- "teamMemberAdded" (team)
- "teamMemberRemoved" (team)
- "bossBarCreated" (bossBar)
- "bossBarDeleted" (bossBar)
- "bossBarUpdated" (bossBar)
- "heldItemChanged" (heldItem)
- "physicsTick" ()
- "chat:name" (matches)
- "particle"
- Functions
- bot.blockAt(point, extraInfos=true)
- bot.waitForChunksToLoad()
- bot.blockInSight(maxSteps, vectorLength)
- bot.blockAtCursor(maxDistance=256)
- bot.entityAtCursor(maxDistance=3.5)
- bot.blockAtEntityCursor(entity=bot.entity, maxDistance=256)
- bot.canSeeBlock(block)
- bot.findBlocks(options)
- bot.findBlock(options)
- bot.canDigBlock(block)
- bot.recipesFor(itemType, metadata, minResultCount, craftingTable)
- bot.recipesAll(itemType, metadata, craftingTable)
- bot.nearestEntity(match = (entity) => { return true })
- Methods
- bot.end(reason)
- bot.quit(reason)
- bot.tabComplete(str, [assumeCommand], [sendBlockInSight], [timeout])
- bot.chat(message)
- bot.whisper(username, message)
- bot.chatAddPattern(pattern, chatType, description)
- bot.addChatPattern(name, pattern, chatPatternOptions)
- bot.addChatPatternSet(name, patterns, chatPatternOptions)
- bot.removeChatPattern(name)
- bot.awaitMessage(...args)
- bot.setSettings(options)
- bot.loadPlugin(plugin)
- bot.loadPlugins(plugins)
- bot.hasPlugin(plugin)
- bot.sleep(bedBlock)
- bot.isABed(bedBlock)
- bot.wake()
- bot.setControlState(control, state)
- bot.getControlState(control)
- bot.clearControlStates()
- bot.getExplosionDamages(entity, position, radius, [rawDamages])
- bot.lookAt(point, [force])
- bot.look(yaw, pitch, [force])
- bot.updateSign(block, text, back = false)
- bot.equip(item, destination)
- bot.unequip(destination)
- bot.tossStack(item)
- bot.toss(itemType, metadata, count)
- bot.elytraFly()
- bot.dig(block, [forceLook = true], [digFace])
- bot.stopDigging()
- bot.digTime(block)
- bot.acceptResourcePack()
- bot.denyResourcePack()
- bot.placeBlock(referenceBlock, faceVector)
- bot.placeEntity(referenceBlock, faceVector)
- bot.activateBlock(block, direction?: Vec3, cursorPos?: Vec3)
- bot.activateEntity(entity)
- bot.activateEntityAt(entity, position)
- bot.consume()
- bot.fish()
- bot.activateItem(offHand=false)
- bot.deactivateItem()
- bot.useOn(targetEntity)
- bot.attack(entity, swing = true)
- bot.swingArm([hand], showHand)
- bot.mount(entity)
- bot.dismount()
- bot.moveVehicle(left,forward)
- bot.setQuickBarSlot(slot)
- bot.craft(recipe, count, craftingTable)
- bot.writeBook(slot, pages)
- bot.openContainer(containerBlock or containerEntity, direction?, cursorPos?)
- bot.openChest(chestBlock or minecartchestEntity, direction?, cursorPos?)
- bot.openFurnace(furnaceBlock)
- bot.openDispenser(dispenserBlock)
- bot.openEnchantmentTable(enchantmentTableBlock)
- bot.openAnvil(anvilBlock)
- bot.openVillager(villagerEntity)
- bot.trade(villagerInstance, tradeIndex, [times])
- bot.setCommandBlock(pos, command, [options])
- bot.supportFeature(name)
- bot.waitForTicks(ticks)
- bot.respawn()
- Lower level inventory methods
- bot.clickWindow(slot, mouseButton, mode)
- bot.putSelectedItemRange(start, end, window, slot)
- bot.putAway(slot)
- bot.closeWindow(window)
- bot.transfer(options)
- bot.openBlock(block, direction?: Vec3, cursorPos?: Vec3)
- bot.openEntity(entity)
- bot.moveSlotItem(sourceSlot, destSlot)
- bot.updateHeldItem()
- bot.getEquipmentDestSlot(destination)
- bot.creative
These enums are stored in the language independent minecraft-data project, and accessed through node-minecraft-data.
The data is available in node-minecraft-data module
require('minecraft-data')(bot.version)
gives you access to it.
blocks indexed by id
items indexed by id
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.
recipes indexed by id
instruments indexed by id
biomes indexed by id
entities indexed by id
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.
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
The skin data is stored in the skinData
property of the player object, if present.
// player.skinData
{
url: 'http://textures.minecraft.net/texture/...',
model: 'slim' // or 'classic'
}
See prismarine-block
Also block.blockEntity
is additional field with block entity data as Object
. The data in this varies between versions.
// 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()
instead of unstable blockEntity data.
> block = bot.blockAt(new Vec3(0, 60, 0)) // assuming a sign is here
> block.getSignText()
[ "Front text\nHello world", "Back text\nHello world" ]
See prismarine-biome
See prismarine-item
This function returns a Promise
, with void
as its argument when done depositing.
itemType
- numerical item idmetadata
- 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.
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 idmetadata
- 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.
Extends windows.Window for chests, dispensers, etc...
See bot.openContainer(chestBlock or minecartchestEntity)
.
Extends windows.Window for furnace, smelter, etc...
See bot.openFurnace(furnaceBlock)
.
Fires when furnace.fuel
and/or furnace.progress
update.
This function returns a Promise
, with item
as its argument upon completion.
This function returns a Promise
, with item
as its argument upon completion.
This function returns a Promise
, with item
as its argument upon completion.
This function returns a Promise
, with void
as its argument upon completion.
This function returns a Promise
, with void
as its argument upon completion.
Returns Item
instance which is the input.
Returns Item
instance which is the fuel.
Returns Item
instance which is the output.
How much fuel is left between 0 and 1.
How much cooked the input is between 0 and 1.
Extends windows.Window for enchantment tables
See bot.openEnchantmentTable(enchantmentTableBlock)
.
Fires when enchantmentTable.enchantments
is fully populated and you
may make a selection by calling enchantmentTable.enchant(choice)
.
Gets the target item. This is both the input and the output of the enchantment table.
The 16 bits xpseed sent by the server.
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:
[
{
level: 3
},
{
level: 4
},
{
level: 9
}
]
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.
This function returns a Promise
, with item
as its argument upon completion.
This function returns a Promise
, with void
as its argument upon completion.
This function returns a Promise
, with void
as its argument upon completion.
Extends windows.Window for anvils
See bot.openAnvil(anvilBlock)
.
This function returns a Promise
, with void
as its argument upon completion.
This function returns a Promise
, with void
as its argument upon completion.
Fires when villager.trades
is loaded.
Array of trades.
Looks like:
[
{
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
}
]
Is the same as bot.trade(villagerInstance, tradeIndex, [times])
Name of the scoreboard.
The title of the scoreboard (does not always equal the name)
An object with all items in the scoreboard in it
{
wvffle: { name: 'wvffle', value: 3 },
dzikoysk: { name: 'dzikoysk', value: 6 }
}
An array with all sorted items in the scoreboard in it
[
{ name: 'dzikoysk', value: 6 },
{ name: 'wvffle', value: 3 }
]
Name of the team
One of always
, hideForOtherTeams
, hideForOwnTeam
One of always
, pushOtherTeams
, pushOwnTeam
Color (or formatting) name of team, e.g. dark_green
, red
, underlined
A chat component containing team prefix
A chat component containing team suffix
Array of team members. Usernames for players and UUIDs for other entities.
Title of boss bar, instance of ChatMessage
Percent of boss health, from 0
to 1
Number of boss bar dividers, one of 0
, 6
, 10
, 12
, 20
Boss bar entity uuid
Determines whether or not to darken the sky
Determines whether or not boss bar is dragon bar
Determines whether or not boss bar creates fog
Determines what color the boss bar color is, one of pink
, blue
, red
, green
, yellow
, purple
, white
Particle ID, as defined in the protocol
Particle Name, as defined in the protocol
Vec3 instance of where the particle was created
Vec3 instance of the particle's offset
Determines whether or not to force the rendering of a particle despite client particle settings and increases maximum view distance from 256 to 65536
Amount of particles created
Particle speed in a random direction
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
- pluginName : false : don't load internal plugin with given name ie.
- physicsEnabled : true by default, should the bot be affected by physics? can later be modified via bot.physicsEnabled
- chat
- colorsEnabled
- viewDistance
- difficulty
- skinParts
- enableTextFiltering
- 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
Instance of minecraft-data used by the bot. Pass this to constructors that expect an instance of minecraft-data, such as prismarine-block.
A sync representation of the world. Check the doc at https://github.com/PrismarineJS/prismarine-world
Fires when a block updates. Both oldBlock
and newBlock
provided for
comparison.
oldBlock
may be null
with normal block updates.
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.
Your own entity. See Entity
.
All nearby entities. This object is a map of entityId to entity.
Use this to find out your own name.
Coordinates to the main spawn point, where all compasses point to.
The item in the bot's hand, represented as a prismarine-item instance specified with arbitrary metadata, nbtdata, etc.
Whether the bot is using the item that it's holding, for example eating food or using a shield.
The bot's current dimension, such as overworld
, the_end
or the_nether
.
minimum y of the world
world height
Enable physics, default true.
Bot's player object
{
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.
Map of username to people playing the game.
bot's tablist object has two keys, header
and footer
.
{
header: { toString: Function }, // ChatMessage object.
footer: { toString: Function } // ChatMessage object.
}
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.
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.
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.
Choices:
enabled
(default)commandsOnly
disabled
Default true, whether or not you receive color codes in chats from the server.
Can be a string listed below or a positive number. Choices:
far
(default)normal
short
tiny
Same as from server.properties.
These boolean Settings control if extra Skin Details on the own players' skin should be visible
If you have a cape you can turn it off by setting this to false.
Unused, defaults to false in Notchian (Vanilla) client.
This setting is sent to the server to determine whether the player should show up in server listings
Total experience points.
Between 0 and 1 - amount to get to the next level.
Number in the range [0, 20] representing the number of half-hearts.
Number in the range [0, 20] representing the number of half-turkey-legs.
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.
Number in the range [0, 20] representing the number of water-icons known as oxygen level.
Edit these numbers to tweak gravity, jump speed, terminal velocity, etc. Do this at your own risk.
How many physics ticks worth of firework rocket boost are left.
abstraction over bot.clickWindow(slot, 0, 0)
abstraction over bot.clickWindow(slot, 1, 0)
Whether or not the gamerule doDaylightCycle is true or false.
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)
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.
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.
Day of the world.
Whether it is day or not.
Based on whether the current time of day is between 13000 and 23000 ticks.
Phase of the moon.
0-7 where 0 is full moon.
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)
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.
Which quick bar slot is selected (0 - 8).
A Window
instance representing your inventory.
The block
that you are currently digging, or null
.
Boolean, whether or not you are in bed.
All scoreboards known to the bot in an object scoreboard name -> scoreboard.
All scoreboards known to the bot in an object scoreboard displaySlot -> scoreboard.
belowName
- scoreboard placed in belowNamesidebar
- scoreboard placed in sidebarlist
- scoreboard placed in list0-18
- slots defined in protocol
All teams known to the bot
Mapping of member to team. Uses usernames for players and UUIDs for entities.
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.
Only emitted when a player chats publicly.
username
- who said the message (compare withbot.username
to ignore your own chat)message
- stripped of all color and control characterstranslate
- chat message type. Null for most bukkit chat messagesjsonMsg
- unmodified JSON message from the servermatches
- array of returned matches from regular expressions. May be null
Only emitted when a player chats to you privately.
username
- who said the messagemessage
- stripped of all color and control characterstranslate
- chat message type. Null for most bukkit chat messagesjsonMsg
- unmodified JSON message from the servermatches
- array of returned matches from regular expressions. May be null
Emitted for every server message which appears on the Action Bar.
jsonMsg
- unmodified JSON message from the serververified
-> null if non signed, true if signed and correct, false if signed and incorrect
Emitted for every server message, including chats.
-
jsonMsg
- ChatMessage 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
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
Fires when the index file has been loaded, you can load mcData and plugins here but it's better to wait for "spawn" event.
Fires after you successfully login to the server.
You probably want to wait for the spawn
event
before doing anything though.
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.
Emitted when you change dimensions and just before you spawn. Usually you want to ignore this event and wait until the "spawn" event instead.
Emitted when the server changes any of the game properties.
Emitted when the server sends a resource pack.
Emitted when the server sends a title
text
- title's text
Emitted when it starts or stops raining. If you join a server where it is already raining, this event will fire.
Emitted when either bot.thunderState
or bot.rainState
changes.
If you join a server where it is already raining, this event will fire.
Emitted when the server sends a time update. See bot.time
.
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.
Emitted when you are no longer connected to the server.
reason
is a string explaining why the client was disconnected. (defaults to 'socketClosed')
Emitted when an error occurs.
Fires when you cannot spawn in your bed and your spawn point gets reset.
Fires when you die.
Fires when your hp or food change.
Fires when your oxygen level change.
Fires when an attribute of an entity changes.
An entity started elytra flying.
An entity picked up an item.
collector
- entity that picked up the item.collected
- the entity that was the item on the ground.
An entity is attached to a vehicle, such as a mine cart or boat.
entity
- the entity hitching a ridevehicle
- the entity that is the vehicle
(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
.
(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
.
Fires when bot places block. Both oldBlock
and newBlock
provided for
comparison.
Note that oldBlock
may be null
.
Fires when a chunk has updated. point
is the coordinates to the corner
of the chunk with the smallest x, y, and z values.
Fires when the client hears a named sound effect.
soundName
: name of the sound effectposition
: a Vec3 instance where the sound originatesvolume
: floating point volume, 1.0 is 100%pitch
: integer pitch, 63 is 100%
Fires when the client hears a hardcoded sound effect.
soundId
: id of the sound effectsoundCategory
: category of the sound effectposition
: a Vec3 instance where the sound originatesvolume
: floating point volume, 1.0 is 100%pitch
: integer pitch, 63 is 100%
Fires when a note block goes off somewhere.
block
: a Block instance, the block that emitted the noiseinstrument
:id
: integer idname
: one of [harp
,doubleBass
,snareDrum
,sticks
,bassDrum
].
pitch
: The pitch of the note (between 0-24 inclusive where 0 is the lowest and 24 is the highest). More information about how the pitch values correspond to notes in real life are available on the official Minecraft wiki.
block
: a Block instance, the block whose lid opened. The right block if it's a double chestisOpen
: number of players that have the chest open. 0 if it's closedblock2
: a Block instance, the other half of the block whose lid opened. null if it's not a double chest
Fires when the client observes a block in the process of being broken.
block
: a Block instance, the block being brokendestroyStage
: integer corresponding to the destroy progress (0-9)entity
: the entity which is breaking the block.
Fires when the client observes a block stops being broken. This occurs whether the process was completed or aborted.
block
: a Block instance, the block no longer being brokenentity
: the entity which has stopped breaking the block
block
- the block that no longer exists
block
- the block that still exists
Fires when the bot uses a firework while elytra flying.
fireworkEntityId
- the entity id of the firework.
Fires when the bot moves. If you want the current position, use
bot.entity.position
and for normal moves if you want the previous position, use
bot.entity.position.minus(bot.entity.velocity)
.
Fires when the bot is force moved by the server (teleport, spawning, ...). If you want the current position, use
bot.entity.position
.
Fires when you mount an entity such as a minecart. To get access
to the entity, use bot.vehicle
.
To mount an entity, use mount
.
Fires when you dismount from an entity.
Fires when you begin using a workbench, chest, brewing stand, etc.
Fires when you may no longer work with a workbench, chest, etc.
Fires when you sleep.
Fires when you wake up.
Fires when bot.experience.*
has updated.
Fires when a scoreboard is added.
Fires when a scoreboard is deleted.
Fires when a scoreboard's title is updated.
Fires when the score of a item in a scoreboard is updated.
Fires when the score of a item in a scoreboard is removed.
Fires when the position of a scoreboard is updated.
Fires when a team is added.
Fires when a team is removed.
Fires when a team is updated.
Fires when a team member or multiple members are added to a team.
Fires when a team member or multiple members are removed from a team.
Fires when new boss bar is created.
Fires when new boss bar is deleted.
Fires when new boss bar is updated.
Fires when the held item is changed.
Fires every tick if bot.physicsEnabled is set to true.
Fires when the all of a chat pattern's regexs have matches
Fires when a particle is created
Returns the block at point
or null
if that point is not loaded. If extraInfos
set to true, also returns information about signs, paintings and block entities (slower).
See Block
.
This function returns a Promise
, with void
as its argument when many chunks have loaded.
Deprecated, use blockAtCursor
instead.
Returns the block at which bot is looking at or null
maxSteps
- Number of steps to raytrace, defaults to 256.vectorLength
- Length of raytracing vector, defaults to5/16
.
Returns the block at which bot is looking at or null
maxDistance
- The maximum distance the block can be from the eye, defaults to 256.
Returns the entity at which bot is looking at or null
maxDistance
- The maximum distance the entity can be from the eye, defaults to 3.5.
Returns the block at which specific entity is looking at or null
entity
- Entity data asObject
maxDistance
- The maximum distance the block can be from the eye, defaults to 256.
Returns true or false depending on whether the bot can see the specified block
.
Finds the closest blocks from the given point.
options
- Options for the search:point
- The start position of the search (center). Default is the bot position.matching
- 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
- 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 touseExtraInfo
with additional info
- boolean - Provide your
maxDistance
- The furthest distance for the search, defaults to 16.count
- 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.
Returns an array (possibly empty) with the found block coordinates (not the blocks). The array is sorted (closest first)
Alias for bot.blockAt(bot.findBlocks(options)[0])
. Return a single block or null
.
Returns whether block
is diggable and within range.
Returns a list of Recipe
instances that you could use to craft itemType
with metadata
.
itemType
- numerical item id of the thing you want to craftmetadata
- the numerical metadata value of the item you want to craftnull
matches any metadata.minResultCount
- based on your current inventory, any recipe from the returned list will be able to produce this many items.null
is an alias for1
.craftingTable
- aBlock
instance. Ifnull
, only recipes that can be performed in your inventory window will be included in the list.
The same as bot.recipesFor except that it does not check whether the bot has enough materials for the recipe.
Return the nearest entity to the bot, matching the function (default to all entities). Return null if no entity is found.
Example:
const cow = bot.nearestEntity(entity => entity.name.toLowerCase() === 'cow') // we use .toLowercase() because in 1.8 cow was capitalized, for newer versions that can be omitted
End the connection with the server.
reason
- Optional string that states the reason of the end.
Gracefully disconnect from the server with the given reason (defaults to 'disconnect.quitting').
This function returns a Promise
, with matches
as its argument upon completion.
Requests chat completion from the server.
str
- String to complete.assumeCommand
- Field sent to server, defaults to false.sendBlockInSight
- Field sent to server, defaults to true. Set this option to false if you want more performance.timeout
- Timeout in milliseconds, after which the function will return an empty array, defaults to 5000.
Sends a publicly broadcast chat message. Breaks up big messages into multiple chat messages as necessary.
Shortcut for "/tell ". All split messages will be whispered to username.
Deprecated, use addChatPattern
instead.
Adds a regex pattern to the bot's chat matching. Useful for bukkit servers where the chat format changes a lot.
pattern
- regular expression to match chatchatType
- the event the bot emits when the pattern matches. Eg: "chat" or "whisper"- 'description ' - Optional, describes what the pattern is for
** this is an alias of bot.addChatPatternSet(name, [pattern], chatPatternOptions)
make an event that is called every time the pattern is matched to a message,
the event will be called "chat:name"
, with name being the name passed
name
- the name used to listen for the eventpattern
- regular expression to match to messages receivedchatPatternOptions
- objectrepeat
- defaults to true, whether to listen for this event after the first matchparse
- instead of returning the actual message that was matched, return the capture groups from the regexdeprecated
- (unstable) used by bot.chatAddPattern to keep compatibility, likely to be removed
returns a number which can be used with bot.removeChatPattern() to only delete this pattern
- 👀 cf. examples/chat_parsing
make an event that is called every time all patterns have been matched to messages,
the event will be called "chat:name"
, with name being the name passed
name
- the name used to listen for the eventpatterns
- array of regular expression to match to messages receivedchatPatternOptions
- objectrepeat
- defaults to true, whether to listen for this event after the first matchparse
- instead of returning the actual message that was matched, return the capture groups from the regex
returns a number which can be used with bot.removeChatPattern() to only delete this patternset
- 👀 cf. examples/chat_parsing
removes a chat pattern(s)
name
: string or number
if name is a string, all patterns that have that name will be removed else if name is a number, only that exact pattern will be removed
promise that is resolved when one of the messages passed as an arg is resolved
Example:
async function wait () {
await bot.awaitMessage('<flatbot> hello world') // resolves on "hello world" in chat by flatbot
await bot.awaitMessage(['<flatbot> hello', '<flatbot> world']) // resolves on "hello" or "world" in chat by flatbot
await bot.awaitMessage(['<flatbot> hello', '<flatbot> world'], ['<flatbot> im', '<flatbot> batman']) // resolves on "hello" or "world" or "im" or "batman" in chat by flatbot
await bot.awaitMessage('<flatbot> hello', '<flatbot> world') // resolves on "hello" or "world" in chat by flatbot
await bot.awaitMessage(/<flatbot> (.+)/) // resolves on first message matching the regex
}
See the bot.settings
property.
Injects a Plugin. Does nothing if the plugin is already loaded.
plugin
- function
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!
})
Injects plugins see bot.loadPlugin
.
plugins
- array of functions
Checks if the given plugin is loaded (or scheduled to be loaded) on this bot.
This function returns a Promise
, with void
as its argument upon completion.
Sleep in a bed. bedBlock
should be a Block
instance which is a bed.
Return true if bedBlock
is a bed
This function returns a Promise
, with void
as its argument upon completion.
Get out of bed.
This is the main method controlling the bot movements. It works similarly to pressing keys in minecraft. For example forward with state true will make the bot move forward. Forward with state false will make the bot stop moving forward. You may use bot.lookAt in conjunction with this to control movement. The jumper.js example shows how to use this.
control
- one of ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak']state
-true
orfalse
Returns true if a control state is toggled.
control
- one of ['forward', 'back', 'left', 'right', 'jump', 'sprint', 'sneak']
Sets all controls to off.
Returns how much damage will be done to the entity in a radius around the position of the explosion.
It will return null
if the entity has no armor and rawDamages is not set to true, since the function can't calculate the damage with armor if there is no armor.
entity
- Entity instanceposition
- Vec3 instanceradius
- the explosion radius as a numberrawDamages
- optional, if true it ignores armor in the calculation
This function returns a Promise
, with void
as its argument when you are looking at point
.
point
Vec3 instance - tilts your head so that it is directly facing this point.force
- Seeforce
inbot.look
This function returns a Promise
, with void
as its argument called when you are looking at yaw
and pitch
.
Set the direction your head is facing.
yaw
- The number of radians to rotate around the vertical axis, starting from due east. Counter clockwise.pitch
- Number of radians to point up or down. 0 means straight forward. pi / 2 means straight up. -pi / 2 means straight down.force
- If present and true, skips the smooth server-side transition. Specify this to true if you need the server to know exactly where you are looking, such as for dropping items or shooting arrows. This is not needed for client-side calculation such as walking direction.
Changes the text on the sign. On Minecraft 1.20 and newer, a truthy back
will try setting the text on the back of a sign (only visible if not attached to a wall).
This function returns a Promise
, with void
as its argument when you have successfully equipped the item or when you learn that you have failed to equip the item.
Equips an item from your inventory. If the argument item
is of Instance Item
equip will equip this specific item from its window slot. If the argument item
is of type number
equip will equip the first item found with that id searched by rising slot id (Hotbar is searched last. Armor, crafting, crafting result and off-hand slots are excluded).
item
-Item
instance ornumber
for item id. Seewindow.items()
.destination
"hand"
-null
aliases to this"head"
"torso"
"legs"
"feet"
"off-hand"
- when available
This function returns a Promise
, with void
as its argument upon completion.
Remove an article of equipment.
This function returns a Promise
, with void
as its argument when tossing is done.
item
- the stack of items you wish to toss truthy, you were not able to complete the toss.
This function returns a Promise
, with void
as its argument once tossing is complete.
itemType
- numerical id of the item you wish to tossmetadata
- metadata of the item you wish to toss. Usenull
to match any metadatacount
- how many you want to toss.null
is an alias for1
.
This function returns a Promise
, with void
as its argument once activating
elytra flight is complete. It will throw an Error if it fails.
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()
.
block
- the block to start digging intoforceLook
- (optional) if true, look at the block and start mining instantly. If false, the bot will slowly turn to the block to mine. Additionally, this can be assigned to 'ignore' to prevent the bot from moving its head at all. Also, this can be assigned to 'raycast' to raycast from the bots head to place where the bot is looking.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.
Tells you how long it will take to dig the block, in milliseconds.
Accepts resource pack.
Denies resource pack.
This function returns a Promise
, with void
as its argument when the server confirms that the block has indeed been placed.
referenceBlock
- the block you want to place a new block next tofaceVector
- one of the six cardinal directions, such asnew Vec3(0, 1, 0)
for the top face, indicating which face of thereferenceBlock
to place the block against.
The new block will be placed at referenceBlock.position.plus(faceVector)
.
This function returns a Promise
, with Entity
as its argument upon completion.
referenceBlock
- the block you want to place the entity next tofaceVector
- one of the six cardinal directions, such asnew Vec3(0, 1, 0)
for the top face, indicating which face of thereferenceBlock
to place the block against.
The new block will be placed at referenceBlock.position.plus(faceVector)
.
This function returns a Promise
, with void
as its argument upon completion.
Punch a note block, open a door, etc.
block
- the block to activatedirection
Optional defaults tonew Vec3(0, 1, 0)
(up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.cursorPos
Optional defaults tonew Vec3(0.5, 0.5, 0.5)
(block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.
This function returns a Promise
, with void
as its argument upon completion.
Activate an entity, useful for villager for example.
entity
- the entity to activate
This function returns a Promise
, with void
as its argument upon completion.
Activate an entity at the given position, useful for armor stands.
entity
- the entity to activateposition
- the world position to click at
This function returns a Promise
, with void
as its argument when consume ends.
Eat / drink currently held item
This function returns a Promise
, with void
as its argument when fishing ends.
Use fishing rod
Activates the currently held item. This is how you eat, shoot bows, throw an egg, activate firework rockets, etc.
Optional parameter is false
for main hand and true
for off hand.
Deactivates the currently held item. This is how you release an arrow, stop eating, etc.
Use the currently held item on an Entity
instance. This is how you apply a saddle and
use shears.
Attack a player or a mob.
entity
is a type of entity. To get a specific entity use bot.nearestEntity() or bot.entities.swing
Default totrue
. If false the bot does not swing its arm when attacking.
Play an arm swing animation.
hand
can takeleft
orright
which is the arm that is animated. Default:right
showHand
is a boolean whether to add the hand to the packet, Default:true
Mount a vehicle. To get back out, use bot.dismount
.
Dismounts from the vehicle you are in.
Moves the vehicle :
- left can take -1 or 1 : -1 means right, 1 means left
- forward can take -1 or 1 : -1 means backward, 1 means forward
All the direction are relative to where the bot is looking at
slot
- 0-8 the quick bar slot to select.
This function returns a Promise
, with void
as its argument when the crafting is complete and your inventory is updated.
recipe
- ARecipe
instance. Seebot.recipesFor
.count
- How many times you wish to perform the operation. If you want to craft planks into8
sticks, you would setcount
to2
.null
is an alias for1
.craftingTable
- ABlock
instance, the crafting table you wish to use. If the recipe does not require a crafting table, you may usenull
for this argument.
This function returns a Promise
, with void
as its argument when the writing was successfully or an error occurred.
slot
is in inventory window coordinates (where 36 is the first quickbar slot, etc.).pages
is an array of strings represents the pages.
Opens a block container or entity.
containerBlock
orcontainerEntity
The block instance to open or the entity to open.direction
Optional defaults tonew Vec3(0, 1, 0)
(up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.cursorPos
Optional defaults tonew Vec3(0.5, 0.5, 0.5)
(block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.
Returns a promise on a Container
instance which represents the container you are opening.
Deprecated. Same as openContainer
Returns a promise on a Furnace
instance which represents the furnace you are opening.
Deprecated. Same as openContainer
Returns a promise on an EnchantmentTable
instance which represents the enchantment table
you are opening.
Returns a promise on an anvil
instance which represents the anvil you are opening.
Returns a promise on a Villager
instance which represents the trading window you are opening.
You can listen to the ready
event on this Villager
to know when it's ready
This function returns a Promise
, with void
as its argument upon completion.
Uses the open villagerInstance
to trade.
Set a command block's properties at pos
.
Example options
argument:
{
mode: 2,
trackOutput: true,
conditional: false,
alwaysActive: true
}
options.mode can have 3 values: 0 (SEQUENCE), 1 (AUTO), 2 (REDSTONE) All options attributes are false by default, except mode which is 2 (as to replicate the default command block in Minecraft).
This can be used to check is a specific feature is available in the current Minecraft version. This is usually only required for handling version-specific functionality.
The list of available features can be found inside the ./lib/features.json file.
This is a promise-based function that waits for a given number of in-game ticks to pass before continuing. This is useful for quick timers that need to function with specific timing, regardless of the given physics tick speed of the bot. This is similar to the standard Javascript setTimeout function, but runs on the physics timer of the bot specifically.
When respawn
option is disabled, you can call this method manually to respawn.
These are lower level methods for the inventory, they can be useful sometimes but prefer the inventory methods presented above if you can.
This function returns a Promise
, with void
as its argument upon completion.
The only valid mode option at the moment is 0. Shift clicking or mouse dragging is not implemented.
Click on the current window. See details at https://wiki.vg/Protocol#Click_Container
Prefer using bot.simpleClick.*
This function returns a Promise
, with void
as its argument upon completion.
Put the item at slot
in the specified range.
This function returns a Promise
, with void
as its argument upon completion.
Put the item at slot
in the inventory.
Close the window
.
This function returns a Promise
, with void
as its argument upon completion.
Transfer some kind of item from one range to an other. options
is an object containing :
window
: Optional. the window where the item will be moveditemType
: the type of the moved itemsmetadata
: Optional. the metadata of the moved itemssourceStart
andsourceEnd
: the source range.sourceEnd
is optional and will default tosourceStart
+ 1destStart
anddestEnd
: the dest Range.destEnd
is optional and will default todestStart
+ 1count
: the amount of items to transfer. Default:1
nbt
: nbt data of the item to transfer. Default:nullish
(ignores nbt)
Open a block, for example a chest, returns a promise on the opening Window
.
block
is the block the bot will open.direction
Optional defaults tonew Vec3(0, 1, 0)
(up). A vector off the direction the container block should be interacted with. Does nothing when a container entity is targeted.cursorPos
Optional defaults tonew Vec3(0.5, 0.5, 0.5)
(block center). The curos position when opening the block instance. This is send with the activate block packet. Does nothing when a container entity is targeted.
Open an entity with an inventory, for example a villager, returns a promise on the opening Window
.
entity
is the entity the bot will open
This function returns a Promise
, with void
as its argument upon completion.
Move an item from sourceSlot
to destSlot
in the current window.
Update bot.heldItem
.
Gets the inventory equipment slot id for the given equipment destination name.
Available destinations are:
- head
- torso
- legs
- feet
- hand
- off-hand
This collection of apis is useful in creative mode. Detecting and changing gamemodes is not implemented here, but it is assumed and often required that the bot be in creative mode for these features to work.
This function returns a Promise
, with void
as its argument when gets fired when the server sets the slot.
Gives the bot the specified item in the specified inventory slot.
slot
is in inventory window coordinates (where 36 is the first quickbar slot, etc.).item
is a prismarine-item instance specified with arbitrary metadata, nbtdata, etc. Ifitem
isnull
, the item at the specified slot is deleted.
If this method changes anything, you can be notified via bot.inventory.on("updateSlot")
.
This function returns a Promise
, with void
as its argument when gets fired when the server clears the slot.
Makes the sets the item in the slot given to null.
slot
is in inventory window coordinates (where 36 is the first quickbar slot, etc.).
This function returns a Promise
, with void
as its argument when gets fired when the server clears the slot.
This function returns a Promise
, with void
as its argument when the bot arrives at the destination.
Calls startFlying()
and moves at a constant speed through 3d space in a straight line to the destination.
destination
is a Vec3
, and often the x
and z
coordinates will end with .5
.
This operation will not work if there is an obstacle in the way,
so it is advised to fly very short distances at a time.
This method does not attempt any path finding. It is expected that a path finding implementation will use this method to move < 2 blocks at a time.
To resume normal physics, call stopFlying()
.
Sets bot.physics.gravity
to 0
.
To resume normal physics, call stopFlying()
.
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()
.
Note that while flying, bot.entity.velocity
will not be accurate.
Restores bot.physics.gravity
to its original value.