Command Stuffs

API package path: mcdreforged.api.command

Command Source

class mcdreforged.command.command_source.CommandSource[source]

Bases: ABC

CommandSource: is an abstracted command executor model. It provides several methods for command execution

Class inheriting tree:

CommandSource
├── InfoCommandSource
│   ├── PlayerCommandSource
│   └── ConsoleCommandSource
└── PluginCommandSource

Plugins can declare a class inherited from CommandSource to create their own command source

property is_player: TypeGuard[PlayerCommandSource]

If the command source is a player command source

Returns:

True if it’s a player command source, False otherwise

property is_console: TypeGuard[ConsoleCommandSource]

If the command source is a console command source

Returns:

True if it’s a console command source, False otherwise

get_server() ServerInterface[source]

Return the server interface instance

get_permission_level() int[source]

Return the permission level that the command source has

The permission level is represented by int

get_preference() PreferenceItem[source]

Return the preference of the command source

By default, the default preference of MCDR from ServerInterface.get_default_preference() will be returned

Subclasses might override this method to return customized preference. e.g. PlayerCommandSource will return the preference of the corresponding player

New in version v2.1.0.

preferred_language_context()[source]

A quick helper method to use the language value in preference to create a context with RTextMCDRTranslation.language_context()

See also

Class RTextMCDRTranslation

Example usage:

with source.preferred_language_context():
    message = source.get_server().rtr('my_plugin.placeholder').to_plain_text()
    text.set_click_event(RAction.suggest_command, message)

New in version v2.1.0.

has_permission(level: int) bool[source]

A helper method for testing permission requirement

Parameters:

level – The permission level to be tested

Returns:

If the command source has not less permission level than the given permission level

has_permission_higher_than(level: int) bool[source]

Just like the CommandSource.has_permission(), but this time it is a greater than judgment

Parameters:

level – The permission level to be tested

Returns:

If the command source has greater permission level than the given permission level

reply(message: str | RTextBase, **kwargs) None[source]

Send a message to the command source. The message can be anything including RTexts

Parameters:

message – The message you want to send

Keyword Arguments:
  • encoding – The encoding method for the message. It’s only used in PlayerCommandSource

  • console_text – Message override when it’s a ConsoleCommandSource

__eq__(other) bool[source]

New in version v2.12.2: All MCDR builtin command sources have the implemented the __eq__ method

class mcdreforged.command.command_source.InfoCommandSource(mcdr_server: MCDReforgedServer, info: Info)[source]

Bases: CommandSource, ABC

Command source originated from an info created by MCDR

get_info() Info[source]

Return the Info instance that this command source is created from

Command Nodes

class mcdreforged.command.builder.nodes.basic.AbstractNode[source]

Bases: ABC

AbstractNode is base class of all command nodes. It’s also an abstract class. It provides several methods for building up the command tree

then(node: AbstractNode) Self[source]

Attach a child node to its children list, and then return itself

It’s used for building the command tree structure

Parameters:

node – A node instance to be added to current node’s children list

Example:

Literal('!!email'). \
then(Literal('list')). \
then(Literal('remove'). \
    then(Integer('email_id'))
). \
then(Literal('send'). \
    then(Text('player'). \
        then(GreedyText('message'))
    )
)
runs(func: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandContext], Any]) Self[source]

Set the callback function of this node. When the command parsing finished at this node, the callback function will be executed

The callback function is allowed to accept 0 to 2 arguments (a CommandSource as command source and a dict (CommandContext) as context). For example, the following 4 functions are available callbacks:

def callback1():
    pass

def callback2(source: CommandSource):
    pass

def callback3(source: CommandSource, context: dict):
    pass

callback4 = lambda src: src.reply('pong')
node1.runs(callback1)
node2.runs(callback2)
node3.runs(callback3)
node4.runs(callback4)

Both of them can be used as the argument of the runs method

This dynamic callback argument adaptation is used in all callback invoking of the command nodes

Parameters:

func – A callable that accepts up to 2 arguments. Argument list: CommandSource, dict (CommandContext)

requires(requirement: Callable[[], bool] | Callable[[CommandSource], bool] | Callable[[CommandSource, CommandContext], bool], failure_message_getter: Callable[[], str | RTextBase] | Callable[[CommandSource], str | RTextBase] | Callable[[CommandSource, CommandContext], str | RTextBase] | None = None) Self[source]

Set the requirement tester callback of the node. When entering this node, MCDR will invoke the requirement tester to see if the current command source and context match your specific condition.

