class Minecraft(host: str = 'localhost', port: int = 1789)

Minecraft is the main object of interacting with Minecraft servers that have the mcpq-plugin. When constructing the class, a host and port of the server should be provided to which a connection will be built. They default to "localhost" and 1789 respectively. All other worlds, events, entities and more are then received via the methods of that instance.

from mcpq import Minecraft
mc = Minecraft()  # connect to localhost
mc.postToChat("Hello Minecraft")  # send message in chat

Note

Generally, it is sufficient to construct one Minecraft instance per server or active connection, as this connection is thread-safe and reusable. However, it is also possible to connect with multiple instances from the same or different hosts at the same time.

Caution

The connection used by the server is not encrypted or otherwise secured, meaning that any man-in-the-middle can read and modify any information sent between the program and the Minecraft server. For security reasons it is recommended to connect from the same host as the server is running on. By default, the plugin does only allow connections from localhost to prevent access from third parties.

The Minecraft instance is also the default World and can be used to query Entity, Player and Event objects from the server. Checkout the corresponding classes for more information.

from mcpq import Minecraft

mc = Minecraft()  # connect to server on localhost with mcpq-plugin

mc.postToChat("Players online:", mc.getPlayerList())  # show online players
mc.events.block_hit.register(mc.postToChat)  # print whenever a player hits a block to chat
mc.setBlock("obsidian", mc.Vec3(0, 0, 0))  # set obsidian block at origin
pos = mc.getHighestPos(0, 0).up(1)  # get position above highest ground at 0 0
stairs = mc.blocks.endswith("_stairs").choice()  # get random block ending in "_stairs"
mc.setBlock(stairs.withData({"waterlogged": True}), pos)  # set waterlogged stairs above ground
creeper = mc.spawnEntity("creeper", pos.up(1))  # spawn creeper on stairs
creeper.giveEffect("invisibility")  # give creeper permanent invisibility effect
creeper.pos = mc.getPlayer().pos  # teleport creeper to player position
# and many more ...
property host: str

The Minecraft server host address this instance is connected to, default is localhost.

property port: int

The Minecraft server port this instance is connected to, default is 1789.

property Block: type[Block]

Alias for constructing Block, e.g., mc.Block("acacia_stairs")

property EntityType: type[Block]

Alias for constructing EntityType, e.g., mc.EntityType("creeper")

property NBT: type[NbtCompound]

Alias for constructing NBT, e.g., mc.NBT({"unbreakable": {}})

property Vec3: type[Vec3]

Alias for constructing Vec3, e.g., mc.Vec3(1, 2, 3)

property vec: type[Vec3]

Alias for constructing Vec3, e.g., mc.vec(1, 2, 3)

property events: EventHandler

The EventHandler for receiving events from the server. Checkout the EventHandler class for examples for receiving events.

property blocks: MaterialFilter

The MaterialFilter containing all types of blocks on the server. Equivalent to mc.materials.block(). Checkout the MaterialFilter class for examples on filtering.

property materials: MaterialFilter

The MaterialFilter containing all materials on the server, including types of blocks, items and more. Checkout the MaterialFilter class for examples on filtering.

property entity_types: EntityTypeFilter

The EntityTypeFilter containing all entity-types on the server. Checkout the EntityTypeFilter class for examples on filtering.

Note

You probably want to use spawnables to get spawnable entity-types only

property spawnables: EntityTypeFilter

The EntityTypeFilter containing all entity-types on the server that can be spawned with spawnEntity(). Equivalent to mc.entity_types.spawnable(). Checkout the EntityTypeFilter class for examples on filtering.

postToChat(*objects, sep: str = ' ') None

Print objects in chat separated by sep. All objects are converted to strings using str() first.

mc.postToChat("Hello Minecraft")
# print all only players
mc.postToChat("Players online:", *mc.getPlayerList())
# print every block hit event into chat (good for learning events)
mc.events.block_hit.register(mc.postToChat)

