Connect and world#

A script talks to a Minecraft server through an Iwb object. mciwb run and mciwb shell make one and call it world; a standalone script makes its own.

Iwb

The connection to a Minecraft world, for scripts and the shell.

get_world

Return the current world object: the most recently created one.

Client

An RCON client for Minecraft Java Edition that copes with the server's other RCON clients.

get_client

Get the RCON client of the current thread.

set_client

Set the client for the current thread.

new_thread

Start a thread that has its own RCON connection to the server.

init_logging

Set up the mciwb log, which writes to stderr.

The world#

class mciwb.Iwb(server=HOST, port=def_port, passwd=None)[source]#

The connection to a Minecraft world, for scripts and the shell.

Making an Iwb connects to the server’s RCON port. The new object becomes the current world (see get_world()), and its connection becomes the client of the current thread, which get_client() returns and the builders use. mciwb run and mciwb shell make one for you and call it world.

With it a script can place and read blocks (set_block(), get_block()), run any command (cmd()), save and load regions (save(), load()), and read and draw what was built (scan(), render()).

The members for interactive play are frozen: they still work, but are no longer developed. They are player, copier, signs, add_player(), get_player() and players, which follow a player in the game with the Player, CopyPaste, Signs and Monitor classes. Call stop() when finished, to stop their monitoring threads.

Connecting also turns off the send_command_feedback game rule, so that operators in the game are not told of every RCON command.

If the server is the one that mciwb start runs in its default folder, world_folder is set and backup() works. That is so when server is "localhost", port is 20100 or the rcon.port in ~/mciwb-server/server.properties, and ~/mciwb-server/world holds a world.

A wrong password raises rcon.exceptions.WrongPassword.

Parameters:
  • server (str) -- The address of the server. Defaults to "localhost", for the server that mciwb start runs on this machine.

  • port (int) -- The RCON port of the server (not the game port that players use, which is one higher for a mciwb start server).

  • passwd (str | None) -- The RCON password of the server. Defaults to the MCIWB_PASSWORD environment variable, or to default_pass if that is not set, as the mciwb commands do. It is never logged.

Raises:
  • ConnectionRefusedError -- If nothing is listening on that port, for example because the server is not running or is still starting.

  • OSError -- For other network failures, such as an unknown host name.

Example:

from mciwb.imports import Item, Iwb, Vec3

world = Iwb()  # or Iwb("localhost", 20100, "my_password")
world.set_block(Vec3(0, 70, 0), Item.GOLD_BLOCK)
world.stop()
copier: CopyPaste#

The CopyPaste of the default player (frozen interactive feature). None until a player is added. When there is one, save() and load() default to its copy buffer.

signs: Signs#

The Signs of the default player (frozen interactive feature). None until a player is added.

world_folder: Path | None#

The server’s world folder, if it is on this machine, otherwise None. scan() and render() read blocks from its files, which is much faster than over RCON. It is set for the server of mciwb start when that uses the default --folder. For another folder, set it yourself: world.world_folder = Path("/my/server/world").

debug(enable=True)[source]#

Turn debug logging on or off.

Debug logging adds mciwb’s debug messages, and the file, line and function of every message. In mciwb shell it also shows the full traceback of an error, in place of a one line report. See init_logging().

Parameters:

enable (bool) -- True to turn debug logging on, False to turn it off.

backup(name=None)[source]#

Backup the Minecraft world to a zip file in ~/mciwb-backups.

This only works for the server that mciwb start runs in its default folder (see the class description). For any other server it logs the warning “no backup available” and does nothing: use Backup with the server’s own folders.

Parameters:

name (str | None) -- The name of the backup file, see backup(). Defaults to the current date and time.

connect()[source]#

Connect to the Minecraft server and make this the current thread’s client.

This is called when the Iwb is made. Call it again if the connection is lost, for example after the server restarts. It also turns off the send_command_feedback game rule. A wrong password raises rcon.exceptions.WrongPassword.

Returns:

The new RCON client, which get_client() now returns in this thread.

Raises:
Return type:

Client

get_player(name)[source]#

Get the player object for a player that has been added.

Parameters:

name (str) -- The name of the player, as given to add_player().

Returns:

The Player for that name.

Raises:

KeyError -- If no player of that name has been added.

Return type:

Player

property player: Player#

The default Player (frozen interactive feature).