If the tester callback return True, nothing will happen, MCDR will continue parsing the rest of the command

If the tester callback return False, a RequirementNotMet exception will be risen. At this time if the failure_message_getter parameter is available, MCDR will invoke failure_message_getter to get the message string of the RequirementNotMet exception, otherwise a default message will be used

New in version v2.7.0: Multiple requires() call results in an “and” combination of all given requirements, i.e. the current command context is satisfied iif. all given requirements are satisfied

Parameters:

Example usages:

node1.requires(lambda src: src.has_permission(3))  # Permission check
node2.requires(lambda src, ctx: ctx['page_count'] <= get_max_page())  # Dynamic range check
node3.requires(lambda src, ctx: is_legal(ctx['target']), lambda src, ctx: 'target {} is illegal'.format(ctx['target']))  # Customized failure message
redirects(redirect_node: AbstractNode) Self[source]

Redirect all further child nodes command parsing to another given node

Redirected stuffs:

  • Children node traversal

  • Command callback, if current node doesn’t have a callback

Unredirected stuffs:

  • Command parsing, i.e. parsing the literal / argument value of the node from command

  • Requirement testing

  • Suggestion fetching

Example use cases:

  • You want a short command and full-path command that will all execute the same commands

  • You want to repeatedly re-enter a command node’s children when parsing commands

Pay attention to the difference between redirects() and then(). redirects() is to redirect the child nodes, and then() is to add a child node

Parameters:

redirect_node – A node instance which current node is redirecting to

suggests(suggestion: Callable[[], Iterable[str]] | Callable[[CommandSource], Iterable[str]] | Callable[[CommandSource, CommandContext], Iterable[str]]) Self[source]

Set the provider for command suggestions of this node

Literal node does not support this method

Examples:

Literal('!!whereis'). \
    then(
        Text('player_name').
        suggests(lambda: ['Steve', 'Alex']).
        runs(lambda src, ctx: find_player(src, ctx['player_name']))
    )

When the user input !!whereis in the console and a space character, MCDR will show the suggestions "Steve" and "Alex"

Parameters:

suggestion – A callable function which accepts up to 2 parameters and return an iterable of str indicating the current command suggestions. Argument list: CommandSource, dict (CommandContext)

on_error(error_type: Type[CommandError], handler: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandError], Any] | Callable[[CommandSource, CommandError, CommandContext], Any], *, handled: bool = False) Self[source]

When a command error occurs, the given will invoke the given handler to handle with the error

Parameters:
Keyword Arguments:

handled – If handled is set to True, CommandError.set_handled is called automatically when invoking the handler callback

on_child_error(error_type: Type[CommandError], handler: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandError], Any] | Callable[[CommandSource, CommandError, CommandContext], Any], *, handled: bool = False) Self[source]

Similar to on_error(), but it gets triggered only when the node receives a command error from one of the node’s direct or indirect child

print_tree(line_writer: ~typing.Callable[[str], ~typing.Any] = <built-in function print>)[source]

Print the command tree in a read-able format. Mostly used in debugging

Parameters:

line_writer – A printer function that accepts a str

New in version v2.6.0.

class mcdreforged.command.builder.nodes.basic.Literal(literal: str)[source]

Bases: EntryNode

Literal node is a special node. It doesn’t output any value. It’s more like a command branch carrier

Literal node can accept a str as its literal in its constructor. A literal node accepts the parsing command only when the next element of the parsing command exactly matches the literal of the node

Literal node is the only node that can start a command execution

class mcdreforged.command.builder.nodes.basic.ArgumentNode(name: str)[source]

Bases: AbstractNode, ABC

Argument node is an abstract base class for all nodes which store parsed values

It has a str field name which is used as the key used in storing parsed value in context

class mcdreforged.command.builder.nodes.arguments.NumberNode(name)[source]

Bases: ArgumentNode, ABC

The base class of all number related argument nodes

It’s inherited by Number, Integer and Float. It represents a type of number based node

For a NumberNode instance, you can restrict the range of the parsed number value. If the parsed number is out of range, a NumberOutOfRange exception will be risen

By default, there’s no range restriction

at_min(min_value: int | float) NumberNode[source]

Set the lower boundary of the value range restriction. The boundary is inclusive

Parameters:

min_value – the lower boundary of the range restriction

at_max(max_value: int | float) NumberNode[source]

Set the higher boundary of the value range restriction. The boundary is inclusive

Parameters:

max_value – the higher boundary of the range restriction

