Minecraft Tools

RText

API package path: mcdreforged.api.rtext

Advanced text component library for Minecraft

Credit: Pandaria98 ‘s stext API library

Text Styles

class mcdreforged.minecraft.rtext.style.RItem[source]

A general Minecraft text style item

abstract property name: str

Its value in Minecraft text component

class mcdreforged.minecraft.rtext.style.RItemClassic(name: str, mc_code: str, console_code: str)[source]

Bases: RItem, ABC

A type of RItem that can be represented with a classic “§”-prefixed formatting code, or a “\033[31m” styled console ANSI escape code

See also

Minecraft Wiki Formatting codes page

property mc_code: str

Its code in Minecraft, with “§” prefix

property console_code: str

Its code in console, i.e. ANSI escape code

It might be an empty str if there’s no appropriate code

class mcdreforged.minecraft.rtext.style.RColor(rgb_code: int)[source]

Minecraft text colors

black: ClassVar[RColorClassic] = RColorClassic(name='black', mc_code='§0', console_code='\x1b[30m')
dark_blue: ClassVar[RColorClassic] = RColorClassic(name='dark_blue', mc_code='§1', console_code='\x1b[34m')
dark_green: ClassVar[RColorClassic] = RColorClassic(name='dark_green', mc_code='§2', console_code='\x1b[32m')
dark_aqua: ClassVar[RColorClassic] = RColorClassic(name='dark_aqua', mc_code='§3', console_code='\x1b[36m')
dark_red: ClassVar[RColorClassic] = RColorClassic(name='dark_red', mc_code='§4', console_code='\x1b[31m')
dark_purple: ClassVar[RColorClassic] = RColorClassic(name='dark_purple', mc_code='§5', console_code='\x1b[35m')
gold: ClassVar[RColorClassic] = RColorClassic(name='gold', mc_code='§6', console_code='\x1b[33m')
gray: ClassVar[RColorClassic] = RColorClassic(name='gray', mc_code='§7', console_code='\x1b[37m\x1b[2m')
dark_gray: ClassVar[RColorClassic] = RColorClassic(name='dark_gray', mc_code='§8', console_code='\x1b[37m\x1b[2m')
blue: ClassVar[RColorClassic] = RColorClassic(name='blue', mc_code='§9', console_code='\x1b[94m')
green: ClassVar[RColorClassic] = RColorClassic(name='green', mc_code='§a', console_code='\x1b[92m')
aqua: ClassVar[RColorClassic] = RColorClassic(name='aqua', mc_code='§b', console_code='\x1b[96m')
red: ClassVar[RColorClassic] = RColorClassic(name='red', mc_code='§c', console_code='\x1b[91m')
light_purple: ClassVar[RColorClassic] = RColorClassic(name='light_purple', mc_code='§d', console_code='\x1b[95m')
yellow: ClassVar[RColorClassic] = RColorClassic(name='yellow', mc_code='§e', console_code='\x1b[93m')
white: ClassVar[RColorClassic] = RColorClassic(name='white', mc_code='§f', console_code='\x1b[37m')
reset: ClassVar[RColorClassic] = RColorClassic(name='reset', mc_code='§r', console_code='\x1b[0m')
classmethod from_mc_value(value: str) RColor[source]

A factory function to create a RColor object from a valid Minecraft color value

Parameters:

value – The value of the color field in Minecraft text component. e.g. "red", "blue", "#00AAFF"

Returns:

A corresponding RColor object

Raises:

ValueError – If the given value is not a valid Minecraft color

property r: int

The red portion of the color in [0, 255]

property g: int

The green portion of the color in [0, 255]

property b: int

The blue portion of the color in [0, 255]

class mcdreforged.minecraft.rtext.style.RColorClassic(name: str, rgb_code: int, mc_code: str, console_code: str)[source]

Bases: RItemClassic, RColor

Classic Minecraft text color defined with color name

Attention

Do not construct the class yourself. Use class fields in RColor if you want to use classic colors

to_rgb() RColorRGB[source]

Converts to the corresponding RColorRGB object with the exact same color

class mcdreforged.minecraft.rtext.style.RColorRGB(rgb_code: int)[source]

Minecraft text color type in hexadecimal color format, with which you can specify the red / green / blue values of the color precisely

Note

Available in Minecraft 1.16+

__init__(rgb_code: int)[source]
Parameters:

rgb_code – An int in hex 0xRRGGBB format, or a str like "RRGGBB", "0xRRGGBB" or "#RRGGBB"

classmethod from_code(rgb_code: str | int) RColorRGB[source]

A factory function to create a RColorRGB object using a single RGB code

Parameters:

rgb_code – An int in hex 0xRRGGBB format, or a str like "RRGGBB", "0xRRGGBB" or "#RRGGBB"

classmethod from_rgb(red: int, green: int, blue: int) RColorRGB[source]

A factory function to create a RColorRGB object using 3 RGB values

Parameters:
  • red – The red portion of the color

  • green – The green portion of the color

  • blue – The blue portion of the color

to_classic() RColorClassic[source]

Converts to the RColorClassic object with the closest Euclidean distance in the RGB color space

class mcdreforged.minecraft.rtext.style.RStyle[source]

Minecraft text styles

bold: ClassVar[RStyleClassic] = RStyleClassic(name='bold', mc_code='§l', console_code='\x1b[1m')
italic: ClassVar[RStyleClassic] = RStyleClassic(name='italic', mc_code='§o', console_code='')
underlined: ClassVar[RStyleClassic] = RStyleClassic(name='underlined', mc_code='§n', console_code='')
strikethrough: ClassVar[RStyleClassic] = RStyleClassic(name='strikethrough', mc_code='§m', console_code='')
obfuscated: ClassVar[RStyleClassic] = RStyleClassic(name='obfuscated', mc_code='§k', console_code='')
class mcdreforged.minecraft.rtext.style.RStyleClassic(name: str, mc_code: str, console_code: str)[source]

Bases: RItemClassic, RStyle

Classic Minecraft text style with corresponding “§”-prefixed formatting code

Text Click Events

class mcdreforged.minecraft.rtext.click_event.RClickAction[source]

Minecraft text click event actions

Added in version v2.15.0.

Note

For versions before v2.15.0, use RAction instead. You can stick to RAction for maximum compatibility

suggest_command: ClassVar[RClickAction[RClickSuggestCommand]] = _RClickActionImpl(action='suggest_command', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickSuggestCommand'>)

Fill the chat bar with given text

run_command: ClassVar[RClickAction[RClickRunCommand]] = _RClickActionImpl(action='run_command', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickRunCommand'>)

Run the given text as command

(Minecraft <1.19.1) If the given text doesn’t start with "/", the given text will be considered as a chat message and sent to the server, so it can be used to automatically execute MCDR command after the player click the decorated text

Attention

In vanilla Minecraft >=1.19.1, only strings starting with "/", i.e. command strings, can be used as the text value of run_command action

For other strings that don’t start with "/", the client will reject to send the chat message

See Issue #203

open_url: ClassVar[RClickAction[RClickOpenUrl]] = _RClickActionImpl(action='open_url', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickOpenUrl'>)

Open given url

open_file: ClassVar[RClickAction[RClickOpenFile]] = _RClickActionImpl(action='open_file', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickOpenFile'>)

Open file from given path

Note

Actually vanilla Minecraft doesn’t allow texts sent by command contain open_file actions, so don’t be surprised if this open_file doesn’t work

copy_to_clipboard: ClassVar[RClickAction[RClickCopyToClipboard]] = _RClickActionImpl(action='copy_to_clipboard', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickCopyToClipboard'>)

Copy given text to clipboard

Note

Available in Minecraft 1.15+

change_page: ClassVar[RClickAction[RClickChangePage]] = _RClickActionImpl(action='change_page', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickChangePage'>)

Change to the specified page of the current book

Note

Only work in written books

show_dialog: ClassVar[RClickAction[RClickShowDialog]] = _RClickActionImpl(action='show_dialog', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickShowDialog'>)

Open specified dialog

Note

Available in Minecraft 1.21.6+

Added in version v2.15.0.

custom: ClassVar[RClickAction[RClickCustom]] = _RClickActionImpl(action='custom', class=<class 'mcdreforged.minecraft.rtext.click_event.RClickCustom'>)

Send a custom event to the server, which has no effect in vanilla servers

Note

Available in Minecraft 1.21.6+

Added in version v2.15.0.

mcdreforged.minecraft.rtext.click_event.RAction

Alias of RClickAction

Added in version v1.0.0.

class mcdreforged.minecraft.rtext.click_event.RClickEvent[source]

An abstract base class of Minecraft click event component

Added in version v2.15.0.

abstract property action: RClickAction

Return the click action type of this component

final to_json_object(json_format: RTextJsonFormat) dict[source]

Serialize itself into a json dict

Parameters:

json_format – The target json format

final classmethod from_json_object(click_event: dict, json_format: RTextJsonFormat) RClickEvent[source]

Deserialize a json dict to a click event component

Parameters:
  • click_event – The json dict to deserialize from

  • json_format – The json format of the provided data

class mcdreforged.minecraft.rtext.click_event.RClickEventSingleValue[source]

An abstract base class for those click event components that contain only 1 value

Added in version v2.15.0.

class mcdreforged.minecraft.rtext.click_event.RClickSuggestCommand(command: str)[source]

The click event component for RClickAction.suggest_command action

Added in version v2.15.0.

command: str

The command to suggest

class mcdreforged.minecraft.rtext.click_event.RClickRunCommand(command: str)[source]

The click event component for RClickAction.run_command action

Added in version v2.15.0.

command: str

The command to run

class mcdreforged.minecraft.rtext.click_event.RClickOpenUrl(url: str)[source]

The click event component for RClickAction.open_url action

Added in version v2.15.0.

url: str

The url to open

class mcdreforged.minecraft.rtext.click_event.RClickOpenFile(path: str)[source]

The click event component for RClickAction.open_file action

Added in version v2.15.0.

path: str

The file path to open

class mcdreforged.minecraft.rtext.click_event.RClickCopyToClipboard(value: str)[source]

The click event component for RClickAction.copy_to_clipboard action

Added in version v2.15.0.

value: str

The content to copy to clipboard

class mcdreforged.minecraft.rtext.click_event.RClickShowDialog(dialog: str | dict)[source]

The click event component for RClickAction.show_dialog action

Note

Available in Minecraft 1.21.6+

Added in version v2.15.0.

dialog: str | dict

The data of the dialog. It can be either:

  1. A dialog identifier, e.g., minecraft:server_links

  2. A full dialog description NBT tag

class mcdreforged.minecraft.rtext.click_event.RClickChangePage(page: int)[source]

The click event component for RClickAction.change_page action

Added in version v2.15.0.

page: int

The page number to change to

class mcdreforged.minecraft.rtext.click_event.RClickCustom(id: str, payload: str | dict | None = None)[source]

The click event component for RClickAction.custom action

Note

Available in Minecraft 1.21.6+

Added in version v2.15.0.

id: str

The identifier

payload: str | dict | None = None

(Optional) The payload

Text Hover Events

class mcdreforged.minecraft.rtext.hover_event.RHoverAction[source]

Minecraft text hover event actions

Added in version v2.15.0.

show_text: ClassVar[RHoverAction[RHoverText]] = _RHoverActionImpl(action='show_text', class=<class 'mcdreforged.minecraft.rtext.hover_event.RHoverText'>)

Show hover text

show_entity: ClassVar[RHoverAction[RHoverEntity]] = _RHoverActionImpl(action='show_entity', class=<class 'mcdreforged.minecraft.rtext.hover_event.RHoverEntity'>)

Show entity information

show_item: ClassVar[RHoverAction[RHoverItem]] = _RHoverActionImpl(action='show_item', class=<class 'mcdreforged.minecraft.rtext.hover_event.RHoverItem'>)

Show item information

class mcdreforged.minecraft.rtext.hover_event.RHoverEvent[source]

An abstract base class of Minecraft hover event component

Added in version v2.15.0.

abstract property action: RHoverAction

Return the hover action type of this component

final to_json_object(json_format: RTextJsonFormat) dict[source]

Serialize itself into a json dict

Parameters:

json_format – The target json format

final classmethod from_json_object(hover_event: dict, json_format: RTextJsonFormat) RHoverEvent[source]

Deserialize a json dict to a hover event component

Parameters:
  • hover_event – The json dict to deserialize from

  • json_format – The json format of the provided data

class mcdreforged.minecraft.rtext.hover_event.RHoverText(text: RTextBase)[source]

The hover event component for RHoverAction.show_text action

Added in version v2.15.0.

text: RTextBase

The text to be displayed

class mcdreforged.minecraft.rtext.hover_event.RHoverEntity(id: str, uuid: UUID, name: str | RTextBase | None = None)[source]

The hover event component for RHoverAction.show_entity action

Added in version v2.15.0.

id: str

The entity type identifier, e.g. minecraft:creeper

uuid: UUID

The UUID of the entity

name: str | RTextBase | None = None

(Optional) The custom name of the entity

class mcdreforged.minecraft.rtext.hover_event.RHoverItem(id: str, count: int | None = None, components: dict | None = None)[source]

The hover event component for RHoverAction.show_item action

Added in version v2.15.0.

id: str

The item type identifier, e.g. minecraft:stone

count: int | None = None

(Optional) Item count. Although it’s optional, it’s still suggested provide a value (e.g. 1)

components: dict | None = None

(Optional) Extra NBT tag / item components information of the item stack

Text Components

class mcdreforged.minecraft.rtext.text.RTextBase[source]

An abstract base class of Minecraft text component

abstractmethod to_json_object(**kwargs: Unpack[ToJsonKwargs]) dict | list[source]

Return an object representing its data that can be serialized into a json string

to_json_str(**kwargs: Unpack[ToJsonKwargs]) str[source]

Return a json formatted str representing its data

It can be used as the second parameter in Minecraft command /tellraw <target> <message> and more

abstractmethod to_plain_text() str[source]

Return a plain text for console display

Click event and hover event will be ignored

abstractmethod to_colored_text() str[source]

Return a colored text stained with ANSI escape code for console display

Click event and hover event will be ignored

abstractmethod to_legacy_text() str[source]

Return a colored text stained with classic “§”-prefixed Minecraft formatting code

Click event and hover event will be ignored

abstractmethod copy() Self[source]

Return a deep copy version of itself

abstractmethod set_color(color: RColor) Self[source]

Set the color of the text and return the text component itself

abstractmethod set_styles(styles: RStyle | Iterable[RStyle]) Self[source]

Set the styles of the text and return the text component itself

final set_click_event(event: RClickEvent, /) Self[source]
final set_click_event(*, event: RClickEvent) Self
final set_click_event(action: RClickAction[RClickEventSingleValue[_T]], value: _T, /) Self
final set_click_event(*, action: RClickAction[RClickEventSingleValue[_T]], value: _T) Self

Set the click event

You can either directly provide the click event, or provide the action type and the action value separately

text = RText('example')

text.set_click_event(RClickSuggestCommand('/say something'))  # directly
text.set_click_event(event=RClickSuggestCommand('/say something'))  # directly (kwarg)
text.set_click_event(RClickAction.suggest_command, '/say something')  # action + value
text.set_click_event(action=RClickAction.suggest_command, value='/say something')  # action + value (kwarg)

Method c() is the short form of set_click_event()

abstractmethod set_hover_event(hover_event: RHoverEvent) Self[source]

Set the hover event

set_hover_text(*args) Self[source]

Set the hover text

Method h() is the short form of set_hover_text()

Parameters:

args – The elements be used to create a RTextList instance. The RTextList instance is used as the actual hover text

Returns:

The text component itself

c(arg1: RClickEvent | RClickAction[RClickEventSingleValue[_T]] = <unset>, arg2: _T = <unset>, /, *, event: RClickEvent = <unset>, action: RClickAction[RClickEventSingleValue[_T]] = <unset>, value: _T = <unset>) Self

Alias of set_click_event()

h(*args) Self

Alias of set_hover_text()

static from_any(text) RTextBase[source]

Convert anything into a RText component

static join(divider: Any, iterable: Iterable[Any]) RTextBase[source]

Just like method str.join(), it concatenates any number of texts with divider

Example:

>>> text = RTextBase.join(',', [RText('1'), '2', 3])
>>> text.to_plain_text()
'1,2,3'
Parameters:
  • divider – The divider between elements. The divider object will be reused

  • iterable – The elements to be joined

static format(fmt: str, *args, **kwargs) RTextBase[source]

Just like method str.format(), it uses *args and **kwargs to build a formatted RText component based on the formatter fmt

Example:

>>> text = RTextBase.format('a={},b={},c={c}', RText('1', color=RColor.blue), '2', c=3)
>>> text.to_plain_text()
'a=1,b=2,c=3'
Parameters:
  • fmt – The formatter string

  • args – The given arguments

  • kwargs – The given keyword arguments

classmethod from_json_object(data: str | list | dict, **kwargs: Unpack[FromJsonKwargs]) RTextBase[source]

Convert a json object into a RText component

Example:

>>> text = RTextBase.from_json_object({'text': 'my text', 'color': 'red'})
>>> text.to_plain_text()
'my text'
>>> text.to_json_object()['color']
'red'
Parameters:

data – A json object

Added in version v2.4.0.

class mcdreforged.minecraft.rtext.text.RText(text: Any, color: RColor | None = None, styles: RStyle | Iterable[RStyle] | None = None)[source]

Bases: RTextBase

The regular text component class

__init__(text: Any, color: RColor | None = None, styles: RStyle | Iterable[RStyle] | None = None)[source]

Create a RText object with specific text, optional color and optional style

Parameters:
  • text – The content of the text. It will be converted into str

  • color – Optional, the color of the text

  • styles – Optional, the style of the text. It can be a single RStyle or an iterable of RStyle

class mcdreforged.minecraft.rtext.text.RTextList(*args: Any)[source]

Bases: RTextBase

A list of RTextBase objects, a compound text component

__init__(*args: Any)[source]

Use the given *args to create a RTextList

Parameters:

args – The items in this RTextList. They can be str, RTextBase or any class implements __str__ method. All non- RTextBase items will be converted to RText

class mcdreforged.minecraft.rtext.text.RTextTranslation(translation_key: str, color: RColor = RColorClassic(name='reset', mc_code='§r', console_code='\x1b[0m'), styles: RStyle | Iterable[RStyle] | None = None)[source]

Bases: RText

The translation text component class. It’s almost the same as RText

__init__(translation_key: str, color: RColor = RColorClassic(name='reset', mc_code='§r', console_code='\x1b[0m'), styles: RStyle | Iterable[RStyle] | None = None)[source]

Create a RTextTranslation object with specific translation key. The rest of the parameters are the same to the constructor of RText

Use method arg() to set the translation arguments, if the translation requires some arguments

Example:

RTextTranslation('advancements.nether.root.title', color=RColor.red)
Parameters:
  • translation_key – The translation key

  • color – Optional, the color of the text

  • styles – Optional, the style of the text. It can be a single RStyle or a collection of RStyle

arg(*args: Any) Self[source]

Set the translation arguments

Parameters:

args – The translation arguments

fallback(fallback: str) Self[source]

Set the translation fallback

Attention

Works in Minecraft >= 1.19.4 only

Parameters:

fallback – The fallback text if the translation is unknown

class mcdreforged.translation.translation_text.RTextMCDRTranslation(translation_key: str, *args, **kwargs)[source]

Bases: RTextBase

The translation text component used in MCDR

When MCDR is running, it will use the tr() method in ServerInterface class as the translating method, and the language of MCDR as the fallback translation language

Added in version v2.1.0.

__init__(translation_key: str, *args, **kwargs)[source]

Create a RTextMCDRTranslation component with necessary parameters for translation

Parameters:
  • translation_key – The translation key

  • args – The translation arguments

  • kwargs – The translation keyword arguments

classmethod language_context(language: str)[source]

Create a context where all RTextMCDRTranslation will use the given language to translate within

It’s mostly used when you want a translated str or Minecraft json text object corresponding to this component under a specific language

MCDR will automatically apply this context with user’s preferred language right before sending messages to a player or the console

Example:

def log_message_line_by_line(server: ServerInterface):
        with RTextMCDRTranslation.language_context('en_us'):
                text: RTextMCDRTranslation = server.rtr('my_plugin.some_message')
                text_as_str: str = text.to_plain_text()  # The translation operation happens here
                server.logger.info('Lines of my translation')
                for line in text_as_str.splitlines():
                        server.logger.info('- {}'.format(line))
Parameters:

language – The language to be used during translation inside the context

Misc

class mcdreforged.minecraft.rtext.schema.RTextJsonFormat(*values)[source]

Define the serialization format of RText components for different Minecraft versions

V_1_7 = RTextJsonFormatItem(click_event_key='clickEvent', hover_event_key='hoverEvent')

For Minecraft [1.7, 1.21.5)

V_1_21_5 = RTextJsonFormatItem(click_event_key='click_event', hover_event_key='hover_event')

For Minecraft [1.21.5, ~)

Rcon

API package path: mcdreforged.api.rcon

class mcdreforged.minecraft.rcon.rcon_connection.RconConnection(address: str, port: int, password: str, *, logger: Logger | None = None)[source]

A simply rcon client for connect to any Minecraft servers that supports rcon protocol

__init__(address: str, port: int, password: str, *, logger: Logger | None = None)[source]

Create a rcon client instance

Parameters:
  • address – The address of the rcon server

  • port – The port if the rcon server

  • password – The password of the rcon connection

Keyword Arguments:

logger – Optional, an instance of logging.Logger. It’s used to output some warning information like failing to receive a packet

connect() bool[source]

Start a connection to the rcon server and try to log in

Returns:

If connect and login success

disconnect()[source]

Disconnect from the server

send_command(command: str, max_retry_time: int = 3) str | None[source]

Send a command to the rcon server

Parameters:
  • command – The command you want to send to the server

  • max_retry_time – The maximum retry time of the operation

Returns:

The command execution result from the server, or None if max_retry_time retries exceeded