Skip to content

Latest commit

 

History

History
655 lines (488 loc) · 13.5 KB

BOT_API.md

File metadata and controls

655 lines (488 loc) · 13.5 KB

MindPy Bot API Documentation

MindPy provides a comprehensive, Pythonic, async-first API for controlling Minecraft bots. The API is designed to be clean, intuitive, and powerful, with three levels of abstraction:

  1. Low-Level Protocol - Direct protocol access for framework developers
  2. Bot Tools - Core bot operations for normal bot development
  3. Intelligent Behaviors - High-level automation for advanced AI agents

Quick Start

import asyncio
from mindpy import Bot

async def main():
    bot = await Bot.connect(
        host="localhost",
        port=25565,
        username="MindPy"
    )

    await bot.chat("Hello Minecraft!")
    await bot.goto(100, 64, -20)
    await bot.mine("diamond_ore", amount=5)
    await bot.craft("diamond_pickaxe")
    await bot.disconnect()

asyncio.run(main())

Bot Connection

Creating a Bot

from mindpy import Bot

# Offline mode (default)
bot = Bot(
    host="localhost",
    port=25565,
    username="MyBot"
)

# Online mode with Microsoft auth
from mindpy.protocol.auth import MicrosoftAuth

async with MicrosoftAuth() as auth:
    profile = await auth.device_flow_auth()

bot = Bot(
    host="mc.example.com",
    username="MyBot",
    auth_profile=profile
)

Connection Lifecycle

# Connect manually
await bot.connect()

# Use context manager (recommended)
async with bot:
    await bot.run()

# Disconnect
await bot.disconnect()

# Reconnect with automatic retry
await bot.reconnect()

Chat API

Sending Messages

# Send chat message
await bot.chat("Hello everyone!")

# Send private message
await bot.whisper("Player", "Secret message")

# Execute server command
await bot.command("time set day")
await bot.command("gamemode creative")

Movement API

Basic Movement

# Look at a position
await bot.look_at(100, 64, -20)

# Set rotation directly
await bot.look(yaw=90.0, pitch=45.0)

# Jump
await bot.jump()

# Toggle sneaking
await bot.sneak(True)
await bot.sneak(False)

# Toggle sprinting
await bot.sprint(True)
await bot.sprint(False)

# Stop all movement
await bot.stop()

# Swing hand (animation)
await bot.swing_hand()

Navigation

# Walk to position (simple)
await bot.walk_to(100, 64, -20)

# Navigate with pathfinding
await bot.goto(100, 64, -20, timeout=30.0)

# Follow an entity
await bot.follow(entity_id, distance=3.0)

Entity API

Querying Entities

# Get entity by ID
entity = bot.get_entity(entity_id)

# Find entities by name
players = bot.find_entities_by_name("Steve")

# Find entities by type
zombies = bot.find_entities_by_type("zombie")

# Get nearby entities
nearby = bot.get_nearby_entities(radius=20.0)

Entity Properties

# Access entity properties
entity.position
entity.health
entity.entity_type
entity.name
entity.distance_to(bot)

Block Interaction

Breaking and Placing

# Break a block
await bot.break_block(100, 64, -20)

# Place a block
await bot.place(100, 64, -20, "cobblestone")

# Use (right-click) a block
await bot.use(100, 64, -20)

# Dig (alias for break_block)
await bot.dig(100, 64, -20)

Tool and Equipment Management

Equipping Items

# Equip specific item
await bot.equip("diamond_pickaxe", "main_hand")

# Equip best tool for block
await bot.equip_best_tool("stone")

# Equip best weapon
await bot.equip_best_weapon()

Combat API

Combat Actions

# Attack an entity
await bot.attack(entity_id)

# Defensive stance
await bot.defend()

# Flee from danger
await bot.flee(direction=(0, -1))

Resource Gathering

Mining

# Mine specific blocks
await bot.mine("diamond_ore", amount=5, radius=32)

# Harvest crops/logs
await bot.harvest("wheat", amount=32, radius=10)
await bot.harvest("oak_log", amount=16, radius=20)

Collecting Items

# Collect items from ground
await bot.collect("diamond", amount=5, radius=20)

High-Level Behaviors

Exploration

# Explore area for a duration
await bot.explore(duration=60.0, radius=50)

Guarding

# Guard a position
await bot.guard(position=(100, 64, -20), radius=10.0)

# Guard current location
await bot.guard(radius=15.0)

Farming

# Farm crops in area
await bot.farm("wheat", area_radius=10)

Building

# Build structures
positions = [
    (1, 64, 1), (2, 64, 1), (3, 64, 1),
    (1, 64, 2), (2, 64, 2), (3, 64, 2),
]
await bot.build("stone", positions)