in_range(min_value: int | float, max_value: int | float) NumberNode[source]

Set the lower and the higher boundary of the value range restriction at the same time

The valid value range will be [min_value, max_value], i.e. inclusive

See also

at_min(), at_max()

Parameters:
  • min_value – the lower boundary of the range restriction

  • max_value – the higher boundary of the range restriction

class mcdreforged.command.builder.nodes.arguments.Number(name)[source]

Bases: NumberNode

An integer, or a float

If the next element is not a number, a InvalidNumber exception will be risen

class mcdreforged.command.builder.nodes.arguments.Integer(name)[source]

Bases: NumberNode

An integer

If the next element is not an integer, a InvalidInteger exception will be risen

class mcdreforged.command.builder.nodes.arguments.Float(name)[source]

Bases: NumberNode

A float

If the next element is not a float, a InvalidFloat exception will be risen

class mcdreforged.command.builder.nodes.arguments.TextNode(name)[source]

Bases: ArgumentNode, ABC

It’s an abstract class. It’s inherited by Text, QuotableText and GreedyText. It represents a type of text based node

For a TextNode instance, you can restrict the length range of the parsed text. If the length of the parsed text is out of range, a TextLengthOutOfRange exception will be risen

By default, there’s no length range restriction

at_min_length(min_length: int) TextNode[source]

Set the lower boundary of the length range restriction. The boundary is inclusive

Parameters:

min_length – the lower boundary of the length range restriction

at_max_length(max_length: int) TextNode[source]

Set the higher boundary of the length range restriction. The boundary is inclusive

Parameters:

max_length – the higher boundary of the length range restriction

in_length_range(min_length: int, max_length: int) TextNode[source]

Set the lower and the higher boundary of the length range restriction at the same time

The valid length range will be [min_length, max_length], i.e. inclusive

Parameters:
  • min_length – the lower boundary of the length range restriction

  • max_length – the higher boundary of the length range restriction

class mcdreforged.command.builder.nodes.arguments.Text(name)[source]

Bases: TextNode

A text argument with no space character

It will keep reading chars continuously until it meets a space character

class mcdreforged.command.builder.nodes.arguments.QuotableText(name)[source]

Bases: Text

A text argument with support for inputting space characters

It works just like a Text argument node, but it gives user a way to input text with space character: Use two double quotes to enclose the text content

If you use two double quotes to enclose the text content, You can use escape character \ to escape double quotes " and escape character \ itself

For example, here are some texts that are accepted by QuotableText:

  • Something

  • "Something with space characters"

  • "or escapes \ like " this"

class mcdreforged.command.builder.nodes.arguments.GreedyText(name)[source]

Bases: TextNode

A text argument that consumes all remaining input

Its principle is quite simple: It greedily takes out all remaining texts in the commands

It’s not a smart decision to append any child nodes to a GreedyText, since the child nodes can never get any remaining command

class mcdreforged.command.builder.nodes.arguments.Boolean(name: str)[source]

Bases: ArgumentNode

A simple boolean argument, only accepts true and false, and store them as the corresponding bool value. Case is ignored

Raises InvalidBoolean if the input is not accepted

New in version v2.3.0.

class mcdreforged.command.builder.nodes.arguments.Enumeration(name: str, enum_class: Type[Enum])[source]

Bases: ArgumentNode

A node associating with an Enum class for reading an enum value of the given class

An Enum class is required as the parameter to its constructor

Raises InvalidEnumeration if the input argument is not a valid name for the given enum class

Example usage:

class MyColor(Enum):
    red = 'red color'
    blue = 'blue color'
    green = 'green color'

node = Enumeration('arg', MyColor)

New in version v2.3.0.

class mcdreforged.command.builder.nodes.special.CountingLiteral(literal: str, counter_key: str)[source]

Bases: Literal

A special literal node with an extra ability: store how many times it got visited during the command parsing in the command context

New in version v2.12.0.

Command Builder

class mcdreforged.command.builder.tools.SimpleCommandBuilder[source]

A tree-free command builder for easier command building. Declare & Define, that’s all you need

New in version v2.6.0.

exception Error[source]

Custom exception to be thrown in SimpleCommandBuilder

command(command: str) Callable[[CommandCallbackFunc], CommandCallbackFunc][source]
command(command: str, callback: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandContext], Any]) None

Define a command and its callback

A command path string is made up of several elements separated by spaces. These elements are the names of corresponding command node. They describe a path from the root node to the target node in the command tree