You can also use the module mcpq.text to color or markup your chat messages:

from mcpq import Minecraft, text
mc.postToChat(text.RED + text.BOLD + "super " + text.RESET + text.BLUE + "cool!")
# prints "super cool!", where "super" is red and bold, and "cool!" is blue
Parameters:

sep (str, optional) – the separator between each object, defaults to “ “

getEntityById(entity_id: str) Entity

Get an entity with a certain entity_id, even if it is not loaded.

Normally the entity_id is not known ahead of time. Prefer using getEntities(), getEntitiesAround() and spawnEntity(), which all return entities.

Parameters:

entity_id (str) – the unique entity identified

Returns:

the corresponding entity with that id, even if not loaded

Return type:

Entity

getOfflinePlayer(name: str) Player

Get the Player with the given name no matter if the player is online or not. Does not raise any errors if the player is offline.

Parameters:

name (str) – player name/id

Returns:

the player with the given name

Return type:

Player

getPlayer(name: str | None = None) Player

Get any currently online player or get the online player with given name. Will raise an error if either no player is online, or if the player with given name is not online.

If you want to check for any currently online players, use getPlayerList() instead.

Note

There is no guarantee that the player returned will be the same across multiple calls of this function. It may change depending on the order the players joined the server or the implementation of the server.

Parameters:

name (str | None, optional) – name of the online Player that should be returned, or None if any online player will do, defaults to None

Returns:

the player with name if name is given, else any online player

Return type:

Player

getPlayerList(names: list[str] | None = None) list[Player]

Get all currently online players on the entire server. If names is provided get all players with the given names only if they are online. Will raise an error if names is provided and at least one player with given name is offline.

Parameters:

names (list[str] | None, optional) – if given return only players with given names or error if one of the given players is offline, otherwise if names is None will return all currently online players, defaults to None

Returns:

the list of all currently online players, or if names is provided, only those online players

Return type:

list[Player]

property worlds: tuple[World, ...]

Give a tuple of all worlds loaded on the server. Does not automatically call refreshWorlds().

Returns:

A tuple of all worlds loaded on the server

Return type:

tuple[World, …]

property overworld: World

Identical to getWorldByKey() with key "minecraft:overworld".

Returns:

The overworld world World object

Return type:

World

property nether: World

Identical to getWorldByKey() with key "minecraft:the_nether".

Returns:

The nether world World object

Return type:

World

property end: World

Identical to getWorldByKey() with key "minecraft:the_end".

Returns:

The end world World object

Return type:

World

getWorldByKey(key: str) World

The key of a world is the dimensions internal name/id. Typically a regular server has the following worlds/keys:

  • "minecraft:overworld"

  • "minecraft:the_nether"

  • "minecraft:the_end"

The "minecraft:" prefix may be omitted, e.g., "the_nether".

If the given key does not exist an exception is raised.

Parameters:

key (str) – Internal name/id of the world, such as "minecraft:the_nether" or "the_nether"

Returns:

The corresponding World object

Return type:

World

getWorldByName(name: str) World

The name of a world is the folder or namespace the world resides in. The setting for the world the server opens is found in server.properties. A typical, unmodified PaperMC server will save the worlds in the following folders:

  • "world", for the overworld

  • "world_nether", for the nether

  • "world_the_end", for the end

The name of the overworld (default world) is used as the prefix for the other folders.

If the given name does not exist an exception is raised.

Parameters:

name (str) – Foldername the world is saved in, such as world

Returns:

The corresponding World object

Return type:

World

refreshWorlds() None

Fetches the currently loaded worlds from server and updates the world objects. This should only be called if the loaded worlds on the server change, for example, with the Multiverse Core Plugin. By default, the worlds will be refreshed on first use only.

getMinecraftVersion() str

The Minecraft version of the server this instance is connected to or None if the version cannot be identified.

getMinecraftVersionTuple() tuple[int, ...]

