API Reference#

Note

The API documented here is for version 1.0.0. You can select a different version at the bottom of the sidebar.

bedrock.consts#

bedrock.consts.GAME_EVENTS = ['additional_content_loaded', 'agent_command', 'agent_created', 'api_init', 'app_paused', 'app_resumed', 'app_suspended', 'award_achievement', 'block_broken', 'block_placed', 'board_text_updated', 'boss_killed', 'camera_used', 'cauldron_used', 'configuration_changed', 'connection_failed', 'crafting_session_completed', 'end_of_day', 'entity_spawned', 'file_transmission_cancelled', 'file_transmission_completed', 'file_transmission_started', 'first_time_client_open', 'focus_gained', 'focus_lost', 'game_session_complete', 'game_session_start', 'hardware_info', 'has_new_content', 'item_acquired', 'item_crafted', 'item_destroyed', 'item_dropped', 'item_enchanted', 'item_smelted', 'item_used', 'join_canceled', 'jukebox_used', 'license_census', 'mascot_created', 'menu_shown', 'mob_interacted', 'mob_killed', 'multiplayer_connection_state_changed', 'multiplayer_round_end', 'multiplayer_round_start', 'npc_properties_updated', 'options_updated', 'performance_metrics', 'player_bounced', 'player_died', 'player_join', 'player_leave', 'player_message', 'player_teleported', 'player_transform', 'player_travelled', 'portal_built', 'portal_used', 'portfolio_exported', 'potion_brewed', 'purchase_attempt', 'purchase_resolved', 'regional_popup', 'responded_to_accept_content', 'screen_changed', 'screen_heartbeat', 'sign_in_to_edu', 'sign_in_to_xbox_live', 'sign_out_of_xbox_live', 'special_mob_built', 'start_client', 'start_world', 'text_to_speech_toggled', 'ugc_download_completed', 'ugc_download_started', 'upload_skin', 'vehicle_exited', 'world_exported', 'world_files_listed', 'world_generated', 'world_loaded', 'world_unloaded']#

A list of game events the server can subcribe to.

Note

Some of these events may not work or are useless in a way.

bedrock.consts.MAX_COMMAND_PROCESSING = 100#

The amount of commands the client can process at a time without responding.

This is already handleded internally so there is usually no need to use this. You can think of the client managing a FIFO queue of command requests with a capacity of 100. The client pops out the first entered command request and sends a command response bback to the server. When the server tries to send a command request while the queue is already full, then the command will never be executed and an error will be sent by the client.

%%{init: {'theme': 'dark'}}%% sequenceDiagram Server-)Client: Command Request Server-)Client: Command Request Server-)Client: Command Request Client-)Server: Command Response loop 98 times Server-)Client: Command Request end Server-xClient: Command Request loop 98 times Client-)Server: Command Response end

An example of an interaction between the server and a client.#

bedrock.consts.MINECRAFT_VERSION = '1.19.70'#

The Minecraft version to use for the command syntax. This usually has no big impact.

bedrock.consts.NAME = 'External'#

The name of the server displayed in the game.

This name is displayed left to the message when the say command is used. Therefore it is usually preferred to use tellraw instead.

bedrock.context#

class bedrock.context.Context(server: Server)[source]#

Context passed to event handlers.

Method generated by attrs for class Context.

Parameters:

server (Server) –

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.GameContext(server: Server, data: Mapping[str, Any])[source]#

Context passed to game event handlers.

Method generated by attrs for class GameContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.BlockBrokenContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class BlockBrokenContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property id: str#
property namespace: str#
property count: int#
property destruction_method: int#
property player: str#
property tool: str | None#
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.BlockPlacedContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class BlockPlacedContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property id: str#
property namespace: str#
property count: int#
property player: str#
property player_position: WorldCoordinates#
property tool: str | None#
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.EndOfDayContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class EndOfDayContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property player_position: WorldCoordinates#
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.PlayerMessageContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class PlayerMessageContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property message: str#

The message.

property receiver: str | None#