If a node has a name surrounding with "<" and ">", it will be considered as an argument node, e.g. "<my_arg>". Otherwise it will be considered as a literal node, e.g. "my_literal"

You need to give definitions of argument nodes with the arg() method. You can also define your custom literal nodes with the literal() method

Examples:

builder.command('!!email list', list_email)
builder.command('!!email remove <email_id>', remove_email)
builder.command('!!email send <player> <message>', send_email)

Alternative, you can use this method as a decorator to decorate the callback function by passing the first argument:

# This syntactic sugar does the same thing as `builder.command('!!email list', list_email)`
@builder.command('!!email list')
def list_email(source: CommandSource, context: CommandContext):
    pass

# You can even chain the decorator. All given commands will use function `foo_bar()` as the callback
@builder.command('!!email foo')
@builder.command('!!email bar')
def foo_bar(source: CommandSource, context: CommandContext):
    pass
Parameters:
  • command – A command path string, e.g. "!!calc add <value_a> <value_b>"

  • callback – The callback function of this command, which will be passed to AbstractNode.then

New in version v2.10.0: It can now be used as a decorator for callback functions

arg(arg_name: str, node_factory: Callable[[str], ArgNodeType]) NodeDefinition[ArgNodeType][source]

Define an argument node for an argument name. All argument names appeared in command() must be defined

Notes that almost all MCDR builtin argument node classes can be constructed with 1 argument name parameter (e.g. Text, Number), so you can just use the name of the argument class here

Examples:

builder.arg('my_arg', QuotableText)
builder.arg('my_arg', lambda name: Integer(name).at_min(0))
Parameters:
  • arg_name – The name of the argument node. It can be quoted with "<>" if you want. Examples: "my_arg", "<my_arg>"

  • node_factory – An argument node constructor, that accepts the argument name as the only parameter and return an ArgumentNode object

Returns:

A NodeDefinition object. With that you can further customize this node definition

literal(literal_name: str, node_factory: Callable[[str], Literal] | None = None) NodeDefinition[Literal][source]

Define a literal node for a literal name. It’s useful when you want to have some custom literal nodes. If you just want a regular literal node, you don’t need to invoke this method, since the builder will use the default Literal constructor for node construction

Parameters:
  • literal_name – The name of the literal node

  • node_factory – A literal node constructor, that accepts the literal name as the only parameter and return a Literal object. Optional

Returns:

A NodeDefinitionImpl object. With that you can further customize this node definition

build(*, use_cache: bool = True) List[AbstractNode][source]

Build the command trees

Nodes with same name will be reused. e.g. if you define 3 commands with path "!!foo", "!!foo bar" and “!!foo baz", the root "!!foo" node will be reused, and there will be only 1 "!!foo" node eventually

Keyword Arguments:

use_cache – If set to false, do not use cache and always build new command trees

Returns:

A list of the built command tree root nodes. The result is cached until you instruct the builder again. You can use clean_cache() to explicitly clean the build cache

Raises:

SimpleCommandBuilder.Error – if there are undefined argument nodes

New in version v2.9.0: Added use_cache keyword argument

clean_cache()[source]

Clean the build cache

See method build()

register(server: PluginServerInterface)[source]

A helper method for lazyman, to build with method build() and register built commands to the MCDR server

Parameters:

server – The PluginServerInterface object of your plugin

Raises:

SimpleCommandBuilder.Error – if build fails, or there are rooted non-literal nodes in the build result

add_children_for(parent_node: AbstractNode)[source]

A helper method for lazyman, to build command trees with method build() and attach all built tree nodes as the children of the given node via then()

Parameters:

parent_node – The command node that will become the parent of the built children nodes

Raises:

SimpleCommandBuilder.Error – if build fails

New in version v2.8.0.

print_tree(line_writer: Callable[[str], Any])[source]

A helper method for lazyman, to build with method build() and print the built command trees

Example:

builder.print_tree(server.logger.info)
Parameters:

line_writer – A printer function that accepts a str

Raises:

SimpleCommandBuilder.Error – if build fails

class mcdreforged.command.builder.tools.NodeDefinition[source]

A node definition class holding extra customization information

post_process(post_processor: Callable[[NodeType], Any]) Self[source]

Add a post-process function to the current node definition

During method SimpleCommandBuilder.build(), after a node is constructed, all the post-process functions will be applied to the node object

