CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mineflayer

High-level JavaScript API for creating Minecraft bots with comprehensive world interaction, entity management, and gameplay automation

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

game-mechanics.mddocs/

Game Mechanics

Advanced game mechanic integrations including sleep management, fishing, book writing, specialized interactions, and comprehensive gameplay automation for sophisticated bot behavior.

Capabilities

Sleep and Bed Management

Manage sleep cycles and bed interactions for health regeneration and time control.

/**
 * Sleep in a bed block
 * @param bedBlock - Bed block to sleep in
 * @returns Promise that resolves when sleep action completes
 */
sleep(bedBlock: Block): Promise<void>;

/**
 * Check if a block is a valid bed
 * @param bedBlock - Block to check
 * @returns True if block is a bed
 */
isABed(bedBlock: Block): boolean;

/**
 * Wake up from sleep
 * @returns Promise that resolves when wake action completes
 */
wake(): Promise<void>;

Usage Examples:

// Find and sleep in nearest bed
const bed = bot.findBlock({
  matching: (block) => bot.isABed(block),
  maxDistance: 16
});

if (bed) {
  try {
    await bot.sleep(bed);
    console.log("Bot is now sleeping");
    
    // Wake up after some time
    setTimeout(async () => {
      await bot.wake();
      console.log("Bot woke up");
    }, 10000);
  } catch (error) {
    console.log("Could not sleep:", error.message);
  }
}

// Auto-sleep at night
bot.on("time", () => {
  if (!bot.time.isDay && !bot.isSleeping) {
    const nearbyBed = bot.findBlock({
      matching: (block) => bot.isABed(block),
      maxDistance: 20
    });
    
    if (nearbyBed) {
      bot.sleep(nearbyBed).catch(console.error);
    }
  }
});

Fishing System

Automated fishing with timing and item collection.

/**
 * Start fishing with equipped fishing rod
 * @returns Promise that resolves when fishing completes (catch or timeout)
 */
fish(): Promise<void>;

/**
 * Check if bot is currently using held item (like fishing rod)
 */
readonly usingHeldItem: boolean;

Usage Examples:

// Basic fishing
const fishingRod = bot.inventory.findItem("fishing_rod");
if (fishingRod) {
  await bot.equip(fishingRod, "hand");
  
  // Look at water
  const water = bot.findBlock({
    matching: (block) => block.name === "water",
    maxDistance: 10
  });
  
  if (water) {
    await bot.lookAt(water.position);
    await bot.fish();
    console.log("Caught something!");
  }
}

// Automated fishing loop
async function autoFish(duration: number) {
  const fishingRod = bot.inventory.findItem("fishing_rod");
  if (!fishingRod) {
    console.log("No fishing rod found");
    return;
  }
  
  await bot.equip(fishingRod, "hand");
  
  const endTime = Date.now() + duration;
  let catches = 0;
  
  while (Date.now() < endTime) {
    try {
      await bot.fish();
      catches++;
      console.log(`Caught item #${catches}`);
      
      // Brief pause between catches
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      console.log("Fishing failed:", error.message);
      break;
    }
  }
  
  console.log(`Fishing session ended. Total catches: ${catches}`);
}

// Auto-fish for 10 minutes
autoFish(10 * 60 * 1000);

Book Writing and Editing

Write and edit books and written books with custom content.

/**
 * Write content to a book
 * @param slot - Inventory slot containing the book
 * @param pages - Array of page contents (strings)
 * @returns Promise that resolves when writing completes
 */
writeBook(slot: number, pages: string[]): Promise<void>;

Usage Examples:

// Write a simple book
const book = bot.inventory.findItem("writable_book");
if (book) {
  const pages = [
    "Chapter 1: The Beginning\n\nOnce upon a time, in a world made of blocks...",
    "Chapter 2: The Adventure\n\nOur hero ventured forth into the dangerous caves...",
    "Chapter 3: The End\n\nAnd they lived happily ever after.\n\nThe End."
  ];
  
  await bot.writeBook(book.slot, pages);
  console.log("Book written successfully!");
}

// Create a diary entry
async function writeDiary() {
  const book = bot.inventory.findItem("writable_book");
  if (!book) return;
  
  const date = new Date().toLocaleDateString();
  const time = bot.time.timeOfDay;
  const weather = bot.isRaining ? "raining" : "clear";
  const pos = bot.entity.position;
  
  const diaryEntry = [
    `Diary Entry - ${date}\n\nTime: ${time}\nWeather: ${weather}\nLocation: ${pos.x.toFixed(1)}, ${pos.y.toFixed(1)}, ${pos.z.toFixed(1)}`,
    `Today I explored the world and learned many things about survival in Minecraft...`,
    `Health: ${bot.health}/20\nFood: ${bot.food}/20\n\nUntil tomorrow,\n- Bot`
  ];
  
  await bot.writeBook(book.slot, diaryEntry);
}

