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.
The connection to a Minecraft world, for scripts and the shell. |
|
Return the current world object: the most recently created one. |
|
An RCON client for Minecraft Java Edition that copes with the server's other RCON clients. |
|
Get the RCON client of the current thread. |
|
Set the client for the current thread. |
|
Start a thread that has its own RCON connection to the server. |
|
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
Iwbconnects to the server’s RCON port. The new object becomes the current world (seeget_world()), and its connection becomes the client of the current thread, whichget_client()returns and the builders use.mciwb runandmciwb shellmake one for you and call itworld.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()andplayers, which follow a player in the game with thePlayer,CopyPaste,SignsandMonitorclasses. Callstop()when finished, to stop their monitoring threads.Connecting also turns off the
send_command_feedbackgame rule, so that operators in the game are not told of every RCON command.If the server is the one that
mciwb startruns in its default folder,world_folderis set andbackup()works. That is so when server is"localhost", port is 20100 or thercon.portin~/mciwb-server/server.properties, and~/mciwb-server/worldholds a world.A wrong password raises
rcon.exceptions.WrongPassword.- Parameters:
server (str) -- The address of the server. Defaults to
"localhost", for the server thatmciwb startruns 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 startserver).passwd (str | None) -- The RCON password of the server. Defaults to the
MCIWB_PASSWORDenvironment variable, or todefault_passif that is not set, as themciwbcommands 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
CopyPasteof the default player (frozen interactive feature). None until a player is added. When there is one,save()andload()default to its copy buffer.
- signs: Signs#
The
Signsof 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()andrender()read blocks from its files, which is much faster than over RCON. It is set for the server ofmciwb startwhen 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 shellit also shows the full traceback of an error, in place of a one line report. Seeinit_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 startruns in its default folder (see the class description). For any other server it logs the warning “no backup available” and does nothing: useBackupwith the server’s own folders.
- connect()[source]#
Connect to the Minecraft server and make this the current thread’s client.
This is called when the
Iwbis made. Call it again if the connection is lost, for example after the server restarts. It also turns off thesend_command_feedbackgame rule. A wrong password raisesrcon.exceptions.WrongPassword.- Returns:
The new RCON client, which
get_client()now returns in this thread.- Raises:
ConnectionRefusedError -- If nothing is listening on the port.
OSError -- For other network failures.
- Return type:
- 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
Playerfor that name.- Raises:
KeyError -- If no player of that name has been added.
- Return type:
- property player: Player#
The default
Player(frozen interactive feature).There is none until
add_player()is called, whichmciwb runandmciwb shelldo when given--player. Checkplayersto 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
Monitorthread that watches for the action signs that the player places (seeSigns), and gives the player a set of those signs.The default player is then available as
world.player, with itsworld.copierandworld.signs. Every added player is available by name fromget_player(), and the names are inplayers.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:
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 runandmciwb shellcall it for you. It stops everyMonitor, 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
facingstate such as stairs and doors: one of the horizontalDirectionvalues, for exampleDirection.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:
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:
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 ofItemnames. If the filename ends in.schemit is saved as a Sponge schematic instead, with the block states of stairs, slabs and logs (seefrom_world()), which other Minecraft tools such as WorldEdit can load.The file can be loaded into a world with
load().- Parameters:
- 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 ofItemnames, and placed withBlocks. If the filename ends in.schemthey are loaded from a Sponge schematic instead (seeSchematic).If a player has been added, the copy buffer is then set to the region that was loaded.
- Parameters:
- 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_folderis set (after asking the server to save its changes), otherwise over RCON one block at a time. Seemciwb.render.scan().- Parameters:
- 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:
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 withmciwb.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:
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, sogamerule doDaylightCycleis an error: usegamerule advance_time. Andtime query daytimeis an error too: usetime query dayfor the ticks into the current day, andtime query day repetitionfor 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,tpto a fixed place,gamerule ..., but notgiveorsummon).- 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+". Seeretry_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:
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 inmciwb shell, this is theworldthat 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:
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:
ClientAn RCON client for Minecraft Java Edition that copes with the server’s other RCON clients.
This is
mcipc.rcon.je.client.Clientwith 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:Iwbconnects the first client, andget_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
setblockandfill(except indestroymode) andloot(as used byget_block()) are checked, the command is sent again if the reply is lost, and only the command’s own output is returned. Other commands, includingclone, are sent once: useretry_command(), or the expect argument ofcmd(), 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 commandorIncorrect argument for command, the matching exception frommcipc.rcon.exceptionsis raised (UnknownCommand,InvalidArgumentand so on, all of them aCommandError). Any other error message is returned as the reply.- Parameters:
- Returns:
The server’s reply, or just the command’s own output for the commands whose replies are checked.
- Return type:
- 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:
- Returns:
The server’s reply, or just the command’s own output for the commands whose replies are checked.
- Return type:
- mciwb.get_client()[source]#
Get the RCON client of the current thread.
Every thread needs its own RCON connection. The thread that creates an
Iwbgets one from it, and threads created withnew_thread()(asMonitordoes) 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:
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
Iwbornew_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.
Monitorstarts its threads with this function: usestop_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:
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
setblockortpto a fixed place, but notgiveorsummon: 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:
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
ReplyCheckforretry_command(): given a reply, it returns the first text in it that matches pattern, or None if nothing matches.- Return type:
>>> 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().
- 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:
Logging#
- mciwb.logging.init_logging(debug)[source]#
Set up the mciwb log, which writes to stderr.
mciwb runandmciwb shellcall this for you (with debug set by their--debugoption). A script that is run with plainpythoncalls 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, asdebug()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"