There is none until add_player() is called, which mciwb run and mciwb shell do when given --player. Check players to see whether any player has been added.

Raises:

AttributeError -- If no player has been added.

property players: list[str]#

The names of the players added with add_player().

add_player(name, me=True, setup=True)[source]#

Add a player to the world object, for interactive play.

This is a frozen interactive feature. It starts a background Monitor thread that watches for the action signs that the player places (see Signs), and gives the player a set of those signs.

The default player is then available as world.player, with its world.copier and world.signs. Every added player is available by name from get_player(), and the names are in players.

If the player is not in the world, or the server does not respond, a warning is logged: the player is still added, but has not been set up or given signs.

Parameters:
  • name (str) -- The name of the player.

  • me (bool) -- Make this player the default player. The first player added becomes the default whatever this is.

  • setup (bool) -- Make the player an operator in creative mode, see setup().

Example:

world.add_player("Steve")
print(world.player.pos)
stop()[source]#

Stop all background monitoring threads.

Call this when finished with the world, for example at the end of a script that is run with plain python. mciwb run and mciwb shell call it for you. It stops every Monitor, including any that the script made itself.

set_block(pos, block, facing=None, nbt=None)[source]#

Place a block in the world.

Parameters:
  • pos (Vec3) -- The position to place the block at. It is rounded down to whole blocks.

  • block (Item) -- The type of block.

  • facing (Vec3 | None) -- The direction that the block should face, for blocks that have a facing state such as stairs and doors: one of the horizontal Direction values, for example Direction.NORTH.

  • nbt (list[str] | None) -- A list of block states to apply to the block, each as "name=value". (Despite the name these are block states, not NBT data.)

Returns:

True if the block is now in place, including when it was there already. False if the server rejected the command, for example for an unloaded position or a state that the block does not have: the server’s reply is logged as an error.

Return type:

bool

Example:

from mciwb.imports import Direction, Item, Vec3

# an upside down stair that faces east
world.set_block(
    Vec3(0, 70, 0), Item.OAK_STAIRS, Direction.EAST, nbt=["half=top"]
)
# the top half of an open door with its hinge on the left
world.set_block(
    Vec3(2, 71, 0),
    Item.OAK_DOOR,
    Direction.NORTH,
    nbt=["half=upper", "hinge=left", "open=true"],
)
place_door(pos, door_type, facing=Direction.NORTH, open=False, right_hinge=False)[source]#

Place a door in the world.

Doors are two blocks high: both halves are placed, replacing whatever was there (including another door).

Parameters:
  • pos (Vec3) -- The position of the bottom half of the door.

  • door_type (Item) -- The type of door to place, for example Item.OAK_DOOR.

  • facing (Vec3) -- The direction that the door should face. Defaults to Direction.NORTH.

  • open (bool) -- True for an open door, False for a closed one.

  • right_hinge (bool) -- True for a hinge on the right, False for the left.

Raises:

ValueError -- If door_type is not a door (its name does not end in _DOOR).

Example:

from mciwb.imports import Direction, Item, Vec3

world.place_door(Vec3(3, 70, 0), Item.SPRUCE_DOOR, Direction.SOUTH)
get_block(pos)[source]#

Get the type of the block at a position in the world.

This asks the server over RCON, one block for each call. To read a region, use scan().

Parameters:

pos (Vec3) -- The position of the block. It is rounded down to whole blocks.

Returns:

The type of the block.

Return type:

Item

Example:

if world.get_block(Vec3(0, 70, 0)) == Item.AIR:
    world.set_block(Vec3(0, 70, 0), Item.STONE)
save(filename, vol=None)[source]#

Save the blocks of a region of the world to a file.

The file is saved in the format of save_items(), which is a JSON file containing a 3D array of Item names. If the filename ends in .schem it is saved as a Sponge schematic instead, with the block states of stairs, slabs and logs (see from_world()), which other Minecraft tools such as WorldEdit can load.

The file can be loaded into a world with load().

Parameters:
  • filename (str | Path) -- The name of the file to save to.

  • vol (Volume | None) -- The region to save. Defaults to the copy buffer that the default player has selected (a frozen interactive feature).

Raises:

ValueError -- If no vol is given and there is no copy buffer.

Example:

from mciwb.imports import Vec3, Volume

vol = Volume.from_corners(Vec3(0, 64, 0), Vec3(9, 75, 9))
world.save("tower.schem", vol)
load(filename, position=None, anchor=Anchor3.BOTTOM_SW)[source]#

