royalnet.utils

Miscellaneous useful functions and classes.

royalnet.utils.asyncify(function: Callable, *args, **kwargs)

Convert a function into a coroutine.

Warning

The coroutine cannot be cancelled, and any attempts to do so will result in unexpected outputs.

class royalnet.utils.Call(channel, command: Type[royalnet.utils.command.Command], command_args: List[str] = None, **kwargs)

A command call. An abstract class, sub-bots should create a new call class from this.

interface_name

The name of the interface that is calling the command. For example, telegram, or discord.

interface_obj

The main object of the interface that is calling the command. For example, the royalnet.bots.TelegramBot object.

interface_prefix

The command prefix used by the interface. For example, /, or !.

alchemy

The royalnet.database.Alchemy object associated to this interface. May be None if the interface is not connected to any database.

__init__(channel, command: Type[royalnet.utils.command.Command], command_args: List[str] = None, **kwargs)

Create the call.

Parameters
  • channel – The channel object this call was sent in.

  • command – The command to be called.

  • command_args – The arguments to be passed to the command

  • kwargs – Additional optional keyword arguments that may be passed to the command, possibly specific to the bot.

_session_init()

If the command requires database access, create a royalnet.database.Alchemy session for this call, otherwise, do nothing.

alchemy = NotImplemented
get_author(error_if_none=False)

Try to find the universal identifier of the user that sent the message. That probably means, the database row identifying the user.

Parameters

error_if_none – Raise a royalnet.error.UnregisteredError if this is True and the call has no author.

Raises

royalnet.error.UnregisteredError

interface_name = NotImplemented
interface_obj = NotImplemented
interface_prefix = NotImplemented
net_request(message, destination: str) → dict

Send data through a royalnet.network.RoyalnetLink and wait for a royalnet.network.Reply.

Parameters
  • message – The data to be sent. Must be pickle-able.

  • destination – The destination of the request, either in UUID format or node name.

reply(text: str) → None

Send a text message to the channel where the call was made.

Parameters

text – The text to be sent, possibly formatted in the weird undescribed markup that I’m using.

run()

Execute the called command, and return the command result.

session_end()

Close the previously created royalnet.database.Alchemy session for this call (if it was created).

class royalnet.utils.Command

The base class from which all commands should inherit.

command_name

The name of the command. To have /example on Telegram, the name should be example.

command_description

A small description of the command, to be displayed when the command is being autocompleted.

command_syntax

The syntax of the command, to be displayed when a royalnet.error.InvalidInputError is raised, in the format (required_arg) [optional_arg].

require_alchemy_tables

A set of royalnet.database tables, that must exist for this command to work.

network_handlers

A list of :py:class:`classyalnet.utils.NetworkHandler`s that must exist for this command to work.

command_description = NotImplemented
command_name = NotImplemented
command_syntax = NotImplemented
classmethod common(call: Call)
classmethod network_handler_dict()
network_handlers = {}
require_alchemy_tables = {}
royalnet.utils.safeformat(string: str, **words) → str

str.format() something, but ignore missing keys instead of raising an error.

Parameters
  • string – The base string to be formatted.

  • words – The words to format the string with.

Returns

The formatted string.

royalnet.utils.cdj(class_: Any) → dict

Return a dict of the class attributes without the __module__, __dict__, __weakref__ and __doc__ keys, to be used while generating dynamically SQLAlchemy declarative table classes.

Parameters

class – The object that you want to dict-ify.

Returns

The class dict.

Warning

You can’t dict-ify classes with __slots__!

royalnet.utils.sleep_until(dt: datetime.datetime) → None

Block the call until the specified datetime.

Warning

Accurate only to seconds.

royalnet.utils.plusformat(i: int) → str

Convert an int to a str, prepending a + if it’s greater than 0.

Parameters

i – the int to convert.

Returns

The resulting str.

class royalnet.utils.CommandArgs

An interface to access the arguments of a command with ease.

__getitem__(item)

Arguments can be accessed with an array notation, such as args[0].

Raises

royalnet.error.InvalidInputError – if the requested argument does not exist.

joined(*, require_at_least=0) → str

Get the arguments as a space-joined string.

Parameters

require_at_least – the minimum amount of arguments required, will raise royalnet.error.InvalidInputError if the requirement is not fullfilled.

Raises

royalnet.error.InvalidInputError – if there are less than require_at_least arguments.

Returns

The space-joined string.

match(pattern: Pattern[AnyStr]) → Sequence[AnyStr]

Match the royalnet.utils.commandargs.joined() to a regex pattern.

Parameters

pattern – The regex pattern to be passed to re.match().

Raises

royalnet.error.InvalidInputError – if the pattern doesn’t match.

Returns

The matched groups, as returned by re.Match.groups().

optional(index: int, default=None)

Get the argument at a specific index, but don’t raise an error if nothing is found, instead returning the default value.

Parameters
  • index – The index of the argument you want to retrieve.

  • default – The value returned if the argument is missing.

Returns

Either the argument or the default value, defaulting to None.

class royalnet.utils.NetworkHandler

The NetworkHandler functions are called when a specific Message type is received.

message_type = NotImplemented
royalnet.utils.andformat(l: List[str], middle=', ', final=' and ') → str

Convert a list to a str by adding final between the last two elements and middle between the others.

Parameters
  • l – the input list.

  • middle – the str to be added between the middle elements.

  • final – the str to be added between the last two elements.

Returns

The resulting str.

royalnet.utils.plusformat(i: int) → str

Convert an int to a str, prepending a + if it’s greater than 0.

Parameters

i – the int to convert.

Returns

The resulting str.

royalnet.utils.fileformat(string: str) → str

Ensure a string can be used as a filename by replacing all non-word characters with underscores.

Parameters

string – the input string.

Returns

A valid filename string.

royalnet.utils.ytdldateformat(string: Optional[str], separator: str = '-') → str

Convert the weird date string returned by youtube-dl into the YYYY-MM-DD format.

Parameters
  • string – the input string, in the YYYYMMDD format.

  • separator – the string to add between the years, the months and the days. Defaults to -.

Returns

The resulting string, in the format YYYY-MM-DD format.