The receiver of the message.

Note

This may be None if there was no specific receiver.

property sender: str#

The sender of the message.

property type: str#

The type of the message.

async reply(message: str, *, raw: bool = False, wait: Literal[False]) None[source]#
async reply(message: str, *, raw: bool = False, wait: Literal[True] = True) CommandResponse
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.PlayerTransformContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class PlayerTransformContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property player: str#
property player_position: WorldCoordinates#
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.PlayerTravelledContext(server: Server, data: Mapping[str, Any])[source]#

Method generated by attrs for class PlayerTravelledContext.

Parameters:
  • server (Server) –

  • data (Mapping[str, Any]) –

property underwater: bool#
property meters: float#
property player: str#
property player_position: WorldCoordinates#
property travel_method: int#
property data: Mapping[str, Any]#

A reference to the raw data of the event received.

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.ServerContext(server: Server)[source]#

Context passed to server event handlers.

Method generated by attrs for class Context.

Parameters:

server (Server) –

property server: Server#

A reference to the server object this context belongs to.

bedrock.context.get_game_context(name: str) type[bedrock.context.GameContext][source]#
Parameters:

name (str) –

Return type:

type[bedrock.context.GameContext]

class bedrock.context.ReadyContext(server: Server, host: str, port: int)[source]#

Method generated by attrs for class ReadyContext.

Parameters:
property host: str#
property port: int#
property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.ConnectContext(server: Server)[source]#

Method generated by attrs for class ConnectContext.

Parameters:

server (Server) –

property server: Server#

A reference to the server object this context belongs to.

class bedrock.context.DisconnectContext(server: Server)[source]#

Method generated by attrs for class DisconnectContext.

Parameters:

server (Server) –

property server: Server#

A reference to the server object this context belongs to.

bedrock.events#

class bedrock.events.Event(name: str, handler: Callable[[ContextType], Coroutine])[source]#

Method generated by attrs for class Event.

Parameters:
name: str#
handler: Callable[[ContextType], Coroutine]#
async __call__(ctx: Context, /) None[source]#

Call self as a function.

Parameters:

ctx (Context) –

Return type:

None

class bedrock.events.GameEvent(name: str, handler: Callable[[ContextType], Coroutine])[source]#

Method generated by attrs for class GameEvent.

Parameters:
async __call__(ctx: Context, /) None#

Call self as a function.

Parameters:

ctx (Context) –

Return type:

None

handler: Callable[[ContextType], Coroutine]#
name: str#
class bedrock.events.ServerEvent(name: str, handler: Callable[[ContextType], Coroutine])[source]#

Method generated by attrs for class ServerEvent.

Parameters:
async __call__(ctx: Context, /) None#

Call self as a function.

Parameters:

ctx (Context) –

Return type:

None

handler: Callable[[ContextType], Coroutine]#
name: str#

bedrock.request#

class bedrock.request.CommandRequest(identifier: UUID, data: Mapping[str, Any], response: Future[CommandResponse])[source]#

A command request sent to the server.

Method generated by attrs for class CommandRequest.

Parameters:
property data: Mapping[str, Any]#

The data of the request.

property identifier: UUID#

The unique id of the request.

property response: Future[CommandResponse]#

The response of the response wrapped inside a asyncio.Future.

bedrock.response#

class bedrock.response.CommandResponse(message: str, status: int)[source]#

A response sent by the client.

Method generated by attrs for class CommandResponse.

Parameters:
  • message (str) –

  • status (int) –

property message: str#

The message of the response.

property ok: bool#

Returns True when the command has been executed successfully.

classmethod parse(data: Mapping[str, Any]) CommandResponse[source]#

Parses a JSON object sent by the client.

Parameters:

data (Mapping[str, Any]) –

Return type:

CommandResponse

raise_for_status() None[source]#

Raises bedrock.exceptions.CommandRequestError if the command did not run successfully. Otherwise this method returns None.

Return type:

None

property status: int#

The status of the response.

bedrock.server#

class bedrock.server.Server[source]#

