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 endAn 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
saycommand is used. Therefore it is usually preferred to usetellrawinstead.
bedrock.context#
- class bedrock.context.Context(server: Server)[source]#
Context passed to event handlers.
Method generated by attrs for class Context.
- Parameters:
server (Server) –
- class bedrock.context.GameContext(server: Server, data: Mapping[str, Any])[source]#
Context passed to game event handlers.
Method generated by attrs for class GameContext.
- class bedrock.context.BlockBrokenContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class BlockBrokenContext.
- class bedrock.context.BlockPlacedContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class BlockPlacedContext.
- property player_position: WorldCoordinates#
- class bedrock.context.EndOfDayContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class EndOfDayContext.
- property player_position: WorldCoordinates#
- class bedrock.context.PlayerMessageContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class PlayerMessageContext.
- property receiver: str | None#
The receiver of the message.
Note
This may be
Noneif there was no specific receiver.
- class bedrock.context.PlayerTransformContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class PlayerTransformContext.
- property player_position: WorldCoordinates#
- class bedrock.context.PlayerTravelledContext(server: Server, data: Mapping[str, Any])[source]#
Method generated by attrs for class PlayerTravelledContext.
- property player_position: WorldCoordinates#
- class bedrock.context.ServerContext(server: Server)[source]#
Context passed to server event handlers.
Method generated by attrs for class Context.
- Parameters:
server (Server) –
- bedrock.context.get_game_context(name: str) type[bedrock.context.GameContext][source]#
- Parameters:
name (str) –
- Return type:
- class bedrock.context.ReadyContext(server: Server, host: str, port: int)[source]#
Method generated by attrs for class ReadyContext.
bedrock.events#
- class bedrock.events.Event(name: str, handler: Callable[[ContextType], Coroutine])[source]#
Method generated by attrs for class Event.
- class bedrock.events.GameEvent(name: str, handler: Callable[[ContextType], Coroutine])[source]#
Method generated by attrs for class GameEvent.
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:
identifier (UUID) –
response (Future[CommandResponse]) –
- 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.
- classmethod parse(data: Mapping[str, Any]) CommandResponse[source]#
Parses a JSON object sent by the client.
- Parameters:
- Return type:
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
- 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.GameContextof the event.Examples
... @app.server_event async def player_message(ctx): ctx.reply("Hello World!")
- is_ready() bool[source]#
Returns
Truewhen the server is ready to establish a connection.- Return type:
- 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:
- 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.ServerContextof the event.Examples
... @app.server_event async def ready(ctx): print(f"Ready @ {ctx.host}:{ctx.port}")
- 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()orgame_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:
- 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:
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) –
- classmethod from_string(value: str) LocalCoordinate[source]#
Parses a local coordinate.
- Parameters:
value (str) – The coordinate to parse.
- Return type:
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.
- classmethod from_string(value: str) WorldCoordinate[source]#
Parses a world coordinate.
- Parameters:
value (str) – The coordinate to parse.
- Return type:
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))
- 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 inTrueas well.- Return type:
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:
- 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
floatis for usage within game commands such asteleportwhere an integer coordinate like42is parsed as42.50whereas floating points are interpreted as is so that21.0means21.0. You may override this behaviour by overriding this function which affects the parsing ofWorldCoordinate.from_string()andLocalCoordinate.from_string():from bedrock import utils utils.numeric = 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:
- 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,/titlerawetc.- 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:
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]}]}'