Load a saved set of blocks into the world.

The blocks are loaded from a file in the format of save_items(), which is a JSON file containing a 3D array of Item names, and placed with Blocks. If the filename ends in .schem they are loaded from a Sponge schematic instead (see Schematic).

If a player has been added, the copy buffer is then set to the region that was loaded.

Parameters:
  • filename (str | Path) -- The name of the file to load from.

  • position (Vec3 | None) -- Where to put the blocks. Defaults to the start of the copy buffer that the default player has selected (a frozen interactive feature).

  • anchor (Anchor3) -- Which point of the loaded blocks goes at position. Defaults to the bottom south west corner.

Raises:

ValueError -- If no position is given and there is no copy buffer.

Example:

from mciwb.imports import Anchor3, Vec3

world.load("tower.schem", Vec3(20, 64, 0), Anchor3.BOTTOM_NW)
scan(start, end)[source]#

Read the blocks between two opposite corners of a region.

The blocks are read from the world’s files if world_folder is set (after asking the server to save its changes), otherwise over RCON one block at a time. See mciwb.render.scan().

Parameters:
  • start (Vec3) -- A corner of the region.

  • end (Vec3) -- The opposite corner of the region.

Returns:

The blocks of the region, both corners included.

Raises:

ValueError -- If the region has more than 32768 blocks and has to be read over RCON, or the world’s files cannot be read.

Return type:

BlockGrid

Example:

grid = world.scan(Vec3(0, 64, 0), Vec3(9, 75, 9))
print(grid.counts())  # {'minecraft:stone_bricks': 240, ...}
render(start, end, file='render.png', views=('top', 'iso'), scale=None, labels=True)[source]#

Render the region between two opposite corners to an image file.

This shows what a build looks like without joining the game. The region is read with scan() and drawn with mciwb.render.render(), which describes the views.

Parameters:
  • start (Vec3) -- A corner of the region.

  • end (Vec3) -- The opposite corner of the region.

  • file (str | Path) -- The image file to write. The format follows the file extension: use .png.

  • views (Sequence[str]) -- The views to draw, side by side: a list of names from mciwb.render.VIEWS ("top", "iso", "north", "south", "east", "west", "iso_ne", "iso_nw", "iso_sw"), or the name of one view.

  • scale (int | None) -- Pixels per block for every view. By default each view gets its own scale, chosen to fit.

  • labels (bool) -- Add titles, and axis labels and grid lines with world coordinates.

Returns:

The blocks that were rendered.

Raises:

ValueError -- If a view is unknown, scale is less than 1, or the region cannot be read (see scan()).

Return type:

BlockGrid

Example:

world.render(
    Vec3(0, 64, 0), Vec3(9, 75, 9), "tower.png", views=["iso", "south"]
)
cmd(cmd, expect=None)[source]#

Run any arbitrary Minecraft console command on the server.

The server’s reply is returned as it is, including error messages such as Incorrect argument for command...<--[HERE]. (On Minecraft 26.x, for example, game rules have snake case names, so gamerule doDaylightCycle is an error: use gamerule advance_time. And time query daytime is an error too: use time query day for the ticks into the current day, and time query day repetition for the number of days.)

Changed: before mciwb#166 the errors that mcipc recognises were raised as mcipc exceptions (e.g. InvalidArgument); now they are returned as text like any other reply.

Another RCON client of the server (e.g. a dashboard) can, rarely, garble the reply: empty it or add its own output to it. Pass expect to check the reply and send the command again if needed. Only do that for a command that is safe to send twice (e.g. setblock, tp to a fixed place, gamerule ..., but not give or summon).

Parameters:
  • cmd (str) -- The command to run, without the leading slash, for example "time set day".

  • expect (str | None) -- A regular expression that the reply must contain, for example r"Game rule \S+ is currently set to \S+". See retry_command() for how the command is sent again.

Returns:

The server’s response. With expect, just the part of it that matched, or the whole response if it never matched.

Return type:

str

Example:

world.cmd("time set day")
reply = world.cmd(
    "gamerule advance_time",
    expect=r"Game rule \S+ is currently set to \S+",
)
mciwb.get_world()[source]#

Return the current world object: the most recently created one.

In a script run by mciwb run, and in mciwb shell, this is the world that is already connected. Modules that a script imports use this to reach it.

Returns:

