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:
- Low-Level Protocol - Direct protocol access for framework developers
- Bot Tools - Core bot operations for normal bot development
- Intelligent Behaviors - High-level automation for advanced AI agents
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())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
)# 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()# 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")# 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()# 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)# 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)# Access entity properties
entity.position
entity.health
entity.entity_type
entity.name
entity.distance_to(bot)# 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)# 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()# Attack an entity
await bot.attack(entity_id)
# Defensive stance
await bot.defend()
# Flee from danger
await bot.flee(direction=(0, -1))# 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)# Collect items from ground
await bot.collect("diamond", amount=5, radius=20)# Explore area for a duration
await bot.explore(duration=60.0, radius=50)# Guard a position
await bot.guard(position=(100, 64, -20), radius=10.0)
# Guard current location
await bot.guard(radius=15.0)# Farm crops in area
await bot.farm("wheat", area_radius=10)# 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)# 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()# Select hotbar slot
bot.inventory.select_hotbar_slot(0)
# Equip item
await bot.equip("diamond_sword", "main_hand")# 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)# 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())# 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()# 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)@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']}")# 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()# Run multiple operations concurrently
await asyncio.gather(
bot.listen_for_chat(),
bot.monitor_health(),
bot.run_behavior()
)# 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)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
)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")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())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())connect()- Connect to serverdisconnect()- Disconnect from serverreconnect()- Reconnect with retry logicrun()- Run main bot loop
chat(message)- Send chat messagewhisper(target, message)- Send private messagecommand(command)- Execute server command
look_at(x, y, z)- Look at positionlook(yaw, pitch)- Set rotationjump()- Jumpsneak(enabled)- Toggle sneakingsprint(enabled)- Toggle sprintingstop()- Stop movementswing_hand()- Swing handwalk_to(x, y, z)- Walk to positiongoto(x, y, z)- Navigate with pathfindingfollow(entity_id)- Follow entity
get_entity(entity_id)- Get entity by IDfind_entities_by_name(name)- Find by namefind_entities_by_type(type)- Find by typeget_nearby_entities(radius)- Get nearby entities
break_block(x, y, z)- Break blockplace(x, y, z, block_type)- Place blockuse(x, y, z)- Use blockdig(x, y, z)- Dig block
equip(item_id, slot)- Equip itemequip_best_tool(block_type)- Equip best toolequip_best_weapon()- Equip best weapon
attack(entity_id)- Attack entitydefend()- Defensive stanceflee(direction)- Flee from danger
mine(block_type, amount, radius)- Mine blockscollect(item_type, amount, radius)- Collect itemsharvest(block_type, amount, radius)- Harvest crops
explore(duration, radius)- Explore areaguard(position, radius)- Guard positionfarm(crop_type, area_radius)- Farm cropsbuild(block_type, positions)- Build structure
open_container(x, y, z)- Open containerclose_container()- Close containerdeposit(item_id)- Deposit itemswithdraw(item_id, count)- Withdraw items
create_task(coro)- Create background taskwait_for(coro, timeout)- Wait with timeout
on(event_type, priority)- Register handler (decorator)off(event_type, handler)- Unregister handler
position- Current position (x, y, z)health- Current healthfood- Current food levelsaturation- Current saturationexperience- Current experiencelevel- Current levelgame_mode- Current game modedimension- Current dimensionrotation- Current rotation (yaw, pitch)velocity- Current velocity
- Use Context Managers - Always use
async with bot:for proper cleanup - Handle Exceptions - Wrap operations in try/except for robustness
- Check State - Verify bot is connected before operations
- Use Pathfinding - Prefer
goto()over direct position changes - Equip Tools - Always equip appropriate tools for mining
- Monitor Health - Use event handlers to respond to low health
- Concurrent Tasks - Use
create_task()for background operations - Cancel Gracefully - Handle cancellation in long-running operations
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.