A server handles the connection to a client in the game.

Method generated by attrs for class Server.

add_game_event(event: GameEvent) None[source]#

Adds a game event to the game event handlers.

Parameters:

event (GameEvent) –

Return type:

None

add_server_event(event: ServerEvent) None[source]#

Adds a server event to the game event handlers.

Parameters:

event (ServerEvent) –

Return type:

None

close() None[source]#

Closes the server.

Return type:

None

game_event(fn: Callable[[ContextType], Coroutine], /) GameEvent[source]#

Convenient way of adding a game event.

The decorated function name must match the name of the event to listen to. It takes one positional argument which is an instance of context.GameContext of the event.

Examples

...
@app.server_event
async def player_message(ctx):
    ctx.reply("Hello World!")
Parameters:

fn (Callable[[ContextType], Coroutine]) – The decorated function.

Returns:

The function turned into a events.GameEvent.

Return type:

events.GameEvent

is_connected() bool[source]#

Returns True when the server is connected to a client.

Return type:

bool

is_ready() bool[source]#

Returns True when the server is ready to establish a connection.

Return type:

bool

remove_game_event(event: GameEvent) None[source]#

Removes a game event from the game event handlers.

Raises:

ValueError – Event is not registered.

Parameters:

event (GameEvent) –

Return type:

None

remove_server_event(event: ServerEvent) None[source]#

Removes a server event from the game event handlers.

Raises:

ValueError – Event is not registered.

Parameters:

event (ServerEvent) –

Return type:

None

async run(command: str, *, version: str | list[str] | None = None, wait: Literal[True] = True) CommandResponse[source]#
async run(command: str, *, version: str | list[str] | None = None, wait: Literal[False]) None

Executes a Minecraft command.

Note

The leading slash (/) may be omitted.

Parameters:
  • command – The command to execute. For example setblock 10 10 10 stone.

  • version – The Minecraft version the command syntax relies on. This can usually be ignored.

  • wait – Waits for a response when awaiting.

async send(header: dict[str, Any], body: dict[str, Any], *, wait: Literal[True] = True) CommandResponse[source]#
async send(header: dict[str, Any], body: dict[str, Any], *, wait: Literal[False]) None

Sends data to the client.

Parameters:
  • header – The header data for the request.

  • body – The body data for the request.

  • wait – Waits for a response when awaiting.

Returns:

The response of the request wrapped in a asyncio.Future.

Return type:

CommandResponse

server_event(fn: Callable[[ContextType], Coroutine], /) ServerEvent[source]#

Convenient way of adding a server event.

The decorated function name must match the name of the event to listen to. It takes one positional argument which is an instance of context.ServerContext of the event.

Examples

...
@app.server_event
async def ready(ctx):
    print(f"Ready @ {ctx.host}:{ctx.port}")
Parameters:

fn (Callable[[ContextType], Coroutine]) – The decorated function.

Returns:

The function turned into a events.ServerEvent.

Return type:

events.ServerEvent

start(host: str, port: int) None[source]#

Starts the server.

Parameters:
  • host (str) – The host to run the server on.

  • port (int) – The port to run the server on.

Return type:

None

async subscribe(event_name: str) CommandResponse[source]#

Subscribes to a game event.

Game events are automatically subscribed to when a listener is added with add_game_event() or game_event() so there is usually no need to manually use this method.

Parameters:

event_name (str) – The name of the game event to subscribe to.

Return type:

CommandResponse

async unsubscribe(event_name: str) CommandResponse[source]#

Unsubscribes to a game event.

Parameters:

event_name (str) – The name of the game event to unsubcribe.

Return type:

CommandResponse

bedrock.utils#

class bedrock.utils.LocalCoordinate(coord: float)[source]#

A class representing a local coordinate.

Method generated by attrs for class LocalCoordinate.

Parameters:

coord (float) –

coord: float#
classmethod from_string(value: str) LocalCoordinate[source]#

Parses a local coordinate.

Parameters:

value (str) – The coordinate to parse.

Return type:

LocalCoordinate

Examples