requires(requirement: Callable[[], bool] | Callable[[CommandSource], bool] | Callable[[CommandSource, CommandContext], bool], failure_message_getter: Callable[[], str | RTextBase] | Callable[[CommandSource], str | RTextBase] | Callable[[CommandSource, CommandContext], str | RTextBase] | None = None) Self[source]

See AbstractNode.requires()

suggests(suggestion: Callable[[], Iterable[str]] | Callable[[CommandSource], Iterable[str]] | Callable[[CommandSource, CommandContext], Iterable[str]]) Self[source]

See AbstractNode.suggests()

on_error(error_type: Type[CommandError], handler: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandError], Any] | Callable[[CommandSource, CommandError, CommandContext], Any], *, handled: bool = False) Self[source]

See AbstractNode.on_error()

on_child_error(error_type: Type[CommandError], handler: Callable[[], Any] | Callable[[CommandSource], Any] | Callable[[CommandSource, CommandError], Any] | Callable[[CommandSource, CommandError, CommandContext], Any], *, handled: bool = False) Self[source]

See AbstractNode.on_child_error()

Tools

class mcdreforged.command.builder.tools.Requirements[source]

A common callback function factory for command node requirement testing

Example usage:

node.requires(Requirements.has_permission(1))

New in version v2.6.0.

classmethod has_permission(level: int) Callable[[CommandSource], bool][source]

Check if the command source has the given permission level

Parameters:

level – The minimum accepted permission level

classmethod is_player() Callable[[CommandSource], bool][source]

Check if the command source indicates a player

classmethod is_console() Callable[[CommandSource], bool][source]

Check if the command source indicates the console

classmethod argument_exists(arg_name: str) Callable[[CommandSource, dict], bool][source]

Check if the given argument has been assigned in current command context

Parameters:

arg_name – The name of the argument to be checked

Exceptions

exception mcdreforged.command.builder.exception.CommandErrorBase[source]

Bases: Exception, ABC

The base exception class for all command related errors

Class inheriting tree:

CommandErrorBase
├── IllegalNodeOperation
└── CommandError
    ├── UnknownCommand
    ├── UnknownArgument
    ├── RequirementNotMet
    └── CommandSyntaxError
        └── IllegalArgument
            ├── AbstractOutOfRange
            │   ├── NumberOutOfRange
            │   └── TextLengthOutOfRange
            ├── InvalidNumber
            ├── InvalidInteger
            ├── InvalidFloat
            ├── IllegalEscapesUsage
            ├── UnclosedQuotedString
            ├── EmptyText
            ├── InvalidBoolean
            └── InvalidEnumeration
exception mcdreforged.command.builder.exception.IllegalNodeOperation[source]

Bases: CommandErrorBase

The operation is unsupported by this node

exception mcdreforged.command.builder.exception.CommandError(message: str | RTextBase, parsed_command: str, failed_command: str)[source]

Bases: CommandErrorBase, ABC

The basic exception, for errors raised when parsing a command

get_error_data() tuple[source]

Data that might be helpful for error report

It will be used in error message str formatting

get_parsed_command() str[source]
Returns:

A prefix of the input command that has been successfully parsed

get_failed_command() str[source]
Returns:

A prefix of the input command that is parsing when the failure occurs

get_error_segment() str[source]
Returns:

The command segment that causes the error

set_handled() None[source]

When handling the command error by error listener on the command tree node, you can use this method to tell MCDR the command error has been handled so MCDR will not display the default command failure message to the command source like Unknown argument: !!MCDR reload this<--

It won’t make any difference to the command node tree execution, but it might be useful for outer error handlers

exception mcdreforged.command.builder.exception.UnknownCommand(parsed_command, failed_command)[source]

Bases: CommandError

When the command finishes parsing, but current node doesn’t have a command callback function

exception mcdreforged.command.builder.exception.UnknownArgument(parsed_command: str, failed_command: str)[source]

Bases: CommandError

When there’s remaining command string, but there’s no matched children command nodes

exception mcdreforged.command.builder.exception.RequirementNotMet(parsed_command: str, failed_command: str, reason: str | RTextBase | None)[source]

Bases: CommandError

The specified requirement for the command source to enter this node is not met

exception mcdreforged.command.builder.exception.CommandSyntaxError(message: str | RTextBase, char_read: int | str)[source]

Bases: CommandError, ABC

The basic exception for command parsing error

exception mcdreforged.command.builder.exception.IllegalArgument(message: str | RTextBase, char_read: int | str)[source]

Bases: CommandSyntaxError, ABC

The basic exception for argument parsing error, usually caused by wrong argument syntax