The Minecraft version of the server this instance is connected to as a integer tuple or None if the version cannot be identified (e.g. from non-release candidate servers).

getPluginVersion() str

The MCPQ Plugin version running on the server this instance is connected to.

getServerVersion() str

The full name and version of the server this instance is connected to.

runCommand(command: str) None

Run the command as if it was typed in chat as /-command. The command is run with the highest possible permission and no other modifiers. Returns immediately without waiting for the command to finish executing.

mc.runCommand("kill @e")
mc.runCommand("gamerule doDaylightCycle false")
Parameters:

command (str) – the command without the slash /

runCommandBlocking(command: str) str

Run the command as if it was typed in chat as /-command and return the response from the server. The command is run with the highest possible permission and no other modifiers. The function blocks and waits for the command to finish executing returning the command’s console output.

response = mc.runCommandBlocking("locate biome mushroom_fields")

Caution

The plugin that is built against the spigot-Bukkit API does not fully support the return of command output, specifically the capturing of output of vanilla commands. Instead it only supports the capturing of Bukkit commands, which can be seen with mc.runCommandBlocking("help Bukkit").split("\n")

Parameters:

command (str) – the command without the slash /

Returns:

the console output of the command

Return type:

str

property pvp: bool

True if any world on the server has pvp enabled. Can be set to enable or disable pvp on all worlds on the server.

getHighestPos(x: int | float, z: int | float) Vec3

The position of the highest non-air block with given x and z in the world.

Returns:

The position of the highest non-air block with given x and z

Return type:

Vec3

getHeight(x: int | float, z: int | float) int

Equivalent to the y value of getHighestPos() with x and z.

getBlock(pos: Vec3) Block

The block Block type/id at position pos in world.

Note

The function does only query the block type/id, no block component data is not queried. To query block component data use getBlockWithData().

Parameters:

pos (Vec3) – position to query block from

Returns:

block type/id at queried position

Return type:

Block

getBlockWithData(pos: Vec3) Block

The block Block at position pos in world including block component data.

pos = mc.vec(1, 2, 3)
mc.setBlock("furnace", pos)
block_without_data = mc.getBlock(pos)  # returns type Block
print(block_without_data)
# >>> "furnace"
block_with_data = mc.getBlockWithData(pos)  # returns type Block
print(block_with_data)
# >>> "furnace[facing=north,lit=false]"
mc.setBlock(block_with_data.withData({"lit": True}), pos)  # make furnce look lit
Parameters:

pos (Vec3) – position to query block from

Returns:

block type/id and component data at queried position

Return type:

Block

getBlockList(positions: list[Vec3]) list[Block]

The list of all block Block types/ids at given positions in world in the same order.

Note

The function does only query the block type/ids, no block component data is not queried.

Parameters:

positions (list[Vec3]) – list of positions to query

Returns:

list of block types/ids at given positions (same order)

Return type:

list[Block]

getBlockListWithData(positions: list[Vec3]) list[Block]

The list of all block Block at given positions in world with component data in the same order.

Parameters:

positions (list[Vec3]) – list of positions to query

Returns:

list of block type/ids and component data at given positions (same order)

Return type:

list[Block]

setBlock(blocktype: str | Block, pos: Vec3) None

Change the block at position pos to blocktype in world. This will overwrite any block at that position.

mc = Minecraft()
pos = mc.vec(1, 2, 3)
# set blocks in default world
mc.setBlock("acacia_stairs", pos)
mc.setBlock(mc.Block("acacia_stairs"), pos)
mc.setBlock(mc.Block("acacia_stairs").withData({"waterlogged": True}), pos)
# or set in specific world
mc.nether.setBlock(...)

If you want to set many blocks of the same type use setBlockList() instead:

start = mc.vec(0, 50, 0)
for x in range(1000):
   pos = start.addX(x)
   mc.setBlock("gold_block", pos)

# instead use setBlockList which is much more efficient:

positions = [start.addX(x) for x in range(1000)]
mc.setBlockList("gold_block", positions)
Parameters:
  • blocktype (str | Block) – the valid block type/id or Block to set the block to

  • pos (Vec3) – the position where the block should be set

setBlockList(blocktype: str | Block, positions: list[Vec3]) None

Change all blocks at positions to blocktype in world. This will overwrite all blocks at the given positions. This is more efficient that using setBlock() multiple times with the same blocktype.

start = mc.vec(0, 50, 0)
positions = [start.addX(x) for x in range(1000)]
mc.setBlockList("gold_block", positions)

# this is equivalent to but much more efficent and faster than:

for x in range(1000):
   pos = start.addX(x)
   mc.setBlock("gold_block", pos)
Parameters:
  • blocktype (str | Block) – the valid block type/id to set the blocks to

  • positions (list[Vec3]) – the positions where the blocks should be set

setBlockCube(blocktype: str | Block, pos1: Vec3, pos2: Vec3) None

Change all blocks in a cube between the corners pos1 and pos2 in world to blocktype, where both positions are inclusive. meaning that both given positions/corners will be part of the cube. This will overwrite all blocks between the given positions. The positions span a cube if all their coordinates are different, a plane if one of their coordinates is the same or a line if two of their three coordinates are the same.

# xlen, ylen, zlen are the length of the cube in the specified axis
start = Vec3()  # this would be the lowest (most negative coordinates) corner of the cube we want to draw, here origin
world.setBlockCube("diamond_block", start, start.addX(xlen).addY(ylen).addZ(zlen))

# this is equivalent to but much more efficent and faster than:

for x in range(xlen + 1):
    for y in range(ylen + 1):
        for z in range(zlen + 1):
            world.setBlock("diamond_block", start.addX(x).addY(y).addZ(z))
Parameters:
  • blocktype (str | Block) – the valid block type/id to set the blocks to

  • pos1 (Vec3) – the position of one corner of the cube

  • pos2 (Vec3) – the position of the opposite corner of the cube

