API Reference¶
Below is the API reference for mctools. Each feature is broken up into a different section. The average user shouldn’t have to worry about these, and should instead use the higher level client classes and functions. You can find tutorials on how to use them elsewhere in this documentation.
Exceptions¶
Exception objects for mctools.
- exception mctools.errors.MCToolsError¶
Base class for mctools exceptions.
- exception mctools.errors.PINGError¶
Base class for PING errors
- exception mctools.errors.PINGMalformedPacketError(message)¶
Exception raised if the ping packet received is malformed/broken, or not what we were expecting.
- exception mctools.errors.ProtoConnectionClosed(message)¶
Exception raised when the connection is closed by the socket we are connected to.
This occurs when we receive empty bytes from ‘recv()’, as this means that the remote socket is done writing, meaning that our connection is closed.
- exception mctools.errors.ProtocolError¶
Base class for protocol errors.
A protocol error is raised when an issue arises with the python socket object. These exceptions will be raised for ALL clients, as they all use the same backend.
- exception mctools.errors.RCONAuthenticationError(message)¶
Exception raised when user is not authenticated to the RCON server. This is raised when a user tries to send a RCON command, and the server refuses to communicate.
- Parameters:
message (str) – Explanation of the error
server_id – ID given to us by the server
- exception mctools.errors.RCONCommunicationError(message)¶
Exception raised if the client has trouble communicating with the RCON server. For example, if we don’t receive any information when we want a packet.
- Parameters:
message (str) – Explanation of the error
- exception mctools.errors.RCONError¶
Base class for RCON errors.
- exception mctools.errors.RCONLengthError(message, length)¶
Exception raised if the client attempts to send a packet that is too big, greater than length 1460.
- exception mctools.errors.RCONMalformedPacketError(message)¶
Exception raised if the packet we received is malformed/broken, or not what we were expecting.
- Parameters:
message (str) – Explanation of the error
MClient Reference¶
Main Minecraft Connection Clients - Easy to use API for the underlying modules Combines the following: - Protocol Implementations - Packet implementations - Formatting tools
- class mctools.mclient.BaseClient¶
Parent class for Minecraft Client implementations. This class has the following formatting constants, which every client inherits:
BaseClient.RAW - Tells the client to not format any content.
BaseClient.REPLACE - Tells the client to replace format characters.
BaseClient.REMOVE - Tells the client to remove format characters.
BaseClient.DEFAULT - Chooses the global default
You can use these constants in the ‘format_method’ parameter in each client.
Changed in version 1.3.0.
Removed interface method ‘raw_send()’, as no generic definition exists.
- gen_reqid() int ¶
Generates a request ID using system time.
- Returns:
System time as an integer
- Return type:
int
- get_formatter() FormatterCollection ¶
Returns the formatter used by this instance, Allows the user to change formatter operations.
- Returns:
FormatterCollection used by the client.
- Return type:
- is_connected() bool ¶
Determine if we are connected to the remote entity, whatever that may be. This raises a ‘NotImplementedError’ exception, as this function should be overridden in the child class.
- Returns:
True if connected, False if not.
- Raises:
NotImplementedError: If function is called.
- set_timeout(timeout: int)¶
Sets the timeout for the underlying socket object.
- Parameters:
timeout (int) – Value in seconds to set the timeout to
- start()¶
Starts the client, and any protocol objects/formatters in use. (Good idea to put a call to Protocol.start() here). This raises a ‘NotImplementedError’ exception, as this function should be overridden in the child class.
- Raises:
NotImplementedError: If function is called.
- stop()¶
Stops the client, and any protocol objects/formatters in use. (Again, good idea to put a call to Protocol.stop() here). This raises a ‘NotImplementedError’ exception, as this function should be overridden in the child class.
- Raises:
NotImplementedError: If function is called.
- class mctools.mclient.PINGClient(host: str, port: int = 25565, reqid: int = -1, format_method: int = 1, timeout: int = 60, proto_num: int = 0)¶
Ping client, allows for user to interact with the Minecraft server via the Server List Ping protocol.
- Parameters:
host (str) – Hostname of the Minecraft server
port (int) – Port of the Minecraft server
reqid (int) – Request ID to use, leave as ‘-1’ to generate one based on system time
format_method (int) – Format method to use. You should specify this using the Client constants
timeout (int) – Sets the timeout value for socket operations
proto_num (int) – Protocol number to use, can specify which version we are emulating. Defaults to 0, which is the latest.
- get_stats(format_method: int = -1, return_packet: bool = False) dict | PINGPacket ¶
Gets stats from the Minecraft server, and preforms a ping operation.
- Parameters:
format_method (int) – Determines the format method we should use. If ‘-1’, then we use the global value. You should use the Client constants to define this.
return_packet (bool) – Determines if we should return the entire packet. If not, return the payload
- Returns:
Dictionary containing stats, or PINGPacket depending on ‘return_packet’
- Return type:
dict, PINGPacket
New in version 1.1.0.
The ‘format_method’ and ‘return_packet’ parameters
New in version 1.2.0.
We now automatically stop this client after the operation
- is_connected() bool ¶
Determines if we are connected.
- Returns:
True if connected, False if otherwise.
- Return type:
bool
- ping() float ¶
Pings the Minecraft server and calculates the latency.
New in version 1.3.0.
We no longer request ping stats, we only preform the ping operation.
New in version 1.2.0.
We now automatically stop this client after the operation
- Returns:
Time elapsed(in milliseconds).
- Return type:
float
- raw_send(pingnum: int, packet_type: int, proto: int = -1, host: str = '', port: int = 0, noread: bool = False) PINGPacket ¶
Creates a PingPacket and sends it to the Minecraft server
- Parameters:
pingnum (int) – Pingnumber of the packet(For ping packets only)
packet_type (int) – Type of packet we are working with
proto (int) – Protocol number of the Minecraft server(For handshake only)
host (str) – Hostname of the Minecraft server(For handshake only)
port (int) – Port of the Minecraft server(For handshake only)
noread (bool) – Determining if we are expecting a response
- Returns:
PINGPacket if noread if False, otherwise None
- Return type:
PINGPacket, None
- start()¶
Starts the connection to the Minecraft server. This is called automatically where appropriate, so you shouldn’t have to worry about calling this.
- stop()¶
Stops the connection to the Minecraft server. This function should always be called when ceasing network communications, as not doing so could cause problems server-side.
- class mctools.mclient.QUERYClient(host: str, port: int = 25565, reqid: int = -1, format_method: int = 1, timeout: int = 60)¶
Query client, allows for user to interact with the Minecraft server via the Query protocol.
- Parameters:
host (str) – Hostname of the Minecraft server
port (int) – Port of the Minecraft server
reqid (int) – Request ID to use, leave as ‘-1’ to generate one based on system time
format_method (int) – Format method to use. You should specify this using the Client constants
timeout (int) – Sets the timeout value for socket operations
- get_basic_stats(format_method: int = -1, return_packet: bool = False) dict | QUERYPacket ¶
Gets basic stats from the Query server.
- Parameters:
format_method (int) – Determines the format method we should use. If ‘-1’, then we use the global value. You should use the Client constants to define this
return_packet (bool) – Determines if we should return the entire packet. If not, return the payload
- Returns:
Dictionary of basic stats, or QUERYPacket, depending on ‘return_packet’.
- Return type:
dict, QUERYPacket
New in version 1.1.0.
The ‘format_method’ and ‘return_packet’ parameters
- get_challenge() QUERYPacket ¶
Gets the challenge token from the Query server. It is necessary to get a token before every operation, as the Query tokens change every 30 seconds.
- Returns:
QueryPacket containing challenge token.
- Return type:
- get_full_stats(format_method: int = -1, return_packet: bool = False) dict | QUERYPacket ¶
Gets full stats from the Query server.
- Parameters:
format_method (int) – Determines the format method we should use. If ‘-1’, then we use the global value. You should use the Client constants to define this.
return_packet (bool) – Determines if we should return the entire packet. If not, return the payload
- Returns:
Dictionary of full stats, or QUERYPacket, depending on ‘return_packet’.
- Return type:
dict
New in version 1.1.0.
The ‘format_method’ and ‘return_packet’ parameters
- is_connected() bool ¶
Determines if we are connected. (UPD doesn’t really work that way, so we simply return if we have been started).
- Returns:
True if started, False for otherwise.
- Return type:
bool
- raw_send(packet_type: int, chall: int, reqtype: int = -1) QUERYPacket ¶
Creates a packet from the given arguments and sends it. Returns a response.
- Parameters:
reqtype (int) – Type of packet to send
chall (int) – Challenge Token, ignored if not relevant
reqtype – Request type to utilize
- Returns:
QUERYPacket containing response
- Return type:
Changed in version 1.3.0.
We now identity request type primarily using the ‘packet_type’ parameter. You may provide the request type, but otherwise mctools will auto-determine it for you.
Parameter types and order has been changed.
- start()¶
Starts the Query object. This is called automatically where appropriate, so you shouldn’t have to worry about calling this.
- stop()¶
Stops the connection to the Query server. In this case, it is not strictly necessary to stop the connection, as QueryClient uses the UDP protocol. It is still recommended to stop the instance any way, so you can be explicit in your code as to when you are going to stop communicating over the network.
- class mctools.mclient.RCONClient(host: str, port: int = 25575, reqid: int = -1, format_method: int = 1, timeout: int = 60)¶
RCON client, allows for user to interact with the Minecraft server via the RCON protocol.
- Parameters:
host (str) – Hostname of the Minecraft server (Can be an IP address or domain name, anything your computer can resolve)
port (int) – Port of the Minecraft server
reqid (int) – Request ID to use, leave as ‘-1’ to generate an ID based on system time
format_method – Format method to use. You should specify this using the Client constants
format_method – int
timeout (int) – Sets the timeout value for socket operations
- authenticate(password: str) bool ¶
Convenience function, does the same thing that ‘login’ does, authenticates you with the RCON server.
- Parameters:
password (str) – Password to authenticate with
- Returns:
True if successful, False if failure
- Return type:
bool
- command(com: str, check_auth: bool = True, format_method: int = -1, return_packet: bool = False, frag_check: bool = True, length_check: bool = True) RCONPacket | str ¶
Sends a command to the RCON server and gets a response.
Note
Be sure to authenticate before sending commands to the server! Most servers will simply refuse to talk to you if you do not authenticate.
- Parameters:
com (str) – Command to send
check_auth (bool) – Value determining if we should check authentication status before sending our command
format_method (int) – Determines the format method we should use. If ‘-1’, then we use the global value You should use the Client constants to define this.
return_packet (bool) – Determines if we should return the entire packet. If not, return the payload
frag_check (bool) –
Determines if we should check and handle packet fragmentation
Warning
Disabling fragmentation checks could lead to instability! Do so at your own risk!
length_check (bool) –
Determines if we should check and handle outgoing packet length
Warning
Disabling length checks could lead to instability! Do so at your own risk!
- Returns:
Response text from server
- Return type:
str, RCONPacket
- Raises:
RCONAuthenticationError: If we are not authenticated to the RCON server, and authentication checking is enabled. We also raise this if the server refuses to serve us, regardless of weather auth checking is enabled. RCONMalformedPacketError: If the packet we received is broken or is not the correct packet. RCONLengthError: If the outgoing packet is larger than 1460 bytes
New in version 1.1.0.
The ‘check_auth’, ‘format_method’, ‘return_packet’, and ‘frag_check’ parameters
New in version 1.1.2.
The ‘length_check’ parameter
- is_authenticated() bool ¶
Determines if we are authenticated.
- Returns:
True if authenticated, False if not.
- Return type:
bool
- is_connected() bool ¶
Determines if we are connected.
- Returns:
True if connected, False if not.
- Return type:
bool
- login(password: str) bool ¶
Authenticates with the RCON server using the given password. If we are already authenticated, then we simply return True.
- Parameters:
password (str) – RCON Password
- Returns:
True if successful, False if failure
- Return type:
bool
- raw_send(reqtype: int, payload: str, frag_check: bool = True, length_check: bool = True) RCONPacket ¶
Creates a RCON packet based off the following parameters and sends it. This function is used for all networking operations.
We automatically check if a packet is fragmented(We check it’s length). If this is the case, then we send a junk packet, and we keep reading packets until the server acknowledges the junk packet. This operation can take some time depending on network speed, so we offer the option to disable this feature, with the risk that their might be stability issues.
We also check if the packet being sent is too big, and raise an exception of this is the case. This can be disabled by passing False to the ‘length_check’ parameter, although this is not recommended.
Warning
Use this function at you own risk! You should really call the high level functions, as not doing so could mess up the state/connection of the client.
- Parameters:
reqtype (int) – Request type
payload (str) – Payload to send
frag_check (bool) – Determines if we should check and handle packet fragmentation.
Warning
Disabling fragmentation checks could lead to instability! Do so at your own risk!
- Parameters:
length_check (bool) – Determines if we should check for outgoing packet length
Warning
Disabling length checks could lead to instability! Do so at your own risk!
- Returns:
RCONPacket containing response from server
- Return type:
- Raises:
RCONAuthenticationError: If the server refuses to server us and we are not authenticated. RCONMalformedPacketError: If the request ID’s do not match of the packet is otherwise malformed.
New in version 1.1.0.
The ‘frag_check’ parameter
New in version 1.1.2.
The ‘length_check’ parameter
- start()¶
Starts the connection to the RCON server. This is called automatically where appropriate, so you shouldn’t have to worry about calling this.
- stop()¶
Stops the connection to the RCON server. This function should always be called when ceasing network communications, as not doing so could cause problems server-side.
Packet Reference¶
Packet classes to hold RCON and Query data
- class mctools.packet.BasePacket¶
Parent class for packet implementations.
- classmethod from_bytes(byts: bytes) Any ¶
Classmethod to create a packet from bytes. Rises an NotImplementedError exception, as this function should be overridden in the child class.
- Parameters:
byts (bytes) – Bytes from remote entity
- Returns:
Packet object
- class mctools.packet.PINGPacket(pingnum: int, packet_type: int, data: dict | None = None, proto: int = 0, host: str = '', port: int = 0)¶
Class representing a Server List Ping Packet(Or ping for short).
PINGPackets have the following types:
HANDSHAKE - Initial handshake with server, this is always the first operation!
STATUS_REQUEST - Client is asking server for status information
STATUS_RESPONSE - Server responds to status request with status response, which contains server info
PING_REQUEST - Client is asking server to respond with a pong packet, useful for determining latency
PONG_RESPONSE - Server responds to ping request with pong response
The lifecycle of a ping connection is as follows:
Handshake is initiated by client, which MUST be preformed before any operations!
Client may request server status information, server responds. Optionally, clients may skip this step
Client makes a ping request, server responds with pong response, connection is closed
- Parameters:
pingnum (int) – Number to use for ping operations
packet_type (int) – Type of packet we are working with
data (dict, None) – Ping data from Minecraft server
proto (str, None) – Protocol Version used
host (str, None) – Hostname of the Minecraft server
port (int) – Port number of the Minecraft server
- classmethod from_bytes(byts: bytes) PINGPacket ¶
Creates a PINGPacket from bytes.
- Parameters:
byts (bytes) – Bytes to decode
- Returns:
PINGPacket decoded from bytes
- Return type:
- class mctools.packet.QUERYPacket(packet_type: int, reqid: int, chall: int, data: dict | None = None, reqtype: int = -1)¶
Class representing a Query Packet.
QUERYPackets have the following types:
BASIC_REQUEST - Client is requesting basic data
BASIC_RESPONSE - Server is responding with basic data
FULL_REQUEST - Client is requesting full data
FULL_RESPONSE - Server is responding with basic data
HANDSHAKE_REQUEST - Client is requesting to handshake
HANDSHAKE_RESPONSE - Server has acknowledged the handshake
The lifecyle of a ping connection is as follows:
Client requests to handshake, and the server acknowledges and provides a challenge token
- Once handshake has completed, clients may preform one of the two actions using provided challenge token:
Client may request basic server stats
Client may request full server stats
Finally, server responds with stats at the requested level, be it basic or full
This packet has some optional parameters, namely ‘reqtype’. This parameter, if unspecified (has a value of -1), will be auto-determined at runtime. Users may set this parameter, and decoded packets will have this parameter set, but it is recommended to utilize ‘packet_type’ to identify packets instead.
- Parameters:
packet_type (int) – Type of this Query packet
reqid (int) – Request ID of the Query packet
chall (int) – Challenge token from Query server, -1 if N/A
data (dict) – Data from the Query server
reqtype (int) – Type of request, this will be auto-determined at runtime
Changed in version 1.3.0.
Removed the ‘data_type’ attribute, and internally it is no longer used. We provide the compatibility property of the same name that behaves the same as the ‘data_type’ attribute.
Packets now use ‘packet_type’ to identify themselves instead of ‘reqtype’
- property data_type: str¶
Determines the data type using the request type.
This property is here to provide compatibility with components that may utilize this value, as it was removed.
- Returns:
‘basic’ for basic data, ‘full’ for full data, blank string for neither
- Return type:
str
- classmethod from_bytes(byts: bytes) QUERYPacket ¶
Creates a Query packet from bytes.
- Parameters:
byts (bytes) – Bytes from Query server
- Returns:
Created QUERYPacket
- Return type:
- is_basic() bool ¶
Determines if this packet contains (or is asking for) basic server information.
- Returns:
True if basic, False if not
- Return type:
bool
New in version 1.3.0.
Convenience method for identifying basic packets
- is_full() bool ¶
Determines if this packet contains (or is asking for) full server information.
- Returns:
True if full, False if not
- Return type:
bool
New in version 1.3.0.
Convenience method for identifying full packets
- class mctools.packet.RCONPacket(reqid: int, reqtype: int, payload: str, length: int = 0)¶
Class representing a RCON packet.
- Parameters:
reqid (int) – Request ID of the RCON packet
reqtype (int) – Request type of the RCON packet
payload (str) – Payload of the RCON packet
Changed in version 1.3.0.
Packet types are now defined here, instead of RCONProtocol
- classmethod from_bytes(byts: bytes) RCONPacket ¶
Creates a RCON packet from bytes.
- Parameters:
byts (bytes) – Bytes from RCON server
- Returns:
RCONPacket created from bytes
- Return type:
Encoding Reference¶
Encoding/Decoding components for RCON and Query.
- class mctools.encoding.PINGEncoder¶
Ping encoder/decoder.
- static decode(byts: bytes) Tuple[dict, int] ¶
Decodes a ping packet. NOTE: Bytes provided should NOT include the length, that is interpreted and used by the PINGProtocol.
- Parameters:
byts (bytes) – Bytes to decode
- Returns:
Tuple of decoded values, data and packet type
- Return type:
Tuple[dict, str]
- static decode_sock(sock) int ¶
Decodes a var(int/long) of variable length or value. We use a socket to continuously pull values until we reach a valid value, as the length of these var(int/long)s can be either very long or very short.
- Parameters:
sock (socket.socket) – Socket object to get bytes from.
- Returns:
Decoded integer
- Return type:
int
- static decode_varint(byts: bytes) Tuple[int, int] ¶
Decodes varint bytes into an integer. We also return the amount of bytes read.
- Parameters:
byts (bytes) – Bytes to decode
- Returns:
result, bytes read
- Return type:
int, int
- static encode(data: dict, pingnum: int, packet_type: int, proto: int, hostname: str, port: int) bytes ¶
Encodes a Ping packet.
- Parameters:
data (dict) – Ping data from server
pingnum (int) – Number for ping operations
packet_type (int) – Type of packet we are working with
proto (int) – Protocol version number
hostname – Hostname of the minecraft server
:type hostname :param port: Port we are connecting to :type port: int :return: Encoded data :rtype: bytes
Changed in version 1.3.0.
We now raise an exception if invalid packet type is provided
- static encode_varint(num: int) bytes ¶
Encodes a number into varint bytes.
- Parameters:
num (int) – Number to encode
- Returns:
Encoded bytes
- Return type:
bytes
- class mctools.encoding.QUERYEncoder¶
Query encoder/decoder
- static decode(byts: bytes) Tuple[int, int, int, dict, int] ¶
Decodes packets from the Query protocol. This gets really messy, as the payload can be many different things. We also figure out what kind of data we are working with, and return that.
- Parameters:
byts (bytes) – Bytes to decode
- Returns:
Tuple containing decoded items - packet_type, reqid, chall, data, reqtype
- Return type:
Tuple[int, int, int, dict, str]
Changed in version 1.3.0.
Changed the return values
- static encode(packet_type: int, reqtype: int, reqid: int, chall: int) bytes ¶
Encodes a Query Packet.
- Parameters:
packet_type (int) – Type of query packet
reqtype (int) – Type of request, will be auto-determined if (-1)
reqid (int) – Request ID of query packet
chall (int) – Challenge token from query server
- Returns:
Encoded data
- Return type:
bytes
We no longer consider the ‘data_type’, we only do checking using the packet type.
If reqtype is not provided (-1), we determine the value using the packet_type parameter.
Input parameters have been changed
- class mctools.encoding.RCONEncoder¶
RCON Encoder/Decoder.
- static decode(byts: bytes) Tuple[int, int, str] ¶
Decodes raw bytestring packet from the RCON server. NOTE: DOES NOT DECODE LENGTH! The ‘length’ value is omitted, as it is interpreted by the RCONProtocol. If your bytestring contains the encoded length, simply remove the first 4 bytes.
- Parameters:
byts (bytes) – Bytestring to decode
- Returns:
Tuple containing values, request ID, request type, payload
- Return type:
Tuple[int, int, str]
- static encode(reqid: int, reqtype: int, payload: str) bytes ¶
Encodes a RCON packet.
- Parameters:
reqid (int) – Request ID of RCON packet
reqtype (int) – Request type of RCON packet
payload (str) – Payload of RCON packet
- Returns:
Bytestring of encoded data
- Return type:
bytes
Protocol Reference¶
Low-level protocol stuff for RCON, Query and Server List Ping.
- class mctools.protocol.BaseProtocol¶
Parent Class for protocol implementations. Every protocol instance should inherit this class!
- read() Any ¶
Method to receive data from remote entity This raises a NotImplementedErrorException, as it should be overridden in the child class.
- Returns:
Data received, data type is arbitrary
- read_tcp(length: int) bytes ¶
Reads data over the TCP protocol.
- Parameters:
length (int) – Amount of data to read
- Returns:
Read bytes
- Return type:
bytes
- read_udp() Tuple[bytes, str] ¶
Reads data over the UDP protocol.
- Returns:
Bytes read and address
- Return type:
Tuple[bytes, str]
- send(pack: Any)¶
Method to send data to remote entity, data type is arbitrary. This raises a NotImplementedErrorException, as it should be overridden in the child class.
- Parameters:
data – Some data in some format.
- set_timeout(timeout: int)¶
Sets the timeout value for the underlying socket object.
- Parameters:
timeout (int) – Value in seconds to set the timeout to
New in version 1.1.0.
This method now works before the protocol object is started
- start()¶
Method to start the connection to remote entity.
We simply set the connected value, and configure the timeout.
- stop()¶
Method to stop the connection to remote entity.
We simply set the connected value.
- write_tcp(byts: bytes)¶
Writes data over the TCP protocol.
- Parameters:
byts (bytes) – Bytes to send
- write_udp(byts: bytes, host: str, port: int)¶
Writes data over the UPD protocol.
- Parameters:
byts (bytes) – Bytes to write
host (str) – Hostanme of remote host
port (int) – Portname of remote host
- class mctools.protocol.PINGProtocol(host: str, port: int, timeout: int)¶
Protocol implementation for server list ping - uses TCP sockets.
- Parameters:
host (str) – Hostname of the Minecraft server
port (int) – Port number of the Minecraft server
timeout (int) – Timeout value used for socket operations
- read() PINGPacket ¶
Read data from the Minecraft server and convert it into a PINGPacket.
- Returns:
PINGPacket
- Return type:
- send(pack: PINGPacket)¶
Sends a ping packet to the Minecraft server.
- Parameters:
pack (PINGPacket) – PINGPacket
- start()¶
Starts the connection to the Minecraft server.
- stop()¶
Stopping the connection to the Minecraft server.
- class mctools.protocol.QUERYProtocol(host: str, port: int, timeout: int)¶
Protocol implementation for Query - Uses UDP sockets.
- Parameters:
host (str) – The hostname of the Query server.
port (int) – Port number of the Query server
timeout (int) – Timeout value for socket operations
- read() QUERYPacket ¶
Gets a Query packet from the Query server.
- Returns:
QUERYPacket
- Return type:
- send(pack: QUERYPacket)¶
Sends a packet to the Query server.
- Parameters:
pack (QUERYPacket) – Packet to send
- start()¶
Sets the protocol object as ready to communicate.
- stop()¶
Sets the protocol object as not ready to communicate.
- class mctools.protocol.RCONProtocol(host: str, port: int, timeout: int)¶
Protocol implementation for RCON - Uses TCP sockets.
- Parameters:
host (str) – Hostname of RCON server
port (int) – Port number of the RCON server
timeout (int) – Timeout value for socket operations.
Changed in version 1.3.0.
Moved packet types to RCONPacket
- read() RCONPacket ¶
Gets a RCON packet from the RCON server.
- Returns:
RCONPacket containing payload
- Return type:
- send(pack: RCONPacket, length_check: bool = False)¶
Sends a packet to the RCON server.
- Parameters:
pack (RCONPacket) – RCON Packet
length_check (bool) – Boolean determining if we should check packet length
New in version 1.1.2.
The ‘length_check’ parameter
- start()¶
Starts the connection to the RCON server.
- stop()¶
Stops the connection to the RCON server.
Formatting Tools Reference¶
Formatters to alter response output - makes everything look pretty
- class mctools.formattertools.BaseFormatter¶
Parent class for formatter implementations.
- static clean(text: Any) Any ¶
Removes format chars, instead of replacing them with actual values. Great for if the user does not want/have color support, And wants to remove the unneeded format chars.
- Parameters:
text (str) – Text to be formatted
- Returns:
Formatted text
- Return type:
str
- static format(text: Any) Any ¶
Formats text in any way fit. Note: This should not remove format chars, that’s what remove is for, Simply replace them with their required values.
- Parameters:
text (str) – Text to be formatted
- Returns:
Formatted text
- Return type:
str
- static get_id() int ¶
Should return an integer representing the formatter ID. This is important, as it determines how the formatters are sorted. Sorting goes from least - greatest, meaning that formatters with a lower ID get executed first.
- Returns:
Formatter ID
- Return type:
int
- class mctools.formattertools.ChatObjectFormatter¶
A formatter that handles the formatting scheme of ChatObjects. This description scheme differs from primitive chat objects, as it doesn’t use formatting characters. It instead uses a collection of dictionaries to define what colors and attributes should be used.
- static clean(text: dict) str ¶
Cleans a description directory, and returns the cleaned text.
- Parameters:
text (dict) – Dictonary to be formatted
- Returns:
Cleaned text
- Return type:
str
- static format(chat: dict, color: str = '', attrib: str = '') str ¶
Formats a description dictionary, and returns the formatted text. This gets tricky, as the server could define a variable number of child dicts that have their own attributes/extra content. So, we must implement some recursion to be able to parse and understand the entire string.
- Parameters:
chat (dict) – Dictionary to be formatted
color (str) – Parent text color, only used in recursive operations
attrib (str) – Parent attributes, only used in recursive operations
- Returns:
Formatted text
- Return type:
str
- class mctools.formattertools.DefaultFormatter¶
- Formatter with good default operation:
format() - Replaces all formatter codes with ascii values
clean() - Removes all formatter codes
This formatter ONLY handles formatting codes and text attributes.
- static clean(text: str) str ¶
Removes all format codes. Does not use color/text effects.
- Parameters:
text (str) – Text to be formatted.
- Returns:
Formatted text.
- Return type:
str
- static format(text: str) str ¶
Replaces all format codes with their intended values (Color, text effect, ect).
- Parameters:
text (str) – Text to be formatted.
- Returns:
Formatted text.
- Return type:
str
- static get_id() int ¶
Returns this formatters ID, which is 10.
- Returns:
Formatter ID
- Return type:
int
- class mctools.formattertools.FormatterCollection¶
A collection of formatters - Allows for formatting text with multiple formatters, and determining which formatter is relevant to the text.
This class offers the following constants:
FormatterCollection.QUERY - Used for identifying Query protocol content.
FormatterCollection.PING - Used for identifying Server List Ping protocol content.
- add(form: BaseFormatter, command: str | Iterable[str] = '', ignore: str | Iterable[str] = '') bool ¶
Adds a formatter, MUST inherit the BaseFormatter class. Your formatter must either be instantiated upon adding it, or the ‘clean’ and ‘format’ methods are static, as FormatterCollection will not attempt to instantiate your object.
- Parameters:
form (BaseFormatter) – Formatter to add.
command (Union[str, Iterable[str]]) – Command(s) to register the formatter with. May be a string or iterable. Supply an empty string (‘’) to affiliate with every command, or an iterable to affiliate with multiple.
ignore (Union[str, Iterable[str]]) – Commands to ignore, formatter will not format them, leave blank to accept everything. May be a string or iterable. Supply an empty string (‘’) to allow all commands, or an iterable to affiliate with multiple.
- Returns:
True for success, False for Failure.
- Return type:
bool
Changed in version 1.3.0.
We not accept blanks strings instead of None to denote a global match/global allow
- clean(text: Any, command: str) Any ¶
Runs the text through the clean() method of every formatter. These formatters will remove characters, without replacing them, Most likely format chars. We only send non-string data to specific formatters.
- Parameters:
text (str) – Text to be formatted.
command (str) – Command issued - determines which formatters are relevant. You may leave command blank to affiliate with every formatter.
- Returns:
Formatted text.
- Return type:
str
- clear()¶
Removes all formatters from the list.
- format(text: Any, command: str) Any ¶
Runs the text through the format() function of relevant formatters. These formatters will be removing and replacing characters, Most likely format chars.
- Parameters:
text (str) – Text to be formatted
command (str) – Command issued - determines which formatters are relevant. You may leave command blank to affiliate with every formatter.
- Returns:
Formatted text.
- Return type:
str
- get() List[Tuple[BaseFormatter, str | Iterable[str], str | Iterable[str]]] ¶
Returns the list of formatters. Can be used to check loaded formatters, or manually edit list. Be aware, that manually editing the list means that the formatters may have some unstable operations.
- Returns:
List of formatters and commands
- Return type:
List[Tuple[BaseFormatter, Command, Command]]
- remove(form: BaseFormatter) bool ¶
Removes a specified formatter from the list.
- Parameters:
form (BaseFormatter) – Formatter to remove
- Returns:
True on success, False on failure
- Return type:
bool
- class mctools.formattertools.PINGFormatter¶
Formatter for formatting responses from the server via Server List Ping protocol. We only format relevant content, such as description and player names. We also use special formatters, such as ChatObjectFormatter, and SampleDescriptionFormatter.
- static clean(stat_dict: dict) dict ¶
Cleaned a dictionary of stats from the Minecraft server.
- Parameters:
stat_dict (dict) – Dictionary to format
- Returns:
Formatted statistics dictionary.
- Return type:
dict
- static format(stat_dict: dict) dict ¶
Formats a dictionary of stats from the Minecraft server.
- Parameters:
stat_dict (dict) – Dictionary to format
- Returns:
Formatted statistics dictionary.
- Return type:
dict
- class mctools.formattertools.QUERYFormatter¶
Formatter for formatting responses from the Query server. Will only format certain parts, as servers SHOULD follow a specific implementation for Query.
- static clean(text: dict) dict ¶
Removes format chars from the response.
- Parameters:
text (dict) – Response from Query server
- Returns:
Formatted content.
- Return type:
dict
- static format(text: dict) dict ¶
Replaces format chars with actual values.
- Parameters:
text (dict) – Response from Query server(Ideally in dict form).
- Returns:
Formatted content.
- Return type:
dict
- class mctools.formattertools.SampleDescriptionFormatter¶
Some servers like to put special messages in the ‘sample players’ field. This formatter attempts to handle this, and sort valid players and null players into separate categories.
- static clean(text: List[dict]) Tuple[List[str], str] ¶
Does the same operation as format. This is okay because we don’t change up any values or alter the content, we just organize them, and the color formatter will handle it later.
- Parameters:
text (List[dict]) – Valid players, Message encoded in the sample list
- Returns:
List containing valid users, and message.
- static format(text: List[dict]) Tuple[List[str], str] ¶
Formats a sample list of users, removing invalid ones and adding them to a message sublist. We return the message in the playerlist, and also return valid players.
- Parameters:
text (List[dict]) – List of valid players, Message encoded in the sample list
- Returns:
List containing valid users, any embedded messages
- Return type:
Tuple[List[str], str]