exception mcdreforged.command.builder.exception.AbstractOutOfRange(message: str | RTextBase, char_read: int | str, value, range_l, range_r)[source]

Bases: IllegalArgument, ABC

The basic exception for out-of-range like argument parsing error

exception mcdreforged.command.builder.exception.NumberOutOfRange(char_read: int | str, value, range_l, range_r)[source]

Bases: AbstractOutOfRange

The parsed number value is out of the restriction range

exception mcdreforged.command.builder.exception.InvalidNumber(char_read: int | str)[source]

Bases: IllegalArgument

The parsed value is not a valid number

exception mcdreforged.command.builder.exception.InvalidInteger(char_read: int | str)[source]

Bases: IllegalArgument

The parsed value is not a valid integer

exception mcdreforged.command.builder.exception.InvalidFloat(char_read: int | str)[source]

Bases: IllegalArgument

The parsed value is not a valid float

exception mcdreforged.command.builder.exception.TextLengthOutOfRange(char_read: int | str, value, range_l, range_r)[source]

Bases: AbstractOutOfRange

The length of the given text is out of the restriction range

exception mcdreforged.command.builder.exception.IllegalEscapesUsage(char_read: int | str)[source]

Bases: IllegalArgument

The text contains illegal \ usage

exception mcdreforged.command.builder.exception.UnclosedQuotedString(char_read: int | str)[source]

Bases: IllegalArgument

The quote is unclosed

exception mcdreforged.command.builder.exception.EmptyText(char_read: int | str)[source]

Bases: IllegalArgument

The text is empty, which is not allowed

exception mcdreforged.command.builder.exception.InvalidBoolean(char_read: int | str)[source]

Bases: IllegalArgument

The parsed value is not a valid boolean

exception mcdreforged.command.builder.exception.InvalidEnumeration(char_read: int | str)[source]

Bases: IllegalArgument

The parsed value is not a valid Enum

Misc

class mcdreforged.command.builder.common.CommandContext(source: CommandSource, command: str)[source]

Bases: Dict[str, Any]

A CommandContext stores the information of the command parsing process. It’s a class inherited from dict

The most common use case for CommandContext is storing the parsed result from argument nodes. The name of the argument node and the parsed result will be stored as a key-value pair in CommandContext, which means you can use dict method like context['arg_name'] to access these argument values

CommandContext also provides some other useful methods for getting information of the current command context

property source: CommandSource

The command source that triggered the current command parsing

property command: str

The complete command string being parsing

property command_read: str

The already-parsed command

property command_remaining: str

The to-be-parsed command, i.e. the remaining command

property cursor: int

The index of the complete command str, the cursor of the command parsing process

property node_path: List[AbstractNode]

The path from the root node of the command tree to the current command node

mcdreforged.command.builder.command_builder_util.DIVIDER = ' '

The char to divide elements in a command string —— space

mcdreforged.command.builder.command_builder_util.remove_divider_prefix(text: str) str[source]

Remove the element divider prefix of the given text. It’s usually used before taking the next element in the command str

Examples:

>>> remove_divider_prefix('foo bar')
'foo bar'
>>> remove_divider_prefix('  foo bar')
'foo bar'
Parameters:

text – The text for divider prefix removal

mcdreforged.command.builder.command_builder_util.get_element(text: str) str[source]

Get an element from the remaining input

Examples:

>>> get_element('foo bar')
'foo'
>>> get_element('foo   bar')
'foo'
>>> get_element('fooooo')
'fooooo'
>>> get_element(' foo')
''
Parameters:

text – The remaining input to be parsed. It should not start with DIVIDER

mcdreforged.command.builder.command_builder_util.get_int(text: str) Tuple[int | None, int][source]

Get an int from the remaining input

Examples:

>>> get_int('1234 abc')
(1234, 4)
>>> get_int('foo bar')
(None, 3)
>>> get_int(' 1234 abc')
(None, 0)
Parameters:

text – The remaining input to be parsed. It should not start with DIVIDER

Returns:

a tuple of value, char_read. The value will be None if parsing failed

mcdreforged.command.builder.command_builder_util.get_float(text: str) Tuple[float | None, int][source]

Get a float from the remaining input

Examples:

>>> get_float('123.4 abc')
(123.4, 5)
>>> get_float('foo bar')
(None, 3)
>>> get_int(' 123.4 abc')
(None, 0)
Parameters:

text – The remaining input to be parsed. It should not start with DIVIDER

Returns:

a tuple of value, char_read. The value will be None if parsing failed