High-level JavaScript API for creating Minecraft bots with comprehensive world interaction, entity management, and gameplay automation
npx @tessl/cli install tessl/npm-mineflayer@4.32.0Mineflayer is a comprehensive JavaScript/TypeScript library for creating Minecraft bots with a stable, high-level API. It provides extensive functionality for world interaction, entity management, inventory control, communication, and gameplay automation across Minecraft versions 1.8.8 through 1.21.6.
npm install mineflayerimport {
createBot,
Bot,
BotOptions,
Location,
Painting,
ScoreBoard,
BossBar,
Particle,
testedVersions,
latestSupportedVersion,
oldestSupportedVersion,
supportFeature
} from "mineflayer";For CommonJS:
const {
createBot,
Location,
Painting,
ScoreBoard,
BossBar,
Particle,
testedVersions,
latestSupportedVersion,
oldestSupportedVersion,
supportFeature
} = require("mineflayer");import { createBot } from "mineflayer";
// Create a bot instance
const bot = createBot({
host: "localhost", // Server hostname
port: 25565, // Server port (default: 25565)
username: "MyBot", // Bot username
version: "1.20.1" // Minecraft version
});
// Basic event handling
bot.once("spawn", () => {
console.log("Bot spawned in the game!");
// Send a chat message
bot.chat("Hello, Minecraft world!");
// Move forward
bot.setControlState("forward", true);
// Look around
bot.look(0, 0); // yaw, pitch
});
// Handle chat messages
bot.on("chat", (username, message) => {
if (username === bot.username) return; // Ignore own messages
console.log(`${username}: ${message}`);
// Simple command response
if (message === "follow me") {
const player = bot.players[username];
if (player?.entity) {
bot.lookAt(player.entity.position);
}
}
});
// Handle errors
bot.on("error", (err) => {
console.error("Bot error:", err);
});Mineflayer is built around several key architectural components:
Core functionality for creating bot instances and managing server connections with comprehensive configuration options.
function createBot(options: BotOptions): Bot;
interface BotOptions {
host?: string;
port?: number;
username?: string;
password?: string;
version?: string | boolean;
auth?: "microsoft" | "mojang" | "offline";
client?: Client;
logErrors?: boolean;
hideErrors?: boolean;
plugins?: PluginOptions;
physicsEnabled?: boolean;
viewDistance?: ViewDistance;
difficulty?: number;
respawn?: boolean;
}Comprehensive world interaction capabilities including block querying, manipulation, and spatial analysis for environmental awareness and interaction.
blockAt(point: Vec3, extraInfos?: boolean): Block | null;
findBlock(options: FindBlockOptions): Block | null;
canDigBlock(block: Block): boolean;
dig(block: Block, forceLook?: boolean | "ignore"): Promise<void>;
placeBlock(referenceBlock: Block, faceVector: Vec3): Promise<void>;
activateBlock(block: Block, direction?: Vec3): Promise<void>;Entity tracking, interaction, and management system for comprehensive awareness of players, mobs, items, and other game entities.
nearestEntity(filter?: (entity: Entity) => boolean): Entity | null;
attack(entity: Entity): void;
activateEntity(entity: Entity): Promise<void>;
mount(entity: Entity): void;
dismount(): void;Advanced movement control with physics simulation, pathfinding integration, and precise positioning for sophisticated bot navigation.
setControlState(control: ControlState, state: boolean): void;
getControlState(control: ControlState): boolean;
lookAt(point: Vec3, force?: boolean): Promise<void>;
look(yaw: number, pitch: number, force?: boolean): Promise<void>;
type ControlState = "forward" | "back" | "left" | "right" | "jump" | "sprint" | "sneak";Complete inventory management system with equipment handling, item manipulation, and container interaction for sophisticated resource management.
equip(item: Item | number, destination: EquipmentDestination): Promise<void>;
toss(itemType: number, metadata: number | null, count: number | null): Promise<void>;
craft(recipe: Recipe, count?: number, craftingTable?: Block): Promise<void>;
setQuickBarSlot(slot: number): void;
type EquipmentDestination = "hand" | "head" | "torso" | "legs" | "feet" | "off-hand";Specialized interfaces for interacting with chests, furnaces, enchantment tables, and other container blocks with type-safe operations.
openChest(chest: Block | Entity): Promise<Chest>;
openFurnace(furnace: Block): Promise<Furnace>;
openEnchantmentTable(enchantmentTable: Block): Promise<EnchantmentTable>;
openVillager(villager: Entity): Promise<Villager>;Chat handling with pattern matching, command processing, and messaging capabilities for interactive bot behavior and user communication.
chat(message: string): void;
whisper(username: string, message: string): void;
addChatPattern(name: string, pattern: RegExp, options?: ChatPatternOptions): number;
awaitMessage(...patterns: (string | RegExp)[]): Promise<string>;Advanced game mechanic integrations including sleep management, fishing, book writing, and specialized interactions for complete gameplay automation.
sleep(bedBlock: Block): Promise<void>;
fish(): Promise<void>;
writeBook(slot: number, pages: string[]): Promise<void>;
trade(villager: Villager, tradeIndex: string | number, times?: number): Promise<void>;Specialized methods available when the bot is in creative mode, providing enhanced capabilities for inventory management and flight control.
interface CreativeMethods {
/**
* Set an inventory slot to contain a specific item
* @param slot - Inventory slot number
* @param item - Item to place in slot, or null to clear
*/
setInventorySlot(slot: number, item: Item | null): Promise<void>;
/**
* Clear a specific inventory slot
* @param slot - Slot number to clear
*/
clearSlot(slot: number): Promise<void>;
/**
* Clear all items from the inventory
*/
clearInventory(): Promise<void>;
/**
* Fly directly to a destination position
* @param destination - Target position coordinates
*/
flyTo(destination: Vec3): Promise<void>;
/**
* Start flying mode
*/
startFlying(): void;
/**
* Stop flying mode
*/
stopFlying(): void;
}Comprehensive event system with 95+ events for monitoring all aspects of game state, entity behavior, world changes, and bot interactions.
interface BotEvents {
// Connection and lifecycle events
inject_allowed: () => void;
login: () => void;
spawn: () => void;
respawn: () => void;
game: () => void;
end: (reason: string) => void;
kicked: (reason: string, loggedIn: boolean) => void;
error: (err: Error) => void;
// Chat and messaging events
chat: (username: string, message: string, translate: string | null, jsonMsg: ChatMessage, matches: string[] | null) => void;
whisper: (username: string, message: string, translate: string | null, jsonMsg: ChatMessage, matches: string[] | null) => void;
actionBar: (jsonMsg: ChatMessage) => void;
message: (jsonMsg: ChatMessage, position: string) => void;
messagestr: (message: string, position: string, jsonMsg: ChatMessage) => void;
unmatchedMessage: (stringMsg: string, jsonMsg: ChatMessage) => void;
// Player and entity events
playerJoined: (player: Player) => void;
playerUpdated: (player: Player) => void;
playerLeft: (player: Player) => void;
entitySpawn: (entity: Entity) => void;
entityGone: (entity: Entity) => void;
entityMoved: (entity: Entity) => void;
entityUpdate: (entity: Entity) => void;
entityAttributes: (entity: Entity) => void;
// Entity action events
entitySwingArm: (entity: Entity) => void;
entityHurt: (entity: Entity, source: Entity) => void;
entityDead: (entity: Entity) => void;
entityTaming: (entity: Entity) => void;
entityTamed: (entity: Entity) => void;
entityShakingOffWater: (entity: Entity) => void;
entityEatingGrass: (entity: Entity) => void;
entityHandSwap: (entity: Entity) => void;
entityWake: (entity: Entity) => void;
entityEat: (entity: Entity) => void;
entityCriticalEffect: (entity: Entity) => void;
entityMagicCriticalEffect: (entity: Entity) => void;
entityCrouch: (entity: Entity) => void;
entityUncrouch: (entity: Entity) => void;
entityEquip: (entity: Entity) => void;
entitySleep: (entity: Entity) => void;
entityElytraFlew: (entity: Entity) => void;
entityDetach: (entity: Entity, vehicle: Entity) => void;
entityAttach: (entity: Entity, vehicle: Entity) => void;
entityEffect: (entity: Entity, effect: Effect) => void;
entityEffectEnd: (entity: Entity, effect: Effect) => void;
// World and environment events
blockUpdate: (oldBlock: Block | null, newBlock: Block) => void;
'blockUpdate:(x, y, z)': (oldBlock: Block | null, newBlock: Block | null) => void;
chunkColumnLoad: (chunk: Vec3) => void;
chunkColumnUnload: (chunk: Vec3) => void;
rain: () => void;
time: () => void;
// Bot state events
health: () => void;
breath: () => void;
death: () => void;
spawnReset: () => void;
move: (position: Vec3) => void;
forcedMove: () => void;
mount: () => void;
dismount: (vehicle: Entity) => void;
sleep: () => void;
wake: () => void;
experience: () => void;
physicsTick: () => void;
physicTick: () => void;
// Interaction events
diggingCompleted: (block: Block) => void;
diggingAborted: (block: Block) => void;
windowOpen: (window: Window) => void;
windowClose: (window: Window) => void;
itemDrop: (entity: Entity) => void;
playerCollect: (collector: Entity, collected: Entity) => void;
usedFirework: () => void;
// Audio and visual events
soundEffectHeard: (soundName: string, position: Vec3, volume: number, pitch: number) => void;
hardcodedSoundEffectHeard: (soundId: number, soundCategory: number, position: Vec3, volume: number, pitch: number) => void;
noteHeard: (block: Block, instrument: Instrument, pitch: number) => void;
title: (text: string, type: "subtitle" | "title") => void;
particle: (particle: Particle) => void;
// Block interaction events
pistonMove: (block: Block, isPulling: number, direction: number) => void;
chestLidMove: (block: Block, isOpen: number, block2: Block | null) => void;
blockBreakProgressObserved: (block: Block, destroyStage: number) => void;
blockBreakProgressEnd: (block: Block) => void;
// Scoreboard and team events
scoreboardCreated: (scoreboard: ScoreBoard) => void;
scoreboardDeleted: (scoreboard: ScoreBoard) => void;
scoreboardTitleChanged: (scoreboard: ScoreBoard) => void;
scoreUpdated: (scoreboard: ScoreBoard, item: number) => void;
scoreRemoved: (scoreboard: ScoreBoard, item: number) => void;
scoreboardPosition: (position: DisplaySlot, scoreboard: ScoreBoard) => void;
teamCreated: (team: Team) => void;
teamRemoved: (team: Team) => void;
teamUpdated: (team: Team) => void;
teamMemberAdded: (team: Team) => void;
teamMemberRemoved: (team: Team) => void;
// UI events
bossBarCreated: (bossBar: BossBar) => void;
bossBarDeleted: (bossBar: BossBar) => void;
bossBarUpdated: (bossBar: BossBar) => void;
resourcePack: (url: string, hash?: string, uuid?: string) => void;
}Version checking and feature support utilities for cross-version compatibility.
const testedVersions: string[];
const latestSupportedVersion: string;
const oldestSupportedVersion: string;
function supportFeature(feature: string, version: string): boolean;Core utility classes for spatial positioning, world object representation, and game state management.
class Location {
floored: Vec3;
blockPoint: Vec3;
chunkCorner: Vec3;
blockIndex: number;
biomeBlockIndex: number;
chunkYIndex: number;
constructor(absoluteVector: Vec3);
}
class Painting {
id: number;
position: Vec3;
name: string;
direction: Vec3;
constructor(id: number, position: Vec3, name: string, direction: Vec3);
}
class ScoreBoard {
name: string;
title: string;
itemsMap: { [name: string]: ScoreBoardItem };
items: ScoreBoardItem[];
constructor(packet: object);
setTitle(title: string): void;
add(name: string, value: number): ScoreBoardItem;
remove(name: string): ScoreBoardItem;
}
class BossBar {
entityUUID: string;
title: ChatMessage;
health: number;
dividers: number;
color: "pink" | "blue" | "red" | "green" | "yellow" | "purple" | "white";
shouldDarkenSky: boolean;
isDragonBar: boolean;
createFog: boolean;
constructor(uuid: string, title: string, health: number, dividers: number, color: number, flags: number);
}
class Particle {
id: number;
position: Vec3;
offset: Vec3;
count: number;
movementSpeed: number;
longDistanceRender: boolean;
static fromNetwork(packet: Object): Particle;
constructor(id: number, position: Vec3, offset: Vec3, count?: number, movementSpeed?: number, longDistanceRender?: boolean);
}interface Bot extends TypedEmitter<BotEvents> {
// Core identification and connection
username: string;
protocolVersion: string;
majorVersion: string;
version: string;
// Entity and player management
entity: Entity;
entities: { [id: string]: Entity };
player: Player;
players: { [username: string]: Player };
// Health and status
health: number;
food: number;
foodSaturation: number;
oxygenLevel: number;
fireworkRocketDuration: number;
// World and environment
world: world.WorldSync;
spawnPoint: Vec3;
game: GameState;
time: Time;
isRaining: boolean;
thunderState: number;
// Inventory and equipment
inventory: Window<StorageEvents>;
heldItem: Item | null;
usingHeldItem: boolean;
quickBarSlot: number;
currentWindow: Window | null;
// Movement and physics
physics: PhysicsOptions;
physicsEnabled: boolean;
isSleeping: boolean;
targetDigBlock: Block;
controlState: ControlStateStatus;
// Game state and settings
settings: GameSettings;
experience: Experience;
// Communication and UI
chatPatterns: ChatPattern[];
tablist: Tablist;
// Scoreboards and teams
scoreboards: { [name: string]: ScoreBoard };
scoreboard: { [slot in DisplaySlot]: ScoreBoard };
teams: { [name: string]: Team };
teamMap: { [name: string]: Team };
// Special modes
creative: CreativeMethods;
// Advanced features
registry: Registry;
simpleClick: SimpleClick;
_client: Client;
// Core methods
connect(options: BotOptions): void;
end(reason?: string): void;
quit(reason?: string): void;
supportFeature: IndexedData['supportFeature'];
// Block and world interaction
blockAt(point: Vec3, extraInfos?: boolean): Block | null;
blockInSight(maxSteps: number, vectorLength: number): Block | null;
blockAtCursor(maxDistance?: number, matcher?: Function): Block | null;
blockAtEntityCursor(entity?: Entity, maxDistance?: number, matcher?: Function): Block | null;
canSeeBlock(block: Block): boolean;
findBlock(options: FindBlockOptions): Block | null;
findBlocks(options: FindBlockOptions): Vec3[];
canDigBlock(block: Block): boolean;
dig(block: Block, forceLook?: boolean | 'ignore', digFace?: 'auto' | Vec3 | 'raycast'): Promise<void>;
stopDigging(): void;
digTime(block: Block): number;
placeBlock(referenceBlock: Block, faceVector: Vec3): Promise<void>;
placeEntity(referenceBlock: Block, faceVector: Vec3): Promise<Entity>;
activateBlock(block: Block, direction?: Vec3, cursorPos?: Vec3): Promise<void>;
// Entity interaction
nearestEntity(filter?: (entity: Entity) => boolean): Entity | null;
entityAtCursor(maxDistance?: number): Entity | null;
activateEntity(entity: Entity): Promise<void>;
activateEntityAt(entity: Entity, position: Vec3): Promise<void>;
attack(entity: Entity): void;
useOn(targetEntity: Entity): void;
mount(entity: Entity): void;
dismount(): void;
moveVehicle(left: number, forward: number): void;
// Movement and control
setControlState(control: ControlState, state: boolean): void;
getControlState(control: ControlState): boolean;
clearControlStates(): void;
lookAt(point: Vec3, force?: boolean): Promise<void>;
look(yaw: number, pitch: number, force?: boolean): Promise<void>;
swingArm(hand: 'left' | 'right' | undefined, showHand?: boolean): void;
// Item and inventory management
equip(item: Item | number, destination: EquipmentDestination | null): Promise<void>;
unequip(destination: EquipmentDestination | null): Promise<void>;
tossStack(item: Item): Promise<void>;
toss(itemType: number, metadata: number | null, count: number | null): Promise<void>;
craft(recipe: Recipe, count?: number, craftingTable?: Block): Promise<void>;
setQuickBarSlot(slot: number): void;
consume(): Promise<void>;
activateItem(offhand?: boolean): void;
deactivateItem(): void;
updateHeldItem(): void;
getEquipmentDestSlot(destination: string): number;
// Container management
openContainer(container: Block | Entity, direction?: Vec3, cursorPos?: Vec3): Promise<Chest | Dispenser>;
openChest(chest: Block | Entity, direction?: Vec3, cursorPos?: Vec3): Promise<Chest>;
openFurnace(furnace: Block): Promise<Furnace>;
openDispenser(dispenser: Block): Promise<Dispenser>;
openEnchantmentTable(enchantmentTable: Block): Promise<EnchantmentTable>;
openAnvil(anvil: Block): Promise<Anvil>;
openVillager(villager: Entity): Promise<Villager>;
trade(villagerInstance: Villager, tradeIndex: string | number, times?: number): Promise<void>;
openBlock(block: Block, direction?: Vec3, cursorPos?: Vec3): Promise<Window>;
openEntity(entity: Entity, Class: new () => EventEmitter): Promise<Window>;
closeWindow(window: Window): void;
// Window and inventory operations
clickWindow(slot: number, mouseButton: number, mode: number): Promise<void>;
putSelectedItemRange(start: number, end: number, window: Window, slot: any): Promise<void>;
putAway(slot: number): Promise<void>;
transfer(options: TransferOptions): Promise<void>;
moveSlotItem(sourceSlot: number, destSlot: number): Promise<void>;
// Communication
chat(message: string): void;
whisper(username: string, message: string): void;
tabComplete(str: string, assumeCommand?: boolean, sendBlockInSight?: boolean, timeout?: number): Promise<string[]>;
chatAddPattern(pattern: RegExp, chatType: string, description?: string): number;
addChatPattern(name: string, pattern: RegExp, options?: ChatPatternOptions): number;
addChatPatternSet(name: string, patterns: RegExp[], options?: ChatPatternOptions): number;
removeChatPattern(name: string | number): void;
awaitMessage(...args: string[] | RegExp[]): Promise<string>;
// Game mechanics
sleep(bedBlock: Block): Promise<void>;
isABed(bedBlock: Block): boolean;
wake(): Promise<void>;
fish(): Promise<void>;
elytraFly(): Promise<void>;
writeBook(slot: number, pages: string[]): Promise<void>;
updateSign(block: Block, text: string, back?: boolean): void;
setCommandBlock(pos: Vec3, command: string, options: CommandBlockOptions): void;
// Utility and helpers
getExplosionDamages(targetEntity: Entity, position: Vec3, radius: number, rawDamages?: boolean): number | null;
waitForChunksToLoad(): Promise<void>;
waitForTicks(ticks: number): Promise<void>;
recipesFor(itemType: number, metadata: number | null, minResultCount: number | null, craftingTable: Block | boolean | null): Recipe[];
recipesAll(itemType: number, metadata: number | null, craftingTable: Block | boolean | null): Recipe[];
// Settings and configuration
setSettings(options: Partial<GameSettings>): void;
loadPlugin(plugin: Plugin): void;
loadPlugins(plugins: Plugin[]): void;
hasPlugin(plugin: Plugin): boolean;
// Resource packs
acceptResourcePack(): void;
denyResourcePack(): void;
// Respawn
respawn(): void;
}
interface Vec3 {
x: number;
y: number;
z: number;
}
interface Block {
type: number;
name: string;
position: Vec3;
metadata: number;
light: number;
skyLight: number;
hardness: number;
material: string;
}
interface Entity {
id: number;
type: string;
username?: string;
position: Vec3;
velocity: Vec3;
yaw: number;
pitch: number;
health?: number;
isValid: boolean;
}
interface Item {
type: number;
count: number;
metadata: number;
name: string;
displayName: string;
stackSize: number;
durabilityUsed?: number;
enchants: Enchant[];
nbt?: NBT;
}
interface ScoreBoardItem {
name: string;
displayName: ChatMessage;
value: number;
}
interface ChatMessage {
text?: string;
color?: string;
bold?: boolean;
italic?: boolean;
underlined?: boolean;
strikethrough?: boolean;
obfuscated?: boolean;
extra?: ChatMessage[];
}
interface Enchant {
name: string;
lvl: number;
}
interface Player {
uuid: string;
username: string;
displayName: ChatMessage;
gamemode: number;
ping: number;
entity: Entity;
skinData: SkinData | undefined;
profileKeys?: {
publicKey: Buffer;
signature: Buffer;
};
}
interface SkinData {
url: string;
model: string | null;
}
interface GameState {
levelType: LevelType;
gameMode: GameMode;
hardcore: boolean;
dimension: Dimension;
difficulty: Difficulty;
maxPlayers: number;
serverBrand: string;
}
type LevelType = 'default' | 'flat' | 'largeBiomes' | 'amplified' | 'customized' | 'buffet' | 'default_1_1';
type GameMode = 'survival' | 'creative' | 'adventure' | 'spectator';
type Dimension = 'the_nether' | 'overworld' | 'the_end';
type Difficulty = 'peaceful' | 'easy' | 'normal' | 'hard';
interface Time {
doDaylightCycle: boolean;
bigTime: BigInt;
time: number;
timeOfDay: number;
day: number;
isDay: boolean;
moonPhase: number;
bigAge: BigInt;
age: number;
}
interface PhysicsOptions {
maxGroundSpeed: number;
terminalVelocity: number;
walkingAcceleration: number;
gravity: number;
groundFriction: number;
playerApothem: number;
playerHeight: number;
jumpSpeed: number;
yawSpeed: number;
pitchSpeed: number;
sprintSpeed: number;
maxGroundSpeedSoulSand: number;
maxGroundSpeedWater: number;
}
interface ControlStateStatus {
forward: boolean;
back: boolean;
left: boolean;
right: boolean;
jump: boolean;
sprint: boolean;
sneak: boolean;
}
type ControlState = 'forward' | 'back' | 'left' | 'right' | 'jump' | 'sprint' | 'sneak';
interface GameSettings {
chat: ChatLevel;
colorsEnabled: boolean;
viewDistance: ViewDistance;
difficulty: number;
skinParts: SkinParts;
mainHand: MainHands;
}
interface SkinParts {
showCape: boolean;
showJacket: boolean;
showLeftSleeve: boolean;
showRightSleeve: boolean;
showLeftPants: boolean;
showRightPants: boolean;
showHat: boolean;
}
interface Experience {
level: number;
points: number;
progress: number;
}
interface ChatPattern {
pattern: RegExp;
type: string;
description: string;
}
interface Tablist {
header: ChatMessage;
footer: ChatMessage;
}
interface SimpleClick {
leftMouse: (slot: number) => Promise<void>;
rightMouse: (slot: number) => Promise<void>;
}
interface FindBlockOptions {
point?: Vec3;
matching: number | number[] | ((block: Block) => boolean);
maxDistance?: number;
count?: number;
useExtraInfo?: boolean | ((block: Block) => boolean);
}
interface TransferOptions {
window: Window;
itemType: number;
metadata: number | null;
count?: number;
sourceStart: number;
sourceEnd: number;
destStart: number;
destEnd: number;
}
interface CommandBlockOptions {
mode: number;
trackOutput: boolean;
conditional: boolean;
alwaysActive: boolean;
}
interface ChatPatternOptions {
repeat: boolean;
parse: boolean;
}
interface Effect {
id: number;
amplifier: number;
duration: number;
}
interface Instrument {
id: number;
name: 'harp' | 'doubleBass' | 'snareDrum' | 'sticks' | 'bassDrum';
}
type DisplaySlot = 'list' | 'sidebar' | 'belowName' | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18;
type ChatLevel = 'enabled' | 'commandsOnly' | 'disabled';
type ViewDistance = 'far' | 'normal' | 'short' | 'tiny' | number;
type MainHands = 'left' | 'right';