// Auto-documentation system
async function documentDiscoveries() {
  const discoveries: string[] = [];
  
  // Track new blocks discovered
  bot.on("blockUpdate", (oldBlock, newBlock) => {
    if (newBlock && !oldBlock) {
      discoveries.push(`Found ${newBlock.name} at ${newBlock.position}`);
    }
  });
  
  // Track new entities
  bot.on("entitySpawn", (entity) => {
    discoveries.push(`Encountered ${entity.type} at ${entity.position}`);
  });
  
  // Write discoveries to book every hour
  setInterval(async () => {
    if (discoveries.length > 0) {
      const book = bot.inventory.findItem("writable_book");
      if (book) {
        const pages = [];
        let currentPage = "Discoveries:\n\n";
        
        for (const discovery of discoveries) {
          if (currentPage.length + discovery.length > 256) {
            pages.push(currentPage);
            currentPage = discovery + "\n";
          } else {
            currentPage += discovery + "\n";
          }
        }
        
        if (currentPage.length > 0) {
          pages.push(currentPage);
        }
        
        await bot.writeBook(book.slot, pages);
        discoveries.length = 0; // Clear discoveries
      }
    }
  }, 3600000); // Every hour
}

Command Block Management

Set and configure command blocks for automated server operations.

/**
 * Set a command block with specific command and options
 * @param pos - Position of the command block
 * @param command - Command to set
 * @param options - Command block configuration
 */
setCommandBlock(pos: Vec3, command: string, options: CommandBlockOptions): void;

interface CommandBlockOptions {
  /** Command block mode (0=impulse, 1=chain, 2=repeat) */
  mode: number;
  /** Track command output */
  trackOutput: boolean;
  /** Conditional execution */
  conditional: boolean;
  /** Always active */
  alwaysActive: boolean;
}

Usage Examples:

// Set up automated farm with command blocks
const commandBlockPos = new Vec3(100, 64, 200);

// Set a repeating command block
bot.setCommandBlock(commandBlockPos, "/say Automated message", {
  mode: 2,           // Repeat mode
  trackOutput: true,
  conditional: false,
  alwaysActive: true
});

// Chain of command blocks for complex automation
const commands = [
  "/fill ~1 ~-1 ~1 ~10 ~-1 ~10 minecraft:farmland",
  "/fill ~1 ~ ~1 ~10 ~ ~10 minecraft:water",
  "/give @p minecraft:wheat_seeds 64"
];

for (let i = 0; i < commands.length; i++) {
  const pos = commandBlockPos.offset(i, 0, 0);
  bot.setCommandBlock(pos, commands[i], {
    mode: i === 0 ? 0 : 1, // First impulse, rest chain
    trackOutput: true,
    conditional: false,
    alwaysActive: false
  });
}

Trading and Villager Management

Advanced villager trading with reputation management and trade optimization.

/**
 * Execute a trade with a villager
 * @param villagerInstance - Open villager trading window
 * @param tradeIndex - Index of the trade to execute
 * @param times - Number of times to execute the trade
 * @returns Promise that resolves when trading completes
 */
trade(villagerInstance: Villager, tradeIndex: string | number, times?: number): Promise<void>;

Usage Examples:

// Optimize trading with multiple villagers
async function optimizeTrading() {
  const villagers = Object.values(bot.entities).filter(entity => 
    entity.name === "villager"
  );
  
  for (const villager of villagers) {
    try {
      const villagerWindow = await bot.openVillager(villager);
      await new Promise<void>(resolve => villagerWindow.on("ready", resolve));
      
      // Find best emerald trades
      const emeraldTrades = villagerWindow.trades.filter(trade => 
        trade.outputItem.name === "emerald" && !trade.tradeDisabled
      );
      
      for (const trade of emeraldTrades) {
        const inputCount = bot.inventory.count(trade.inputItem1.type);
        const maxTrades = Math.min(
          Math.floor(inputCount / trade.inputItem1.count),
          trade.maximumNbTradeUses - trade.nbTradeUses
        );
        
        if (maxTrades > 0) {
          await bot.trade(villagerWindow, villagerWindow.trades.indexOf(trade), maxTrades);
          console.log(`Traded ${maxTrades} times with villager`);
        }
      }
      
      villagerWindow.close();
    } catch (error) {
      console.log("Trading failed:", error.message);
    }
  }
}

