Command Stuffs
API package path: mcdreforged.api.command
Command Source
- class mcdreforged.command.command_source.CommandSource[source]
Bases:
ABCCommandSource: is an abstracted command executor model. It provides several methods for command executionClass inheriting tree:
CommandSource ├── InfoCommandSource │ ├── PlayerCommandSource │ └── ConsoleCommandSource └── PluginCommandSource
Plugins can declare a class inherited from
CommandSourceto create their own command source- property is_player: bool
If the command source is a player command source
- Returns:
Trueif it’s a player command source,Falseotherwise
- property is_console: bool
If the command source is a console command source
- Returns:
Trueif it’s a console command source,Falseotherwise
- abstractmethod get_server() ServerInterface[source]
Return the server interface instance
- abstractmethod 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 returnedSubclasses might override this method to return customized preference. e.g.
PlayerCommandSourcewill return the preference of the corresponding playerSee also
Added 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
RTextMCDRTranslationExample 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)
Added 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
- abstractmethod 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
PlayerCommandSourceconsole_text – Message override when it’s a
ConsoleCommandSource
- class mcdreforged.command.command_source.InfoCommandSource(mcdr_server: MCDReforgedServer, info: Info)[source]
Bases:
CommandSource,ABCCommand source originated from an info created by MCDR
- class mcdreforged.command.command_source.PlayerCommandSource(mcdr_server: MCDReforgedServer, info: Info, player: str)[source]
Bases:
InfoCommandSourcePlayer command source: the command source that represents a player
- class mcdreforged.command.command_source.ConsoleCommandSource(mcdr_server: MCDReforgedServer, info: Info)[source]
Bases:
InfoCommandSourceConsole command source: the command source that represents the console
- class mcdreforged.command.command_source.PluginCommandSource(server: ServerInterface, plugin: AbstractPlugin | None = None)[source]
Bases:
CommandSourcePlugin command source: the command source that represents a MCDR plugin
Command Nodes
- class mcdreforged.command.builder.nodes.basic.AbstractNode[source]
Bases:
ABCAbstractNodeis 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
CommandSourceas command source and adict(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
runsmethodThis 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 meet the specified 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
RequirementNotMetexception 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 theRequirementNotMetexception, otherwise a default message will be usedAdded 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:
requirement – A callable that accepts up to 2 arguments and returns a bool. Argument list:
CommandSource,dict(CommandContext)failure_message_getter – An optional callable that accepts up to 2 arguments and returns a str or a
RTextBase. Argument list:CommandSource,dict(CommandContext)
Example usages:
node1.requires(lambda src: src.has_permission(3)) # Permission check, error if the permission is not enough 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
- precondition(precondition: Callable[[], bool] | Callable[[CommandSource], bool] | Callable[[CommandSource, CommandContext], bool]) Self[source]
Set the precondition callback for this node. Before attempting to enter this node, MCDR will invoke the precondition callback to see if the current command source and context meet the specified condition
If the precondition callback returns True, the node will remain accessible, and MCDR will continue entering the node
If the precondition callback returns False, the node will be filtered out and treated as if it does not exist
Added in version v2.14.0.
- Parameters:
precondition – A callable that accepts up to 2 arguments and returns a bool. Argument list:
CommandSource,dict(CommandContext)
Example usages:
node1.precondition(lambda src: src.has_permission(3)) # Permission check, but hide if the permission is not enough node2.precondition(lambda src, ctx: 'foo' in ctx) # Avoid re-assigning the "foo" argument
- 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
Precondition 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()andthen().redirects()is to redirect the child nodes, andthen()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
Literalnode does not support this methodExamples:
Literal('!!whereis'). \ then( Text('player_name'). suggests(lambda: ['Steve', 'Alex']). runs(lambda src, ctx: find_player(src, ctx['player_name'])) )
When the user input
!!whereisin 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:
error_type – A class that is subclass of
CommandErrorhandler – A callable that accepts up to 3 arguments. Argument list:
CommandError,CommandSource,dict(CommandContext)
- Keyword Arguments:
handled – If handled is set to True,
CommandError.set_handledis 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
- class mcdreforged.command.builder.nodes.basic.Literal(literal: str | Iterable[str])[source]
Bases:
EntryNodeLiteral 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, *, accumulate: bool | None = None, metavar: str | None = None)[source]
Bases:
AbstractNode,ABCArgument node is an abstract base class for all nodes which store parsed values
It has a str field
namewhich is used as the key used in storing parsed value in context- __init__(name: str, *, accumulate: bool | None = None, metavar: str | None = None)[source]
- Parameters:
name – The name of the argument node. Should be unique within the command tree path
- Keyword Arguments:
accumulate – If set to True, then the parsed value will be stored in a list in the command context. Re-visiting of this node appends new value to the end of the list
metavar – Optional str. It behaves like the metavar kwarg of
argparse.ArgumentParser.add_argument(), which overrides the name displayed of the command suggestion usage placeholder. If not provided, the name argument will be used as the default placeholder
Added in version v2.13.0: The accumulate parameter
Added in version v2.14.0: The metavar parameter
- class mcdreforged.command.builder.nodes.arguments.NumberNode(name, **kwargs: Unpack[_InitKwargs])[source]
Bases:
ArgumentNode,ABCThe base class of all number related argument nodes
It’s inherited by
Number,IntegerandFloat. It represents a type of number based nodeFor a
NumberNodeinstance, you can restrict the range of the parsed number value. If the parsed number is out of range, aNumberOutOfRangeexception will be risenBy 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- 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, **kwargs: Unpack[_InitKwargs])[source]
Bases:
NumberNodeAn integer, or a float
If the next element is not a number, a
InvalidNumberexception will be risen
- class mcdreforged.command.builder.nodes.arguments.Integer(name, **kwargs: Unpack[_InitKwargs])[source]
Bases:
NumberNodeAn integer
If the next element is not an integer, a
InvalidIntegerexception will be risen
- class mcdreforged.command.builder.nodes.arguments.Float(name, **kwargs: Unpack[_InitKwargs])[source]
Bases:
NumberNodeA float
If the next element is not a float, a
InvalidFloatexception will be risen
- class mcdreforged.command.builder.nodes.arguments.TextNode(name: str, **kwargs: Unpack[_InitKwargs])[source]
Bases:
ArgumentNode,ABCIt’s an abstract class. It’s inherited by
Text,QuotableTextandGreedyText. It represents a type of text based nodeFor a
TextNodeinstance, you can restrict the length range of the parsed text. If the length of the parsed text is out of range, aTextLengthOutOfRangeexception will be risenBy 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. inclusiveSee also
- 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: str, **kwargs: Unpack[_InitKwargs])[source]
Bases:
TextNodeA 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, **kwargs: Unpack[_InitKwargs])[source]
Bases:
TextA text argument with support for inputting space characters
It works just like a
Textargument node, but it gives user a way to input text with space character: Use two double quotes to enclose the text contentIf you use two double quotes to enclose the text content, You can use escape character
\to escape double quotes"and escape character\itselfFor 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: str, **kwargs: Unpack[_InitKwargs])[source]
Bases:
TextNodeA 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, *, accumulate: bool | None = None, metavar: str | None = None)[source]
Bases:
ArgumentNodeA simple boolean argument, only accepts
trueandfalse, and store them as the corresponding bool value. Case is ignoredRaises
InvalidBooleanif the input is not acceptedAdded in version v2.3.0.
- class mcdreforged.command.builder.nodes.arguments.Enumeration(name: str, enum_class: Type[Enum], **kwargs: Unpack[_InitKwargs])[source]
Bases:
ArgumentNodeA 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
InvalidEnumerationif the input argument is not a valid name for the given enum classExample usage:
class MyColor(Enum): red = 'red color' blue = 'blue color' green = 'green color' node = Enumeration('arg', MyColor)
Added in version v2.3.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
Added 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 theliteral()methodExamples:
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
Added 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 definedNotes 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 hereExamples:
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
ArgumentNodeobject
- Returns:
A
NodeDefinitionobject. 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
Literalconstructor 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
Literalobject. Optional
- Returns:
A
NodeDefinitionImplobject. 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
Added in version v2.9.0: Added
use_cachekeyword argument
- 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
PluginServerInterfaceobject 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 viathen()- Parameters:
parent_node – The command node that will become the parent of the built children nodes
- Raises:
SimpleCommandBuilder.Error – if build fails
Added in version v2.8.0.
- print_tree(line_writer: tree_printer.LineWriter)[source]
A helper method for lazyman, to build with method
build()and print the built command treesExample:
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]
- precondition(precondition: Callable[[], bool] | Callable[[CommandSource], bool] | Callable[[CommandSource, CommandContext], bool]) Self[source]
See
AbstractNode.precondition()Added in version v2.14.0.
- suggests(suggestion: Callable[[], Iterable[str]] | Callable[[CommandSource], Iterable[str]] | Callable[[CommandSource, CommandContext], Iterable[str]]) Self[source]
- 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]
- 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]
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))
See also
Method
AbstractNode.requires(), methodNodeDefinition.requires()Added 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
Exceptions
- exception mcdreforged.command.builder.exception.CommandErrorBase[source]
-
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:
CommandErrorBaseThe operation is unsupported by this node
- exception mcdreforged.command.builder.exception.CommandError(message: str | RTextBase, parsed_command: str, failed_command: str)[source]
Bases:
CommandErrorBase,ABCThe 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
- 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:
CommandErrorWhen 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:
CommandErrorWhen 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:
CommandErrorThe 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,ABCThe basic exception for command parsing error
- exception mcdreforged.command.builder.exception.IllegalArgument(message: str | RTextBase, char_read: int | str)[source]
Bases:
CommandSyntaxError,ABCThe 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,ABCThe 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:
AbstractOutOfRangeThe parsed number value is out of the restriction range
- exception mcdreforged.command.builder.exception.InvalidNumber(char_read: int | str)[source]
Bases:
IllegalArgumentThe parsed value is not a valid number
- exception mcdreforged.command.builder.exception.InvalidInteger(char_read: int | str)[source]
Bases:
IllegalArgumentThe parsed value is not a valid integer
- exception mcdreforged.command.builder.exception.InvalidFloat(char_read: int | str)[source]
Bases:
IllegalArgumentThe parsed value is not a valid float
- exception mcdreforged.command.builder.exception.TextLengthOutOfRange(char_read: int | str, value, range_l, range_r)[source]
Bases:
AbstractOutOfRangeThe length of the given text is out of the restriction range
- exception mcdreforged.command.builder.exception.IllegalEscapesUsage(char_read: int | str)[source]
Bases:
IllegalArgumentThe text contains illegal
\usage
- exception mcdreforged.command.builder.exception.UnclosedQuotedString(char_read: int | str)[source]
Bases:
IllegalArgumentThe quote is unclosed
- exception mcdreforged.command.builder.exception.EmptyText(char_read: int | str)[source]
Bases:
IllegalArgumentThe text is empty, which is not allowed
- exception mcdreforged.command.builder.exception.InvalidBoolean(char_read: int | str)[source]
Bases:
IllegalArgumentThe parsed value is not a valid boolean
- exception mcdreforged.command.builder.exception.InvalidEnumeration(char_read: int | str)[source]
Bases:
IllegalArgumentThe parsed value is not a valid Enum
Misc
- class mcdreforged.command.builder.common.CommandContext(source: CommandSource, command: str)[source]
-
A
CommandContextstores the information of the command parsing process. It’s a class inherited from dictThe most common use case for
CommandContextis storing the parsed result fromargument nodes. The name of the argument node and the parsed result will be stored as a key-value pair inCommandContext, which means you can use dict method likecontext['arg_name']to access these argument valuesCommandContextalso 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 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_utils.DIVIDER = ' '
The char to divide elements in a command string —— space
- mcdreforged.command.builder.command_builder_utils.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_utils.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_utils.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_utils.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
Note
Changed in version v2.13.0: Renamed command_builder_util to command_builder_utils. The old name is still accessible from mcdreforged.api.command