from bedrock.utils import LocalCoordinate, LocalCoordinates

x = LocalCoordinate.from_string("^1")
y = LocalCoordinate.from_string("^-19.5752")
z = LocalCoordinate.from_string("^0")

goto = LocalCoordinates((x, y, z))
class bedrock.utils.TargetSelector(value)[source]#

A collection of target selectors that can be used within commands.

ALL_AGENTS = '@v'#
ALL_ENTITIES = '@e'#
ALL_PLAYERS = '@a'#
INITIATOR = '@initiator'#
NEAREST_PLAYER = '@p'#
PLAYER_AGENT = '@c'#
RANDOM_PLAYER = '@r'#
SELF = '@s'#
class bedrock.utils.WorldCoordinate(coord: float, is_relative: bool = False)[source]#

A class representing a world coordinate.

Method generated by attrs for class WorldCoordinate.

Parameters:
coord: float#
classmethod from_string(value: str) WorldCoordinate[source]#

Parses a world coordinate.

Parameters:

value (str) – The coordinate to parse.

Return type:

WorldCoordinate

Examples

from bedrock.utils import WorldCoordinate, WorldCoordinates

x = WorldCoordinate.from_string("17")
y = WorldCoordinate.from_string("~27")
z = WorldCoordinate.from_string("~-27.4928")

goto = WorldCoordinates((x, y, z))
is_relative: bool#
bedrock.utils.boolean(value: str) bool[source]#

Converts a string into a boolean.

Parameters:

value (str) –

The string to convert into a boolean.

  • 'y'/'yes'/'true'True

  • 'n'/'no'/'false'False

Note

The string is converted into lower case before comparing. That means that 'TRUe' results in True as well.

Return type:

bool

Examples

>>> from bedrock.utils import boolean
>>> boolean("y")
True
>>> boolean("yes")
True
>>> boolean("true")
True
>>> boolean("trUE")
True
>>> boolean("1")
Traceback (most recent call last):
  File "<stdin>", line 1 in <module>
ValueError: cannot turn '1' into a boolean
>>> boolean("n")
False
>>> boolean("NO")
False
>>> boolean("False")
False
>>>
Raises:

ValueError – The string cannot be converted into a boolean.

Parameters:

value (str) –

Return type:

bool

bedrock.utils.numeric(value: str) float[source]#

Converts a string into an integer or if that fails into a floating point.

The major reason to use this instead of float is for usage within game commands such as teleport where an integer coordinate like 42 is parsed as 42.50 whereas floating points are interpreted as is so that 21.0 means 21.0. You may override this behaviour by overriding this function which affects the parsing of WorldCoordinate.from_string() and LocalCoordinate.from_string():

from bedrock import utils
utils.numeric = float
Parameters:

value (str) – The string to converr into a numeric.

Return type:

float

Examples

>>> from bedrock.utils import numeric
>>> numeric("10")
10
>>> numeric("10.500")
10.5
>>>
Raises:

ValueError – The string cannot be converted into a boolean.

Parameters:

value (str) –

Return type:

float

bedrock.utils.rawtext(text: str | Iterable[Mapping[Literal['text', 'selector', 'translate'], str] | Mapping[Literal['score'], Mapping[Literal['name', 'objective'], str]]]) str[source]#

Wraps text inside a rawtext JSON object which can be used for /tellraw, /titleraw etc.

Parameters:

text (str | Iterable[Mapping[Literal['text', 'selector', 'translate'], str] | ~collections.abc.Mapping[~typing.Literal['score'], ~collections.abc.Mapping[~typing.Literal['name', 'objective'], str]]]) – Either just a string or an iterable of mappings beeing valid rawtext parts.

Return type:

str

Examples

>>> from bedrock.utils import rawtext
>>> rawtext('Hello World')
'{"rawtext": [{"text": "Hello World"}]}'
>>> rawtext([{'text': 'Hello '}, {'selector': '@p[r=10]'}])
'{"rawtext": [{"text": "Hello "}, {"selectors": "@p[r=10]}]}'