// Create emerald farm
async function createEmeraldFarm() {
  // Find farmer villager
  const farmer = Object.values(bot.entities).find(entity =>
    entity.name === "villager" && entity.metadata[13] === 0
  );
  
  if (!farmer) return;
  
  // Plant crops nearby
  const farmArea = bot.findBlocks({
    matching: (block) => block.name === "farmland",
    maxDistance: 20,
    count: 100
  });
  
  const seeds = bot.inventory.items().filter(item => 
    item.name.includes("seeds") || item.name === "carrot" || item.name === "potato"
  );
  
  for (const seedType of seeds) {
    for (const farmPos of farmArea) {
      const airBlock = bot.blockAt(farmPos.offset(0, 1, 0));
      if (airBlock && airBlock.type === 0) {
        await bot.equip(seedType, "hand");
        await bot.placeBlock(bot.blockAt(farmPos)!, new Vec3(0, 1, 0));
        break;
      }
    }
  }
  
  console.log("Farm planted for emerald trading");
}

Advanced Game State Management

Monitor and react to various game state changes and environmental conditions.

interface Bot {
  /** Whether bot is currently sleeping */
  isSleeping: boolean;
  /** Current weather state */
  isRaining: boolean;
  /** Thunder state */
  thunderState: number;
  /** Game time information */
  time: Time;
  /** Current experience */
  experience: Experience;
}

interface Time {
  /** Whether daylight cycle is enabled */
  doDaylightCycle: boolean;
  /** Full time value as BigInt */
  bigTime: BigInt;
  /** Time in ticks */
  time: number;
  /** Time of day (0-24000) */
  timeOfDay: number;
  /** Current day number */
  day: number;
  /** Whether it's daytime */
  isDay: boolean;
  /** Moon phase (0-7) */
  moonPhase: number;
  /** World age as BigInt */
  bigAge: BigInt;
  /** World age in ticks */
  age: number;
}

interface Experience {
  /** Experience level */
  level: number;
  /** Total experience points */
  points: number;
  /** Progress to next level (0-1) */
  progress: number;
}

Game Events and Reactions

React to various game events and environmental changes.

interface BotEvents {
  /** Sleep state changed */
  sleep(): void;
  wake(): void;
  
  /** Weather events */
  rain(): void;
  
  /** Time events */
  time(): void;
  
  /** Experience gained */
  experience(): void;
  
  /** Death and respawn */
  death(): void;
  respawn(): void;
  
  /** Health and status */
  health(): void;
  breath(): void;
  
  /** Firework usage */
  usedFirework(): void;
  
  /** Spawn point changes */
  spawnReset(): void;
}

Usage Examples:

// React to weather changes
bot.on("rain", () => {
  if (bot.isRaining) {
    console.log("It started raining, seeking shelter");
    const shelter = bot.findBlock({
      matching: (block) => block.name.includes("roof") || block.name.includes("house"),
      maxDistance: 50
    });
    
    if (shelter) {
      // Move to shelter logic here
    }
  } else {
    console.log("Rain stopped, can go outside");
  }
});

// Time-based behavior
bot.on("time", () => {
  const timeOfDay = bot.time.timeOfDay;
  
  if (timeOfDay === 0) {
    console.log("New day started!");
  } else if (timeOfDay === 12000) {
    console.log("Nighttime, being cautious");
    // Enable defensive behavior
  } else if (timeOfDay === 23000) {
    console.log("Almost dawn, preparing for day");
  }
});

// Experience tracking
bot.on("experience", () => {
  console.log(`Level: ${bot.experience.level}, XP: ${bot.experience.points}`);
  
  if (bot.experience.level % 5 === 0) {
    bot.chat(`Reached level ${bot.experience.level}!`);
  }
});

// Health monitoring
bot.on("health", () => {
  if (bot.health < 6) {
    console.log("Low health! Seeking food and safety");
    
    // Find food
    const food = bot.inventory.items().find(item => 
      ["bread", "apple", "cooked_beef", "golden_apple"].includes(item.name)
    );
    
    if (food) {
      bot.equip(food, "hand").then(() => bot.consume()).catch(console.error);
    }
  }
});

// Auto-respawn system
bot.on("death", () => {
  console.log("Bot died, respawning soon...");
});

bot.on("respawn", () => {
  console.log("Bot respawned");
  
  // Return to last known safe location
  const safeLocation = new Vec3(0, 64, 0); // Spawn area
  // Navigation logic here
});

// Comprehensive game state monitor
function monitorGameState() {
  setInterval(() => {
    const status = {
      health: bot.health,
      food: bot.food,
      level: bot.experience.level,
      time: bot.time.timeOfDay,
      weather: bot.isRaining ? "rain" : "clear",
      position: bot.entity.position,
      dimension: bot.game.dimension
    };
    
    console.log("Bot Status:", JSON.stringify(status, null, 2));
  }, 60000); // Every minute
}

monitorGameState();

docs

bot-management.md

communication.md

container-management.md

entity-management.md

game-mechanics.md

index.md

inventory-items.md

movement-physics.md

world-interaction.md

tile.json