Inventory API

Querying Inventory

# Count items
count = bot.inventory.count_item("diamond")

# Check if has items
has_item = bot.inventory.has_item("iron_ingot", count=5)

# Find item
item = bot.inventory.find_item("diamond_pickaxe")

# Get held item
held = bot.inventory.get_held_item()

Inventory Operations

# Select hotbar slot
bot.inventory.select_hotbar_slot(0)

# Equip item
await bot.equip("diamond_sword", "main_hand")

Crafting API

Crafting Items

# Craft using recipe ID
await bot.craft("diamond_pickaxe", count=1)

# Craft by item name
recipes = bot.crafting.get_recipes_for_item("diamond_pickaxe")
if recipes:
    await bot.craft(recipes[0].recipe_id)

Recipe Management

# Get recipe
recipe = bot.crafting.get_recipe("crafting_table")

# Check if can craft
can_craft = bot.crafting.can_craft("diamond_pickaxe", bot.inventory.get_player_inventory())

# Get missing ingredients
missing = bot.crafting.get_missing_ingredients("diamond_pickaxe", bot.inventory.get_player_inventory())

Container Interaction

Opening and Using Containers

# Open a chest
await bot.open_container(100, 64, -20)

# Deposit items
await bot.deposit("iron_ingot")  # Deposit specific item
await bot.deposit()  # Deposit all items

# Withdraw items
await bot.withdraw("diamond", count=5)

# Close container
await bot.close_container()

Event System

Event Handlers

# Using decorator
@bot.on("chat")
async def on_chat(event):
    print(f"Chat: {event.data['raw']}")

# Programmatic registration
bot.on("chat", handler)
bot.off("chat", handler)

Common Events

@bot.on("bot.connected")
async def on_connected(event):
    print("Connected to server")

@bot.on("bot.spawned")
async def on_spawn(event):
    print(f"Spawned at {bot.position}")

@bot.on("chat")
async def on_chat(event):
    print(f"Chat: {event.data['raw']}")

@bot.on("entity.spawned")
async def on_entity_spawn(event):
    print(f"Entity spawned: {event.data}")

@bot.on("bot.health_changed")
async def on_health(event):
    print(f"Health: {event.data['health']}")

Tasks and Concurrency

Creating Tasks

# Create background task
task = bot.create_task(bot.follow(player))

# Wait for task with timeout
result = await bot.wait_for(task, timeout=30.0)

# Cancel task
task.cancel()

Concurrent Operations

# Run multiple operations concurrently
await asyncio.gather(
    bot.listen_for_chat(),
    bot.monitor_health(),
    bot.run_behavior()
)

Bot State Properties

Accessing Bot State

# Position
bot.position  # (x, y, z)
bot.state.position  # Same

# Health and stats
bot.health
bot.food
bot.saturation
bot.experience
bot.level

# World state
bot.game_mode
bot.dimension
bot.rotation  # (yaw, pitch)
bot.velocity  # (vx, vy, vz)

Exception Handling

Exception Hierarchy

from mindpy.exceptions import (
    MindPyError,          # Base exception
    ConnectionError,      # Connection failures
    ProtocolError,        # Protocol errors
    AuthenticationError,  # Auth failures
    NavigationError,      # Navigation failures
    PathNotFound,         # No path found
    ActionError,          # Action failures
    InventoryError,       # Inventory errors
    CraftingError,        # Crafting errors
    InteractionError,     # Block/entity interaction errors
    EntityNotFound,       # Entity not found
    BlockNotFound,        # Block not found
    OperationCancelled,   # Operation cancelled
    ContainerError,       # Container errors
    CombatError,          # Combat errors
    TaskError,            # Task errors
    PluginError,          # Plugin errors
    StateError,           # Invalid state
    TimeoutError,         # Operation timeout
)

Error Handling Example

from mindpy.exceptions import PathNotFound, EntityNotFound

try:
    await bot.goto(100, 64, -20)
except PathNotFound:
    print("No path to target")
except TimeoutError:
    print("Operation timed out")

Plugin Architecture

Using Plugins

from mindpy.plugins import Plugin

class MyPlugin(Plugin):
    def __init__(self):
        super().__init__(name="my_plugin", version="1.0.0")

    async def on_load(self, bot):
        # Register event handlers
        @bot.on("chat")
        async def on_chat(event):
            await self.handle_chat(bot, event)

    async def handle_chat(self, bot, event):
        # Custom chat handling
        pass

# Load plugin
bot.plugin_manager.load_plugin(MyPlugin())

Complete Example