setBed(pos: Vec3, direction: Literal['east', 'south', 'west', 'north'] = 'east', color: Literal['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] = 'red') None

Place a bed at pos in direction with color, which is composed of two placed blocks with specific block data.

Parameters:
  • pos (Vec3) – the position of foot part of bed

  • direction (CARDINAL, optional) – direction in which to place head part of bed, defaults to “east”

  • color (COLOR, optional) – color of bed, defaults to “red”

setSign(pos: Vec3, text: list[str | NbtCompound | dict] | str, *, color: Literal['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] = 'black', glowing: bool = False, direction: Literal['east', 'south', 'west', 'north'] | int = 'south', sign_block: str | Block = 'oak_sign') None

Place a sign block at pos with text overwriting any block there. text can be a list of at most 8 elements, where each element is a line of text on the sign; the first 4 on the front and the second 4 on the back. Lists with fewer than 8 elements are allowed and result in empty following lines. text may also be a string in which case the above list is built by splitting the string on newlines. The elements in the list may also be NBT instances of the form: {selector: "@p", color: "red", bold: false, italic: false, underlined: false, strikethrough: false, obfuscated: false, text: "A Line of Text"} The material and type of sign can be set with sign_block - it can be a sign, wall_sign, or hanging_sign of any given wood material.

pos = Vec3(0, 120, 0) # position where to place sign
mc.setSign(pos, "Hello Minecraft") # front line 1
mc.setSign(pos, "Hello\nMinecraft") # front line 1 and 2
mc.setSign(pos, ["Hello", "Minecraft"]) # front line 1 and 2
mc.setSign(pos, ["", "Hello", "Minecraft"]) # front line 2 and 3
# back line 6 and 7
mc.setSign(pos, ["", "", "", "",  "", "Hello", "Minecraft"])
# everything beyond line 8 (back line 4) is not on sign anymore
mc.setSign(pos, ["", "", "", "",  "", "", "", "",  "NOT ON SIGN"])
# line-wise customization with NBT compounds or dicts
mc.setSign(pos, [{"text": "Hello", "color": "red"}, NBT({"text": "Minecraft", "bold": True})])

valid_signs = mc.blocks.endswith("_sign")
mc.setSign(..., sign_block="spruce_sign")
mc.setSign(..., sign_block="jungle_wall_sign")
mc.setSign(..., sign_block="acacia_hanging_sign")
mc.setSign(..., sign_block="acacia_hanging_sign[attached=true]")
mc.setSign(..., sign_block=Block("oak_sign").withData({"waterlogged": True}))

mc.setSign(pos, "\nHello\nMinecraft\n", direction="east", color="green", glowing=True)
Parameters:
  • pos (Vec3) – the position where the sign should be set

  • text (list[str | NBT | dict[str, Any]] | str) – the text to put on sign either as list of at most 8 elements, where the first 4 are text on the front and the second set of 4 are the text on the back of the sign, or as a string, where said list is produced by splitting on newlines. Elements of the list may also be NBT compounds instead of strings.

  • color (COLOR, optional) – the base color of the text on the sign, can be overwritten on a per-line basis by providing NBT({“text”:”…”,”color”:”red”}) NBT compounds, defaults to “black”

  • glowing (bool, optional) – whether or not the text should use the glowing effect, defaults to False

  • direction (CARDINAL | int, optional) – the cardinal direction the sign should be facing, for non-wall signs can also be an integer between 0-15, defaults to “south”

  • sign_block (str | Block, optional) – the block type/id of the sign that should be placed, should end with “_sign”, defaults to “oak_sign”

copyBlockCube(pos1: Vec3, pos2: Vec3, withData: bool = False) list[list[list[Block]]]

Get all block types in a cube between pos1 and pos2 inclusive. Should be used in conjunction with pasteBlockCube().

Parameters:
  • pos1 (Vec3) – the position of one corner of the cube

  • pos2 (Vec3) – the position of the opposite corner of the cube

  • withData (bool, optional) – whether block component data should be queried, defaults to False

Returns:

the block types in the cube given as rows of x with columns of y with slices of depth z respectively

Return type:

list[list[list[Block]]]

pasteBlockCube(blocktypes: list[list[list[str | Block]]], pos: Vec3, rotation: Literal['east', 'south', 'west', 'north', 'up', 'down'] = 'east', flip_x: bool = False, flip_y: bool = False, flip_z: bool = False) None

Paste the block types in the cube blocktypes into the world at position pos where pos is the negative most corner of the cube along all three axes. Additional options can be used to change the rotation of blocks in the copied cube, however, no matter in which way the cube is rotated and/or flipped, pos will also be the most negative corner. Should be used in conjunction with copyBlockCube().

start = Vec3(0, 0, 0)
end = start.addX(5).addY(5).addZ(5)
# copy a 6x6x6 block cube from origin in world
blocks = world.copyBlockCube(start, end)
# replace that space with the same blocks but rotated by 90 degrees
world.pasteBlockCube(blocks, start, "south")
# copy same original block at different point above origin
world.pasteBlockCube(blocks, start.up(200))
Parameters:
  • blocktypes (list[list[list[str | Block]]]) – the cube of block types/ids that should be pasted, given as rows of x with columns of y with slices of depth z respectively

  • pos (Vec3) – the most negative corner along all three axes of the cube where the cube should be pasted

  • rotation (DIRECTION, optional) – the direction of the x axis of the cube to be pasted (“east” means copied x axis aligns with real x axis, i.e., the original orientation), defaults to “east”

  • flip_x (bool, optional) – flip pasted blocks along x axis, defaults to False

  • flip_y (bool, optional) – flip pasted blocks along y axis, defaults to False

  • flip_z (bool, optional) – flip pasted blocks along z axis, defaults to False

spawnEntity(type: str | Block, pos: Vec3) Entity

Spawn and return a new entitiy of given type at position pos in world. The entity has default settings and behavior.

cow = mc.spawnEntity("cow", mc.getHighestPos(0, 0).up())
creeper = mc.spawnEntity("creeper", mc.getHighestPos(0, 0).up())
creeper.giveEffect("invisibility")  # make creeper permanently invisible
creeper.pos = mc.getPlayer().pos  # teleport creeper a player
Parameters:
  • type (str | EntityType) – the valid entity type that should be spawned (must be spawnable without additional parameters)

  • pos (Vec3) – the position where to spawn the entitiy in the world

Returns:

the Entity entity spawned

Return type:

entity.Entity

spawnItems(type: str | Block, pos: Vec3, amount: int = 1) None

Spawn amount many collectable items of type at pos.

pos = mc.vec(1, 2, 3)  # position where to spawn the item (on the ground)
mc.spawnItems("iron_sword", pos)  # spawn a dropped iron_sword at pos
mc.spawnItems(mc.Block("iron_sword").withData({"enchantments": {"sharpness": 5}}), pos)  # enchanted
mc.spawnItems("acacia_stairs", pos, 64)  # spawn a stack of dropped acacia_stairs at pos
# for component data that should be set on blocks once placed, use asBlockStateForItem()
mc.spawnItems(mc.Block("acacia_stairs").withData({"waterlogged": True}).asBlockStateForItem(), pos, 64)
Parameters:
  • type (str | Block) – the item type as string or Block, e.g., "minecraft:arrow" with potential component data

  • pos (Vec3) – position where to spawn the items

  • amount (int, optional) – number of items to spawn, defaults to 1

getEntities(type: str | Block | None = None, only_spawnable: bool = True) list[Entity]

Get all (loaded) entities in the world. If a type is provided, only entities of that type are returned. By default only entities of types that could be spawned using spawnEntity() are returned. To get all entities (except players) set only_spawnable=False, which will also return non-spawnable entities such as e.g. "falling_block" or "dropped_item".

entities = mc.getEntities()  # get all (loaded) entities in the world
items = mc.getEntities("item")  # get only all (loaded) dropped items
mc.removeEntities("item")  # remove all dropped items (is more efficient than iterating over items manually)
Parameters:
  • type (str | EntityType | None, optional) – if provided returns only entities of that type, returns all types if None, defaults to None

  • only_spawnable (bool, optional) – if False, will also return non-spawnable entities, defaults to True

Returns:

list of (loaded and filtered) entities in the world

Return type:

list[entity.Entity]

getEntitiesAround(pos: Vec3, distance: float, type: str | Block | None = None, only_spawnable: bool = True) list[Entity]

Equivalent to getEntities(), however, is filtered to only return entities within distance around pos. Is more efficient that filtering the list manually.

Parameters:
  • pos (Vec3) – position around which the entities are returned

  • distance (float) – the maximum distance entities returned have around pos

  • type (str | EntityType | None, optional) – if provided returns only entities of that type, returns all types if None, defaults to None

  • only_spawnable (bool, optional) – if False, will also return non-spawnable entities, defaults to True

Returns:

list of (loaded and filtered) entities in the world closer than distance to pos

Return type:

list[entity.Entity]

removeEntities(type: str | Block | None = None) None

Remove all entities (except players) from the world, they do not drop anything. If type is provided remove only entities of that type.

Parameters:

type (str | EntityType | None, optional) – if provided removes only entities of that type, otherwise remove all entities, defaults to None

getNbt(pos: Vec3) NBT | False | None

Get the block entitiy’s NBT data at pos as NBT. Return None if the block is not loaded or False if the block is loaded but not a block entity. The data is not cached NBT data is always queried on call.

Caution

This function requires command output captuing. The plugin that is built against the spigot-Bukkit API does not fully support the return of command output.