The most recently created Iwb, or None if none has been created yet in this process.

Return type:

Iwb

Example:

from mciwb.imports import Item, Vec3, get_world

def marker(pos: Vec3):
    get_world().set_block(pos, Item.GOLD_BLOCK)

RCON clients and threads#

The RCON client that mciwb talks to the server with, and one client for each thread.

One client per thread. A Client is one RCON connection to the server, and each thread that sends commands needs its own. The client of a thread is kept in thread local storage: get_client() returns the client of the thread that calls it, and everything in mciwb that sends a command gets its client that way. The first client is made on the main thread, by Iwb (or by hand, and stored with set_client()). A thread started with new_thread(), as Monitor does, opens its own connection to the same server. A plain threading.Thread has no client until it calls set_client().

Replies are checked and commands retried. The Minecraft server collects the output of all its RCON connections in one buffer, so two connections that run commands at the same moment can get each other’s output, or none. Within one process, mciwb sends one command at a time, whatever the thread, which prevents that. It can not stop another process (a second script, or a dashboard that polls the server) from running a command at the same moment. So the client checks the replies of setblock, fill and loot, which are safe to send twice, and sends the command again, up to RCON_ATTEMPTS times in all, until the reply is the command’s own. Every other command is sent once: for one that is safe to repeat, pass expect to cmd(), or use retry_command().

class mciwb.Client(*args, frag_threshold=4096, **kwargs)[source]#

Bases: Client

An RCON client for Minecraft Java Edition that copes with the server’s other RCON clients.

This is mcipc.rcon.je.client.Client with a different way of sending commands, so it has a method for each Minecraft command (client.setblock(...), client.fill(...), client.data.get(...) and so on) and is created in the same way. Most code does not create one: Iwb connects the first client, and get_client() returns the client of the current thread.

Each command waits for any command running on another connection of this process to complete, so that the server returns the output of this command only.

Other processes can still run commands at the same moment, which can empty our reply or add theirs to it (about 1 in 10000 commands while another client polls the server). So the replies of setblock and fill (except in destroy mode) and loot (as used by get_block()) are checked, the command is sent again if the reply is lost, and only the command’s own output is returned. Other commands, including clone, are sent once: use retry_command(), or the expect argument of cmd(), for those that are safe to send again.

Example:

from mciwb import Client, set_client

with Client("localhost", 25575, passwd="secret") as client:
    set_client(client)
    print(client.run("time", "query", "day"))
run(command, *arguments)[source]#

Run a command and raise an exception for an error that mcipc knows.

Every command method of the client goes through here, so this is where the reply is checked and the command sent again (for the commands described in the class).

If the reply is one of the error messages that mcipc recognises, such as Unknown or incomplete command or Incorrect argument for command, the matching exception from mcipc.rcon.exceptions is raised (UnknownCommand, InvalidArgument and so on, all of them a CommandError). Any other error message is returned as the reply.

Parameters:
  • command (str) -- The command, or its first word, with no leading slash.

  • *arguments (str) -- More words of the command. They are joined to command with spaces, and the first None ends the command.

Returns:

The server’s reply, or just the command’s own output for the commands whose replies are checked.

Return type:

str

run_raw(command, *arguments)[source]#

Run a command and return the server’s reply, whatever it says.

Like run(), with the same checks and retries, but an error message from the server is returned as text and no mcipc exception is raised. cmd() uses this.

Parameters:
  • command (str) -- The command, or its first word, with no leading slash.

  • *arguments (str) -- More words of the command. They are joined to command with spaces, and the first None ends the command.

Returns:

The server’s reply, or just the command’s own output for the commands whose replies are checked.

Return type:

str

mciwb.get_client()[source]#

Get the RCON client of the current thread.

Every thread needs its own RCON connection. The thread that creates an Iwb gets one from it, and threads created with new_thread() (as Monitor does) get one automatically.

Returns:

The client that was set for the calling thread.

Raises:

AttributeError -- If no client has been set for this thread: no world has been connected, or this is a plain threading.Thread.

Return type:

Client

Example:

from mciwb.imports import Item, Vec3, get_client

reply = get_client().setblock(Vec3(0, 70, 0), Item.STONE)
mciwb.set_client(client)[source]#

Set the client for the current thread.

Use this when the client has been created by hand, not by Iwb or new_thread(). A client is one connection, so do not give the same client to two threads.

Parameters:

client (Client) -- The connected client that this thread sends its commands through from now on.

mciwb.new_thread(client, target, name)[source]#

Start a thread that has its own RCON connection to the server.

The new thread first opens a connection to the same server as client and logs in, makes that its client (see get_client()), then calls target. If the connection fails, the exception ends the thread and target is not called.

The thread is a daemon thread so that it can never keep the Python interpreter alive on exit. Monitor starts its threads with this function: use stop_all() to stop those cleanly.

Parameters:
  • client (Client) -- The client whose host, port and password the new thread uses for its own connection.

  • target (Callable[[], None]) -- The function to run in the new thread, called with no arguments.

  • name (str) -- The name of the new thread, as returned by get_thread_name().

Returns:

The thread, which has already been started.

Return type:

Thread

Example:

from mciwb import new_thread
from mciwb.imports import Item, Vec3, get_client, get_world

world = get_world()

def build() -> None:
    for x in range(100):
        world.set_block(Vec3(x, 70, 0), Item.STONE)

thread = new_thread(get_client(), build, "builder")
thread.join()

Retries#

mciwb.threads.retry_command(send, check, description, attempts=RCON_ATTEMPTS)[source]#

Send a command again until its reply is the command’s own.

This is for when another RCON client of the server may have emptied the reply or added its own output to it (see mciwb.threads). The command is sent until its reply passes check, or it has been sent attempts times. Each failed reply is logged as a warning.

Only use this for commands that do the same thing when sent twice, such as setblock or tp to a fixed place, but not give or summon: a garbled reply does not mean that the command failed.

A non-empty reply that fails check twice in a row, word for word, is taken to be the server’s real reply (for example an error such as “That position is not loaded”): garbled replies are random, so it is returned at once and the command is not sent again.

Parameters:
  • send (Callable[[], str]) -- A function that sends the command and returns the reply.

  • check (Callable[[str], str | None]) -- A function that returns the command’s own output from a reply, or None if it is not there. See reply_matches().

  • description (str) -- The command, for the log messages.

  • attempts (int) -- The most times to send the command.

Returns:

The command’s own output, as returned by check, or the last reply as it is if no reply passed the check.

Return type:

str

Example:

from mciwb.imports import get_client
from mciwb.threads import reply_matches, retry_command

client = get_client()
command = "tp Steve 0 70 0"
reply = retry_command(
    lambda: client.run_raw(command),
    reply_matches(r"Teleported Steve to "),
    command,
)
mciwb.threads.reply_matches(pattern)[source]#

Make a reply check that looks for a regular expression in the reply.

Parameters:

pattern (str | Pattern[str]) -- The regular expression that a command’s own output matches. It is searched for anywhere in the reply.

Returns:

A ReplyCheck for retry_command(): given a reply, it returns the first text in it that matches pattern, or None if nothing matches.

Return type:

Callable[[str], str | None]

>>> from mciwb.threads import reply_matches
>>> check = reply_matches("The time is [0-9]+")
>>> check("There are 0 of a max of 20 players online: The time is 1000")
'The time is 1000'
>>> check("") is None
True
mciwb.threads.ReplyCheck#

The type of a check of a command’s reply. It is a function that takes the reply and returns the command’s own output, without any other client’s output around it, or None if the command’s output is not in the reply. See reply_matches().

alias of Callable[[str], str | None]

mciwb.threads.RCON_ATTEMPTS = 5#

The most times that a command which is safe to repeat is sent when its reply is lost or garbled by another RCON client. After that the last reply is returned as it is.

mciwb.threads.get_thread_name()[source]#

Get the name of the current thread.

Returns:

The name that was passed to new_thread(), or the Python thread name for any other thread.

Return type:

str

Logging#

mciwb.logging.init_logging(debug)[source]#

Set up the mciwb log, which writes to stderr.

mciwb run and mciwb shell call this for you (with debug set by their --debug option). A script that is run with plain python calls it itself: until it does, only mciwb’s warnings and errors are shown, in Python’s default format. It can be called again to change the level, as debug() does.

Parameters:

debug (bool) -- False for messages of level INFO and above, as INFO:<tab>message. True for DEBUG messages too, each with the file, line number and function that logged it.

Example:

from mciwb.imports import Iwb
from mciwb.logging import init_logging

init_logging(debug=False)
world = Iwb()  # logs "INFO:   Connected to localhost on 20100"