import asyncio
from mindpy import Bot, EventTypes

async def main():
    bot = Bot(
        host="localhost",
        port=25565,
        username="MinerBot"
    )

    @bot.on(EventTypes.BOT_SPAWNED)
    async def on_spawn(event):
        print(f"Spawned at {bot.position}")
        await bot.chat("MinerBot online!")

    @bot.on(EventTypes.CHAT_MESSAGE)
    async def on_chat(event):
        message = event.data.get("raw", "")
        if "mine" in message.lower():
            await bot.mine("diamond_ore", amount=5)
            await bot.chat("Mined 5 diamond ore!")

    async with bot:
        # Go to mining area
        await bot.goto(100, 64, -20)

        # Mine resources
        await bot.mine("iron_ore", amount=32)
        await bot.mine("coal_ore", amount=64)

        # Craft tools
        await bot.craft("iron_pickaxe")

        # Store items in chest
        await bot.open_container(105, 64, -20)
        await bot.deposit("iron_ingot")
        await bot.close_container()

        # Explore
        await bot.explore(duration=30.0, radius=50)

asyncio.run(main())

API Reference

Bot Class

Connection Methods

  • connect() - Connect to server
  • disconnect() - Disconnect from server
  • reconnect() - Reconnect with retry logic
  • run() - Run main bot loop

Chat Methods

  • chat(message) - Send chat message
  • whisper(target, message) - Send private message
  • command(command) - Execute server command

Movement Methods

  • look_at(x, y, z) - Look at position
  • look(yaw, pitch) - Set rotation
  • jump() - Jump
  • sneak(enabled) - Toggle sneaking
  • sprint(enabled) - Toggle sprinting
  • stop() - Stop movement
  • swing_hand() - Swing hand
  • walk_to(x, y, z) - Walk to position
  • goto(x, y, z) - Navigate with pathfinding
  • follow(entity_id) - Follow entity

Entity Methods

  • get_entity(entity_id) - Get entity by ID
  • find_entities_by_name(name) - Find by name
  • find_entities_by_type(type) - Find by type
  • get_nearby_entities(radius) - Get nearby entities

Block Methods

  • break_block(x, y, z) - Break block
  • place(x, y, z, block_type) - Place block
  • use(x, y, z) - Use block
  • dig(x, y, z) - Dig block

Tool Methods

  • equip(item_id, slot) - Equip item
  • equip_best_tool(block_type) - Equip best tool
  • equip_best_weapon() - Equip best weapon

Combat Methods

  • attack(entity_id) - Attack entity
  • defend() - Defensive stance
  • flee(direction) - Flee from danger

Resource Methods

  • mine(block_type, amount, radius) - Mine blocks
  • collect(item_type, amount, radius) - Collect items
  • harvest(block_type, amount, radius) - Harvest crops

Behavior Methods

  • explore(duration, radius) - Explore area
  • guard(position, radius) - Guard position
  • farm(crop_type, area_radius) - Farm crops
  • build(block_type, positions) - Build structure

Container Methods

  • open_container(x, y, z) - Open container
  • close_container() - Close container
  • deposit(item_id) - Deposit items
  • withdraw(item_id, count) - Withdraw items

Task Methods

  • create_task(coro) - Create background task
  • wait_for(coro, timeout) - Wait with timeout

Event Methods

  • on(event_type, priority) - Register handler (decorator)
  • off(event_type, handler) - Unregister handler

Properties

  • position - Current position (x, y, z)
  • health - Current health
  • food - Current food level
  • saturation - Current saturation
  • experience - Current experience
  • level - Current level
  • game_mode - Current game mode
  • dimension - Current dimension
  • rotation - Current rotation (yaw, pitch)
  • velocity - Current velocity

Best Practices

  1. Use Context Managers - Always use async with bot: for proper cleanup
  2. Handle Exceptions - Wrap operations in try/except for robustness
  3. Check State - Verify bot is connected before operations
  4. Use Pathfinding - Prefer goto() over direct position changes
  5. Equip Tools - Always equip appropriate tools for mining
  6. Monitor Health - Use event handlers to respond to low health
  7. Concurrent Tasks - Use create_task() for background operations
  8. Cancel Gracefully - Handle cancellation in long-running operations

Architecture

MindPy follows a layered architecture:

High-Level Behaviors (explore, guard, farm, build)
         ↓
Bot Tools (mine, collect, craft, combat)
         ↓
Core API (chat, move, interact, inventory)
         ↓
World & State (entities, blocks, chunks)
         ↓
Protocol Layer (packets, connection, login)

This design allows developers to work at the appropriate level of abstraction for their needs.