Client reference

Any ShellBot needs a Client and other data model. To this end, core modules are required and listed below.

class shellbot.client.ShellBotClient(sql)

Implement a Discord bot client.

Parameters:sql (py314.sql.driver.SqlDriver) – A driver.
classmethod enable_timeit_strategy()

Decorate some methods with WithTimeitPolicy.wraps().

classmethod disable_timeit_strategy()

Remove the timing decorators.

uptime

int – The client uptime in seconds.

mstime

int – The client uptime in milliseconds.

library

Library – The current plugins.

servers

ServerSet – Set of servers.

mention

str – Return a mention for the client.

client

discord.Client – The Discord Client attached to self.

client_user

discord.ClientUser – The associated Discord user.

id

int – The client id.

sql

py314.sql.driver.SqlDriver – An SQL interface.

save()

Save the current state in the database file.

reload()

Read the configuration files for each server and reloads them.

owner

discord.User – The bot owner.

coroutine announce(destination, body, *, style=None)

Send a message to the channel and notify the channel via a mention. The message contains a specific header that connot be modified.

Parameters:
coroutine auth_check(record)

Superuser check permissions.

Parameters:record (MessageRecord) – A looking-like command record.
coroutine debug(ctx)

A critical error occurs on the server, and the bot cannot normally behave. This attempts to solve the problem, by reloading the server and disconnecting from a potential voice channel. Usually, this is the blocking cause.

Parameters:ctx (Context) – The context to debug.
coroutine forward_embed(destination, embed, *, peer=None)

Send an embed on some destination without having to construct it. If peer is provided, prepend a mention to the embed message.

Parameters:
coroutine mark(message, state)

Add a check or a cross to message depending on state.

Parameters:message (discord.Message) – The message to modify.
coroutine notify(destination, content)

Send content to a specific destination by appending a bell emoji. This method is usually used when one wants the bot to speak without mentioning someone.

The bot client does not interact in private messages, except for un-ignoring users. Therefore, the destination parameter is expected to be of suitable types.

Parameters:
Returns:

The discord.Message that was sent.

coroutine process_command(record)

Command event analysis and plugin dispatch.

Parameters:record (MessageRecord) – A looking-like command record.
coroutine reply(record, body, *, style=None, override=False)

Reply to a record via send(). Destination is record’s channel.

Since MessageRecord instances are meant to be constructed using Discord servers and messages, this method must reply on a public server’s channel.

Parameters:
Returns:

The discord.Message that was sent if any.

coroutine send(destination, body, delete_after=None, **kwargs)

Make a Message with body and the keyword arguments, and send it to the desired destination.

Despite the fact that the bot does not react to private messages, it is still possible to send messages to private channels directly.

Parameters:
  • destination (discord.abc.Messageable) – The destination the content is to be sent to.
  • body (str) – The message body to send.
  • delete_after (float [optional]) – Timeout before deleting the messsage.
Returns:

The discord.Message that was sent.

coroutine send_analyzed_embed(destination, *, peer=None, **kwargs)

Delegate to Embed the construction of a discord.Embed sent to destination and enable voting analysis via ImageView.

Parameters:
coroutine send_book(destination, pages, broadcaster, *, peer=None)

Send the output pages of prepare_book() to destination via a suitable broadcaster.

Parameters:
coroutine send_embed(destination, *, peer=None, **kwargs)

Delegate to Embed the construction of the discord.Embed sent to destination.

Parameters:
coroutine send_embeds(destination, *messages, peer=None)

Send a book to destination via send_book().

A page in pages is expected to be a dict which matches the signature of Embed, or an instance of the latter already.

Parameters:
coroutine send_messages(destination, *messages, peer=None)

Send a book to destination via send_book().

The book pages are given by messages and all messages are expected to be Message instances.

Parameters:
coroutine system_announce(content)

Send an administration message to all servers.

Parameters:
coroutine wait_for(*args, **kwargs)

Proxy for the discord.Client.wait_for() method.

Internal Events

ShellBotClient.on_exception(location=None)

Log a message where into the runtime logging file with a FATAL flag and logs the exception in the error logs.

coroutine ShellBotClient.on_command_error(record)

Called when an error occurred. An error will be sent on the event’s location, which has no type restriction. After some time, the message will be automatically deleted in order to avoid error’s flood.

Discord events

The following Discord events have been supplanted from their original behaviour.

coroutine ShellBotClient.on_ready()
coroutine ShellBotClient.on_message(message)

Called when a message is created and sent to a server. Private messages must are most of the time ignored, except in the following cases

  • The user that sent the private message is an ignored user. Sending a private message disables this functionality.
  • The user that sent the private message is the bot owner. The message will be interpreted as a sysadmin command and handled by the administration UI.
Parameters:message (discord.Message) – A discord.Message of the current message.
coroutine ShellBotClient.on_message_delete(message)

Called when a self (i.e. from the bot itself) message is deleted.

Parameters:message (discord.Message) – The discord.Message being deleted.
coroutine ShellBotClient.on_reaction_add(reaction, member)

Called when a message has a reaction added to it.

Decides on a strategy depending on the reactions on bot messages. Only messages with predefined reactions are analyzed.

No reactions can be added except for those with sufficiently many privileges. The message must comes from a public channel.

Parameters:

Note

Get the parent message via discord.Reaction.message.

coroutine ShellBotClient.on_guild_available(parent)

Called when a parent server becomes available. The server must have existed in the discord.Client.servers cache.

Load a new instance of the server in the set of servers if needed.

Parameters:parent (discord.Guild) – The guild that has changed availability.
coroutine ShellBotClient.on_guild_unavailable(parent)

Called when a parent server becomes unavailable. The server must have existed in the discord.Client.servers cache.

Parameters:parent (discord.Guild) – The guild that has changed availability.
coroutine ShellBotClient.on_guild_update(before, after)

Called when a server has been updated, i.e. whenever a discord.Guild updates, for example:

  • Changed name
  • Changed AFK channel
  • Changed AFK timeout
  • etc
Parameters:
coroutine ShellBotClient.on_guild_join(parent)

Called when either a discord.Guild is either created by the discord.Client or the discord.Client joins a server. The parent is properly added and all plugins are by default enabled on the latter.

Parameters:parent (discord.Guild) – The guild that was joined.
coroutine ShellBotClient.on_guild_remove(parent)

Called when the client is removed from an existing Discord server. This happens through, but not limited to, these circumstances:

  • The client got banished.
  • The client got kicked.
  • The client left the server.
  • The client or the server owner deleted the server.

In order for this event to be invoked, the discord.Client must have been part of the server to begin with. (i.e. it is part of discord.Client.servers)

The parent is properly deleted from the set of registered servers.

Parameters:parent (discord.Guild) – The guild that got removed.
coroutine ShellBotClient.on_guild_role_create(role)

Called when a discord.Guild creates a discord.Role.

Parameters:role (discord.Role) – The role that was created.
coroutine ShellBotClient.on_guild_role_delete(role)

Called when a discord.Guild deletes a discord.Role.

Parameters:role (discord.Role) – The discord.Role that was deleted.
coroutine ShellBotClient.on_guild_role_update(_, after)

Called when a discord.Role is changed guild-wide.

Parameters:
  • before (discord.Role) – The role that updated with the old info [unused].
  • after (discord.Role) – The role that updated with the updated info.
coroutine ShellBotClient.on_guild_channel_create(channel)

Called when a guild channel is added to a server.

Parameters:channel (discord.abc.GuildChannel) – The guild channel that got added.
coroutine ShellBotClient.on_guild_channel_delete(channel)

Called when a guild channel is removed from a server.

Parameters:channel (discord.abc.GuildChannel) – The guild channel that got removed.
coroutine ShellBotClient.on_member_join(member)

Called when a discord.Member joins a server.

Parameters:member (discord.Member) – The member that joined.
coroutine ShellBotClient.on_member_remove(member)

Called when a discord.Member leaves a server.

Parameters:member (discord.Member) – The member that left.
coroutine ShellBotClient.on_member_ban(guild, member)

Called when a discord.Member is banished from a server.

Parameters:
coroutine ShellBotClient.on_member_unban(guild, user)

Called when a discord.User gets unbanned from a server.

Parameters:
coroutine ShellBotClient.on_member_update(before, after)

Called when a discord.Member changes its Discord status.

Parameters:
coroutine ShellBotClient.on_voice_state_update(member, *_)

Called when a discord.Member changes their voice state.

The following, but not limited to, examples illustrate when this event is called:

  • A member joins a voice room.
  • A member leaves a voice room.
  • A member is muted or deafened by their own accord.
  • A member is muted or deafened by a server administrator.
Parameters:member (discord.Member) – Member whose voice state changed.

Administration

class shellbot.ui.Administration(bot)

All owner-only commands that relate to debug bot operations.

Parameters:bot (ShellBotClient) – An instance of the bot.
coroutine sql(_, stmt)
Brief SQL execution with transaction commit.
Usage sql <stmt>
Options Description
  stmt statement to execute
coroutine status(_, action, value=None)
Brief Define Discord status.
Usage status [set VALUE | reset]
Options Description
  set VALUE try to change presence and then status
  reset reset status to default status
coroutine chgroup(user, prefix, gid, uid)
Brief Change user group.
Usage chgroup <prefix> <gid> <rid>
Options Description
  prefix either ‘+’ or ‘-‘ for an up or down action
  gid a valid group (blacklisted, sudo, root)
  uid user id
coroutine chmod(user, prefix, mode, name)
Brief Enable or disable command or plugin.
Usage chmod <prefix> <mode> <name>
Options Description
  prefix either ‘+’ or ‘-‘ for an up or down action
  mode either ‘c’ or ‘p’ for command or plugin mode
  name a command or plugin name
Raise:CommandError.
coroutine config(user, path, cast, value)
Brief Change credentials values.
Usage config path [--cast CAST] <VALUE>
Options Description
  path the dictionary tree path
  --cast builtins constructor string
  VALUE new value
coroutine help(user, name)
Brief Display command help.
Usage help <command_name>
coroutine logs(user, opt, name)
Parameters:user (discord.User) – The sysadmin.
Brief Manage logs.
Usage logs [ls | clear | clear-all] [name]
Options Description
  name security, error, all or a server ID
  ls fetch logs in T
  clear clear all .gz logs of server ID T
  clear-all clear all logs of server ID T
coroutine ls(user, group)
Brief List specific collections.
Usage ls <group>
Groups Description
  cmds the Administration commands
  blcmds blacklisted commands
  plugins plugins
  servers servers
  users users with additional permissions
  blusers blacklisted users
  sudo superusers
  root root users
coroutine notify(destination, body)

Send a message to destination.

Parameters:message (str) – The message to send.
coroutine on_message(message, permissions)

Command event analysis when the author is perhaps the bot owner.

A core command will be a manager command that only the bot owner can access; such an event will be triggered only by the bot owner who actually has an specific ID.

Exceptions can be raised if a message cannot be send.

Parameters:permissions (PermissionsRecord) – Permission record.
coroutine say(_, location, message)
Brief Send a message.
Usage say <ID> <message>
Options Description
  ID message is sent to an explicit location ID
Raise:CommandError.
coroutine system(user, term, value=None)
Brief Redefine system variables.
Usage system [? | (+/-)d|r | -v N | timeout N]
Options Description
  ? display debug informations
  +d enter DEBUG_MODE
  -d leave DEBUG_MODE
  +r leave RELEASE_MODE
  -r leave RELEASE_MODE
  -v N change verbosity to N
  timeout N change SQL timeout to N (-1 for none)
coroutine systemd(user, action)
Brief Execute a systemd action.
Usage systemd <action>
Actions Description
  save save the current state
  stop stop the Python script
  reboot restart the Python script
  reload reload configurations
coroutine top(user, action=None)
Brief Display stats usage.
Usage top --[cpu | memory | disk | uptime]
Options Description
  --cpu display CPU usage
  --memory display RAM usage
  --disk display DISK usage
  --uptime display bot uptime
coroutine warn(_, location, message)
Brief Send an administration message.
Usage warn [-g | -G | [id]] <message>
Options Description
  -g message is sent everywhere
  -G message is sent everywhere with @everyone
  ID message is sent to an explicit location ID
Raise:CommandError.

Commands

core module

class shellbot.ext.core.CommandManual(config)

Command documentation meta-data.

Parameters:config (dict) – The configuration block for the command.
brief

str – The command description.

usage

str – The command usage.

options

dict – The command options documentation.

raw_examples

dict – The command examples (from YML).

raw_details

str – The command extended help (from YML).

class shellbot.ext.core.Command(shared, callback)

An object describing a plugin command. It contains the documentation along with the method to execute.

Parameters:
qualifiers

set – An alias for qualifiers.

cooldown_cache

CooldownCache – The command cooldown cache mapping.

manual

dict – The command manual dictionary for this command.

name

str – The command name.

essential

bool – Essential component (disabling not allowed).

aliases

set – The name aliases.

qualifiers

set – A set of command name and aliases.

on_reload()

Update command configuration according to the plugin configuration.

prepare(ctx)

Prepare the context ctx and return a dict or a sentinel to denote the command arguments or the presence of an help argument.

The help page can only be displayed for contexts with permissions.

Exceptions are raised and describe command or permissions errors.

Parameters:ctx (Context) – The command context.
generate_rst()

Generate the RST documntation of the command.

coroutine execute(ctx, **kwargs)

Delegate the command execution to the associated callback. Positional and keyword parameters must match the signature of the callback.

Parameters:ctx (Context) – The command context.
class shellbot.ext.core.commands

Implement the decorator design pattern for Command.

Command options can be defined either using strings or keyword arguments, depending on the decorator used. In all cases, the option must not contain any prefix for it is automatically and internally determined.

The order decorators are called is important. Defining meta data via this class requires to call enter() and exit() as the first and the last decorators respectively. Use decorate() if no other decorators are to be called.

Examples

@commands.exit
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass

# Equivalent to the one above.
@commands.decorate
async def my_command(ctx, *args, **kwargs):
    pass

@commands.exit
# Some other decorators (see below).
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass
static enter(func)

Define the necessary fields for a command callback.

static exit(func)

Add to the func coroutine an attribute __specs__ defined to be a CommandSpecs instance constructed via the temporary fields injected by the other decorators.

These fields are deleted at the end of the process and __specs__ is expected to denote a valid attribute of func.

If func lacks a __misc__ field, misc() is called before.

static decorate(func)

Composition of enter() with exit().

classmethod misc(*names, metaname=None, cooldown=<class 'py314.globals.SENTINEL'>, **kwargs)

Add a MiscSpecs attribute to the callback accessible through __misc__.

The command name is either the function name with underscores repaced by - or metaname.

Parameters:
  • *names – Optional aliases.
  • metaname (str [optional]) – Another command name to override the default one.

Note

This temporary attribute is deleted on exit() call.

classmethod specify(name, typespecs, **kwargs)

Add to the callback a temporary attribute called name with value set to typespecs(**kwargs).

Note

The temporary attribute is deleted on exit() call.

Parameters:
  • name (str) – The temporary field name.
  • typespecs (type) – Subclass of Specs.
classmethod options(**kwargs)

Partialization of specify() with name set to __options__ and typespecs to OptionsSpecs.

classmethod permissions(**kwargs)

Partialization of specify() with name set to __permissions__ and typespecs to PermissionsSpecs.

classmethod abbrev(*args, **kwargs)

Define aliases for optional commands parameters that are not flags. In particular, positional commands parameters do not support aliases.

If this method is called without arguments, aliases are internally and automatically defined as follows: for all non-flags optional command parameters, their alias is set to the first letter, e.g. the alias for the option --arg is -a.

If arguments are passed to this method, aliases are defined as follows according to the positional and optional arguments.

  • A positional argument is interpreted as the option name and its alias is automatically determined as above.
  • An arrow key → value is interpreted as an option called key and its alias is then set to value.
Raise:AssertionError – Duplicated or unknown argument.
classmethod define_field(field, value, *args, **kwargs)

Construct a namespace mapping argument names with parser attributes as defined in options.

The arrows in the namespace are defined as follows.

  • Positional arguments yield arrows key → attrs, where attrs is a dict with a single arrow field → value.
  • Arrow key → obj yields an arrow key → attrs, where attrs is a dict defined to be either obj updated with the arrow field → value if obj is itself a dict, or the associative array [field → value, action → obj] otherwise.
Raises:AssertionError – Duplicated arguments.
classmethod switch(*names)

Define optional CommandOption whose names are given by names. The underlying parser attributes is given by enable.

Each name in names is either a full string denoting a option name or a tuple of strings denoting a mutually exclusive group.

Examples

Define the options --foo and --bar.

@commands.exit
@commands.switch('foo', 'bar')
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass

Define the options --foo and --bar and a mutually exclusive group formed by --baz and --biz.

@commands.exit
@commands.switch('foo', 'bar', ('baz', 'biz'))
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass

Warning

The prefix char must not be given, for only optional arguments may behave like switches.

classmethod flags(*names)

Use bool_exclusive to make mutually exclusive flags groups. A name in names is interpreted as a common flag name for a single group.

Example

Mutually exclusive flags +x and -x with destination variable set to x.

@commands.exit
@commands.flags('x')
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass
classmethod inclusive_flags(**kwargs)

Use inclusive to make many inclusive flags groups. Each keyword is interpreted as the base flag name for a single group.

Example

Inclusive flags +x and -x with action parsers attribute set to append and destination variables set to x_allow and x_deny.:

@commands.exit
@commands.inclusive_flags(x='append')
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass
classmethod multi_inclusive_flags(attrs, *names)

Define flags arguments of the form (+/-) with a same pattern.

classmethod weak_options(typeinfo, *args, **kwargs)

Define weak options depending on typeinfo.

Parameters:typeinfo (TypeInfo) – A valid option type info.

See also

options

classmethod posin(*args, **kwargs)

Define positional inclusive options.

Warning

The order which the arguments are given in is important.

classmethod weak_posin(*args, **kwargs)

Define weak CommandOption instances with POS typeinfo.

Warning

The order which the arguments are given in is important.

classmethod required(*args, **kwargs)

Positional required argument.

classmethod gather(argument, *, required=True)

Use gather() to make options gathering all parsed values into a single string.

Parameters:required (bool [optional]) – The option is required.
classmethod multiposin(attrs, *args)

Define positional inclusive options with same parser attributes.

Warning

When this decorator is called or the order which the arguments are given in is important.

classmethod weak_multiposin(attrs, *args)

Define weak positional inclusive options with same parser attributes.

Warning

The order which the arguments are given in is important. It is also important whether weak_multiposin() is called before or after other decorators.

classmethod optin(*args, **kwargs)

Define some CommandOption instances with OPT typeinfo.

Positional arguments always yield weak options since the default parser attribute is set to SUPPRESS but keyword arguments allow to redefine this behaviour by providing a parser attribute dictionary.

Example

Define an option --this with a default value set to that

@commands.exit
@commands.optin(this={'default': 'that'})
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass
classmethod weak_optin(*args, **kwargs)

Define weak CommandOption instances with OPT typeinfo.

Example

Define an option --this with an action set to append

@commands.exit
@commands.optin(this='append')
@commands.enter
async def my_command(ctx, *args, **kwargs):
    pass
classmethod multioptin(attrs, *args)

Define optional inclusive arguments with common parser attributes.

Equivalent to:

optin(**dict.fromkeys(args, model))

Warning

The order which the arguments are given in is not important, because those are optional arguments, hence with a specific name.

classmethod weak_multioptin(attrs, *args)

Add weak optional inclusive arguments with common parser attributes.

See also

weak_optin()

classmethod optex(*groups)

Add the optional exclusive arguments.

classmethod optex_group(attrs, *args)

Define a XORGroup group whose members names are given by args and whose parser attributes are all attrs.

specs module

class shellbot.ext.specs.MiscSpecs(name, *aliases, cooldown=<class 'py314.globals.SENTINEL'>, skip=False, state=<State.ENABLED: 1>)

Command miscellaneous meta-data.

Parameters:
  • name (str) – The command name.
  • *aliases – Command aliases.
  • cooldown (Cooldown [optional]) – The command cooldown.
  • skip (bool [optional]) – The command is not implemented.
  • state (State [optional]) – The command state default state. Runtime state is handled by the state attribute.

A py314.globals.SENTINEL cooldown is considered as a default one.

qualifiers

set – A set of command name and aliases.

bits

str –A string describing (skip, state).

class shellbot.ext.specs.OptionsSpecs(arity=None, posin=(), optin=(), optex=())

Command Options meta-data.

A tuple is necessary to store positional, optional and mutually exclusive arguments because the order of the declare arguments MUST match the signature of the coroutine and the invokation.

Parameters:
  • arity (Union[int, Tuple[int, int]] [optional]) – Either (nmin, nmax) for the minimal and maximal number of arguments or the arity of the coroutine.
  • posin (tuple [optional]) – Positional inclusive arguments.
  • optin (tuple [optional]) – Optional inclusive arguments.
  • optex (tuple [optional]) – Optional exclusive argument groups.
arity

Union[int, Tuple[int, int]] – Arity description.

class shellbot.ext.specs.PermissionsSpecs(gid=None, www=None, no_www=True, options=None)

Command Permissions meta-data.

gid

GID – Minimal required GID to execute the command.

www

WWW – Minimal Discord permissions to execute this command.

no_www

bool – GID permissions override Discord permissions.

options

dict – A mapping whose keys are options names and values are required GIDs.

class shellbot.ext.specs.CommandSpecs(misc, options, permissions)

A command callback meta data holder. The __specs__ attribute in callback that are command callbacks is an instance of this class.

Parameters:
set_doc(manual)

Define help text for all options.

Parameters:manual (CommandManual) – A command manual.

Cooldowns and errors

class shellbot.ext.cooldown.Cooldown(tokens, dt, scope)

A command cooldown object.

Parameters:
  • tokens (int) – The number of available tokens before starting cooldown.
  • dt (float) – The cooldown time.
  • scope (Scope) – The scope on which the cooldown acts.
copy()

Return a deepcopy of self.

is_dead(now)

Decide whether the current cooldown must be consumed.

Parameters:now (float) – A time base reference point.
is_rate_limited()

Update number of tokens left and check if a rate-limit takes place.

A rate-limit takes place if the current number of tokens left is zero and if the current window contains the current time.

retry_after

float – Number of seconds to wait before refreshing tokens.

reset()

Reset the cooldown and the tokens.

classmethod default()

Traits method for a default cooldown.

class shellbot.ext.cooldown.CooldownCache(cooldown)

Cooldown cache based on cooldown. If it is None, it means that the base cooldown is a cooldown equivalent to no cooldown.

Parameters:cooldown (Cooldown) – An original cooldown object.
is_set

bool – A common cooldown is set.

get_cooldown(ctx)

Return the current cooldown object associated with ctx and create a valid entry in the current cache if ctx has no associated key.

Parameters:ctx (Context) – The command context.
Returns:The associated Cooldown object.
exception shellbot.ext.errors.CommandError

Generic exception for Commands Execution errors.

exception shellbot.ext.errors.OnCooldown

Exception raised when the command is in cooldown.

exception shellbot.ext.errors.BadArgument

Generic exception for errors due to command arguments.

exception shellbot.ext.errors.UnreachedArity

Exception raised when there is not sufficiently many arguments.

exception shellbot.ext.errors.ArityExcess

Exception raised when there is too many arguments.

Actions on arguments

Action objects are used by an argparse.ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. This package provides an extension of argparse.Action.

Core classes

class shellbot.ext.action.ABCAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Actions used by an UNIXParser object. Implement more actions in addition to those provided in argparse.

The destination value is filled with the output of adapter() and thus children classes must re-implement the internal method feed().

An error message can be defined in children classes through the errmsg keyword parameter of the __init_subclass__() special method.

classmethod __init_subclass__(errmsg=None)

This method is called when a class is subclassed.

The default implementation does nothing. It may be overridden to extend subclasses.

__call__(parser, namespace, values, option_string=None)

Add a field named argparse.ArgumentParser.dest to namespace and set its value to self.adapter(take_next(values)).

classmethod adapter(string)

Check that string is valid and return the output of feed().

Parameters:string (str) – A string to adapt.
Returns:The value inserted into the namespace as in __call__().
classmethod feed(string)

Transformation to apply on the values sent into the namespace.

Return a DataView instance or an instance of a builtin type if possible.

Parameters:string (str) – A string to transform or None.
Returns:The value inserted into the namespace as in __call__().
classmethod check(*args)

A class predicate invoked to check the parsed values.

classmethod format_exc(string)

Return a formatted exception when string is an invalid data.

Parameters:string (str) – A string that could not have been transformed.
Returns:A BadArgument exception.
class shellbot.ext.action.Extended

Namespace containing extended base actions.

class Required(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Argparse action for a required positional argument which also flattens the list containing it if needed.

__call__(parser, namespace, values, option_string=None)

Call self as a function.

class Gather(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Argparse action for gathering arguments in a list into a single one. It is equivalent to define an argument with an append action and then join them in a single string.

__call__(parser, namespace, values, option_string=None)

Call self as a function.

__weakref__

list of weak references to the object (if defined)

class shellbot.ext.action_data.DataView(data)

A generic data that may hydrate the namespace value.

Parameters:data (str) – A string to use in a certain manner.
data

str – The parent raw data.

class shellbot.ext.action_data.SlotsView(data)

Parse a string following a finite pattern a_1:...:a_n.

Give a slot a_i, the type() and default() methods yield an explicit transformation (which can be apparented as a type) and a default value respectively and these are retrieved via type(i) and default(i).

Slots can be skipped by putting two consecutive colons, e.g a_1::a_3. The slot value of a missing slot is given by its default value.

classmethod size()

The number of slots.

classmethod sanitize(data)

Clean all slots in data and return an interpretable version it.

Parameters:data (str) – A string to sanitize.
classmethod type(index)

Return the slot transformation to apply on the parsed string.

Parameters:index (int) – A slot index.
classmethod default(index)

Return the default slot value.

Parameters:index (int) – A slot index.
classmethod hydrate(data)

Given a sanitized data, return a tuple of slot converted values.

Parameters:data (str) – A data passed through sanitize().

See also

to_slots()

classmethod to_slots(data)

Given a sanitized data, return a tuple of non-converted slot values. A skipped slot has a default value as explained above.

Parameters:data (str) – A data passed through sanitize().
slot(index)

Return the current slot (converted) value positioned at index.

Parameters:index (int) – Slot index.
slots(*indices)

Return a tuple whose items are given by slot() via slot(index) as index ranges over indices.

class shellbot.ext.action_data.MatchView(data)

Construct a valid abstract action data. No sanity check is performed so that properties() may have an unpredicable behaviour.

A class attribute sre_pattern of type typing.Pattern instance is given to handle parsing and extraction of properties in subclasses, and its source string pattern is given by the class keyword argument source.

classmethod sre_match(string)

Return a typing.Match instance for string if any.

Parameters:string (str) – A string to parse.
classmethod has_match(string)

Check that there are zero or more characters matched at the beginning of the given string.

Parameters:string (str) – A string to parse.
match

typing.Match – The match on DataView.data.

properties(*fields)

Return a tuple of properties in subclasses.

Enumerations

This module provides actions for enumerations in "shellbot.enums.

class shellbot.ext.action_enums.PrimaryKeyType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Action to retrieve primary keys from strings desrcibing valid ones.

classmethod feed(string)

Return a Role primary key.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string is a literal nonzero positive integer or the name of a GID member. Strings parsed without considering their case.

Parameters:string (str) – A string to check.
class shellbot.ext.action_enums.HTTPMethodType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Action to retrieve py314.requests.HTTPMethod instances.

classmethod feed(string)

Return the member in py314.requests.HTTPMethod described by string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string contains a py314.requests.HTTPMethod member name (case insensitive check).

Parameters:string (str) – A string to check.

Mentions

This module provides actions handling Discord mentions.

class shellbot.ext.action_mentions.MentionObject(data)
id

int – The Discord ID in the mention as an integer.

class shellbot.ext.action_mentions.ChannelMatch(data)
class shellbot.ext.action_mentions.UserMatch(data)
class shellbot.ext.action_mentions.ChannelMention(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Retrieve an integral Discord Channel ID from a mention.

classmethod feed(string)

Return the Discord Channel ID of the string mention as an integer.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string is a valid channel mention.

Parameters:string (str) – A string to check.
class shellbot.ext.action_mentions.UserMention(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Retrieve an integral Discord User ID from a mention.

classmethod feed(string)

Return the Discord Member ID of the string mention as an integer.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string is a valid user mention.

Parameters:string (str) – A string to check.

Mathematics

This module provides actions handling numerical values and operations.

class shellbot.ext.action_maths.RRType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

A string that is None or False is accepted and is left literal. This is implemented like this so that users can decide which default value to give to an empty string.

classmethod feed(string)

Re-implement float conversion.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string is either a real number or is logically false.

Parameters:string (str) – A string to check.
classmethod numeric_check(string)

Check that string is a real number.

Parameters:string (str) – A string to check.
class shellbot.ext.action_maths.ZZType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Representation of an integer.

classmethod feed(string)

Re-implement int conversion.

Parameters:string (str) – A string satisfying check().
classmethod numeric_check(string)

Check that string is an integer.

Parameters:string (str) – A string to check.
class shellbot.ext.action_maths.ZZPType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Representation of a positive integer.

classmethod numeric_check(string)

Check that string is a positive integer (≥ 0).

Parameters:string (str) – A string to check.
class shellbot.ext.action_maths.NNType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Representtion of a nonzero positive integer.

classmethod numeric_check(string)

Check that string is a nonzero positive integer (> 0).

Parameters:string (str) – A string to check.

Syntax

This module provides actions handling generic strings and syntax.

class shellbot.ext.action_interpreter.RandSlots(data)

Parse a string following the pattern a:b:n, where a, b and n are optional integers with possible parenthesis around (e.g. (-1) or (2)).

classmethod size()

The number of slots.

classmethod sanitize(data)

Clean all slots in data and return an interpretable version it.

Parameters:data (str) – A string to sanitize.
classmethod type(_)

Return the slot transformation to apply on the parsed string. Transformations are shellbot.ext.action_maths.ZZType.feed().

Parameters:index (int [unused]) – A slot index.
classmethod default(index)

Return the slot default value.

  • Index 01.
  • Index 16.
  • Index 21.
Parameters:index (int) – A slot index.
class shellbot.ext.action_interpreter.RandIntSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Range syntax checker of Arguments associated data type.

classmethod feed(string)

Return an instance of RandSlots based on string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string can be split into three slots whose values are all integers and such that the last slot is a nonzero positive integer.

Parameters:string (str) – A string to check.
class shellbot.ext.action_interpreter.DiceMatch(data)

Parse a string following the rules given in dice command documentation.

n

int – The number of dices.

limit

int – The number of faces.

sign

int – The operator sign.

index

str – The operator value.

operator

str – The operator group.

post_action

callable – The post transformation.

class shellbot.ext.action_interpreter.DiceSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Dice syntax checker of class:DiceMatch associated data type.

classmethod feed(string)

Return an instance of DiceMatch based on string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string can be passed to DiceMatch.

Parameters:string (str) – A string to check.
class shellbot.ext.action_syntax.ComponentMatch(data)

Parse a string following the rules given in chmod command documentation.

prog

str – The name of the component (command or plugin name).

scope

str – The action scope.

syntax

str – The syntax object.

class shellbot.ext.action_syntax.TextSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Generic text type.

classmethod feed(string)

Return the string itself.

class shellbot.ext.action_syntax.ComponentSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
classmethod feed(string)

Return an instance of ComponentMatch based on string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string can be passed to ComponentMatch.

Parameters:string (str) – A string to check.
class shellbot.ext.action_syntax.WordSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Single word string type.

classmethod check(string)

Check that string is an alphabetic word.

Parameters:string (str) – A string to check.
class shellbot.ext.action_syntax.WeakWordSyntax(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Single word string type but with some accepted characters.

classmethod check(string)

Check that string only contains alphabetic characters, spaces or &.

Parameters:string (str) – A string to check.

Time formats

This module provides actions handling time objects or time formats following a specific syntax.

class shellbot.ext.action_time.TimeData(data)

Parse a string following the rules given in sleep command documentation for the time parameter.

value

float – An hour converted into seconds.

class shellbot.ext.action_time.TimeType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Simple time type (syntax now or hh:mm:ss).

classmethod feed(string)

Return an instance of TimeData based on string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string satisfies TimeData.has_match().

Parameters:string (str) – A string to check.
class shellbot.ext.action_time.TimeExpression(data)

Parse a string satisfying the rules of the delay or dt parameters given in sleep command documentation.

value

float – The time value.

unit

py314.unit.Unit – A temporal unit class.

class shellbot.ext.action_time.TimeExpressionType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

A string describing a time value, following an implemented syntax.

classmethod feed(string)

Return an instance of TimeExpression based on string.

Parameters:string (str) – A string satisfying check().
classmethod check(string)

Check that string satisfies TimeExpression.has_match().

Parameters:string (str) – A string to check.
class shellbot.ext.action_time.DelayType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Delay time type (syntax +<value><format>).

classmethod check(string)

Check that string satisfies TimeExpression.has_match() and is prefixed by a + character.

Parameters:string (str) – A string to check.
class shellbot.ext.action_time.DurationType(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Duration time type (syntax =<value><format>).

classmethod check(string)

Check that string satisfies TimeExpression.has_match() and is prefixed by an = character.

Parameters:string (str) – A string to check.

Parsing and context

This module provides classes describing positional or optional parser arguments and factory classes and methods to help in the construction of specific actions.

Keyword arguments passed to argparse.ArgumentParser.add_argument() are referred in this document as parser attributes.

class shellbot.ext.options.TypeInfo

Enumeration for positional or optional parser argument.

POS

Positional arguments are characterized by the fact that they lack an argument prefix char.

A positional argument has a default default value set to None if the CommandOption constructor lacks the default keyword.

OPT

Optional arguments are characterized by the presence of an argument prefix char in their names.

By convention, an optional argument is always a weak option, i.e. it has a default default value set to SUPPRESS. In particular, the destination namespace is populated only with the optional arguments that are explicitly given.

This is implemented as such so that the default values is defined by the callback command instead of the argument itself.

Note

The difference between a positional and an optional argument lies in the way the destination namespace is populated. There always exists an entry in the namespace associated with the non-weak positionals options, yet only explicitly given optional arguments will be present.

class shellbot.ext.options.CommandOption(name, typeinfo, **attrs)

Base class for a command option. Keyword arguments are keyword arguments passed to argparse.ArgumentParser.add_argument(). In this document, they are referred as parser attributes.

Parameters:
  • name (str) – The full command option name.
  • typeinfo (TypeInfo) – The option type info.
name

str – The option name.

typeinfo

TypeInfo – The option type.

aka

str – The command alias if any.

qualifiers

set – A set containing the option name and an optional alias.

is_special

bool – The option name is a flag name or not.

clean_name

str – The argument name without prefix if possible.

data

dict – Dict of attributes that can be passed as keyword arguments for argparse.ArgumentParser.add_argument().

set_alias(alias)

Define the (unique) alias for the current argument.

Parameters:alias (str) – The argument alias.
set_doc(config)

Define the (unique) help message for the current argument.

Parameters:config (dict) – The command options config.
set_destination(dest)

Define the (unique) destination variable.

Parameters:dest (str) – The destination variable name.
class shellbot.ext.options.Attributes

Factory class to make parser attributes as dict associating valid parser attributes for CommandOption with some pre-defined values.

classmethod suppress()

Make parser attributes describing a weak CommandOption via the arrow default → SUPPRESS.

Returns:Keyword default for CommandOption.

See also

TypeInfo

classmethod required()

Make parser attributes dict for a required positional option via the arrows action → store and nargs → 1 and such that the value is not a list (flatten).

Returns:Keywords action and nargs for CommandOption
classmethod const(constant)

Make parser attributes dict for a store_const action via the arrows action → store_const and const → constant.

Returns:Keywords action and const for CommandOption.
classmethod enable()

Make parser attributes dict for a weak store_true action.

Returns:Keywords action and default for CommandOption.

See also

TypeInfo

classmethod disable()

Make parser attributes dict for a weak store_false action.

Returns:Keywords action and default for CommandOption.

See also

TypeInfo

classmethod gather(required)

Define a gather action which is a composition of an append with a str.join() of the list.

Returns:Keywords action and nargs for CommandOption.
classmethod add_suppress(attrs)

Update a single arrow action → SUPPRESS with attrs if attrs is a dict or with action → attrs otherwise, and return it.

Parameters:attrs (Union[object, dict]) – An action or parser attributes.
Returns:Keyword arguments for CommandOption.

See also

TypeInfo

classmethod parse_attrs(attrs)

If attrs is not a dict, return a dict whose unique arrow is action → attrs; otherwise return attrs unchanged.

Parameters:attrs (Union[object, dict]) – An action or keywords passed to CommandOption.
class shellbot.ext.options.XORGroup(*options, **kwargs)

Represent a group of mutually exclusive optional arguments.

Positional arguments are instances of CommandOption that are then directly added to the group without modification. It is expected that the options have CommandOption.typeinfo set to TypeInfo.OPT.

For each arrow of keyword arguments key → attrs such that attrs is not a dict, redefine attrs to be action → attrs, and then, for all arrows, add the option CommandOption(name, TypeInfo.OPT, **attrs) to the mutually exclusive group, where name is key prefixed with -- if key[0] is a letter and key otherwise.

Parameters:*options – Instances of CommandOption.
__contains__(name)

Determine whether name is an existing full option name.

__iter__()

Return an iterator over the options instances.

classmethod from_attrs(attrs, *names)

Call the XORGroup constructor with keyword arguments defined by name → attrs as name ranges over names.

Parameters:attrs (dict) – Common parser attributes passed to Optional.
class shellbot.ext.options.UnaryFlag

A factory to construct inclusive or exclusive optional arguments behaving like positive and negative flags (+/-).

classmethod names(name)

Return the positive and negative literal names for name.

Parameters:name (str) – The common option name.
classmethod bool_exclusive(name)

Make a XORGroup of two members representing a positive and a negative flag named +name and -name. The option action is given by Attributes.enable() and Attributes.disable() and the destination variable name is set to name, for the options are mutually exclusive.

Parameters:name (str) – The common option name.

Example

p, n = bool_exclusive('x')

# attrs = {'default': SUPPRESS, 'dest': 'x'}
# typeinfo = TypeInfo.OPT
# p = CommandOption('+x', typeinfo, action='store_true', **attrs)
# n = CommandOption('-x', typeinfo, action='store_false', **attrs)
classmethod inclusive(name, attrs, *, p_dest='p%s', n_dest='n%s')

Make two CommandOption instances of TypeInfo.OPT typeinfo describing inclusive positive and negative flags.

The parser attributes dictionary for the positive (resp. negative) flag is given by attrs and the two arrows default → SUPPRESS and dest → d, where d is p_dest % name (resp. n_dest % name).

Parameters:
  • name (str) – The common option name.
  • attrs (dict) – Common parser attributes passed to Optional.
  • p_dest (str [optional]) – A format string for the + destination variable.
  • n_dest (str [optional]) – A format string for the - destination variable.
Returns:

A pair of CommandOption instances.

Examples

tp = TypeInfo.OPT
attrs = { 'default': SUPPRESS }

p0, n0 = inclusive('x', {'nargs': 1})
# p0 = CommandOption('+x', tp, nargs=1, dest='px', **attrs)
# n0 = CommandOption('-x', tp, nargs=1, dest='nx', **attrs)

p1, n1 = inclusive('x', {}, p_dest='%s_200', n_dest='%s_403')
# p1 = CommandOption('+x', tp, dest='x_200', **attrs)
# n1 = CommandOption('-x', tp, dest='x_403', **attrs)
classmethod from_attrs(name, p_attrs, n_attrs)

Make two CommandOption instances of TypeInfo.OPT typeinfo describing inclusive positive and negative flags whose names are given by +name and -name and parser attributes dictionaries by p_attrs and n_attrs.

Parameters:
  • name (str) – The common option name.
  • p_attrs (dict) – Parser attributes for the positive flag.
  • n_attrs (dict) – Parser attributes for the negative flag.
Returns:

A pair of CommandOption instances.

parser module

class shellbot.ext.parser.UNIXParser(specs, manual)

An UNIX parser-like but for ShellBot commands.

Parameters:
classmethod enable_timeit_strategy()

Decorate some methods with WithTimeitPolicy.wraps().

classmethod disable_timeit_strategy()

Remove the timing decorators.

generate_rstdoc()

Generate the reStructured Text documentation for the command. This does not include the usage section, nor the epilog section. It only includes positional and optional arguments with their help.

error(message)

Raise an BadArgument exception.

Parameters:message (str) – The message to print.

Servers

class shellbot.server.model.Server(parent, sql, plugins)

Provide information about Discord servers the bot client is connected to.

Parameters:
dispatch(name, description=None, cause=None)

Dispatch an event named name caused by cause.

id

int – The Discord server’s id.

name

str – The Discord server’s name.

channels

list [discord.TextChannel] – Textual channels.

default_channel

discord.TextChannel – A default channel if any.

has_plugin(shared, bypass=False)

Return True if this server accepts a plugin whose name is given by the name attribute of shared. If shared has a state attribute that is disabled, then the server does not accept the plugin either.

Parameters:
  • shared (SharedView) – A plugin shared view.
  • bypass (bool [optional]) – Bypass non-sysadmin disabled state check.
has_command(command, channel, bypass=False)

Return True if the channel accepts the command.

Parameters:
  • command (Command) – The command to check.
  • channel (discord.TextChannel) – The channel where to search.
  • bypass (bool [optional]) – Bypass blacklist check.
update_component(component, state, scope=None, *, quiet=True)

Change the state of component to state for the given scope.

Parameters:
  • component (Component) – The component to update.
  • state (State) – New component state.
  • scope (discord.TextChannel [optional]) – Channel where the component is to be updated if any.
  • quiet (bool [optional]) – Silence exceptions.
Raise:

BadState – Modifications failed.

Note

The scope and quiet parameters are unused for plugins.

clear_blacklist(scope=None)

Remove blacklisted commands and channels on the server.

Parameters:channel (discord.TextChannel [optional]) – Channel whose blacklist is to be cleared.
has_role(primary_key)

Return whether primary_key is a valid role’s primary key.

get_role(primary_key, default=None)

Return the role attached to the primary_key.

Parameters:
  • primary_key (int) – Role primary key.
  • default (Role [optional]) – Role to return if primary_key does not exist.
Returns:

The associated Role if any.

in_group(member, group)

Return whether member role’s GID is gid or not..

Parameters:
  • member (discord.Member) – A server member.
  • group (GID) – A group ID.
register_role(role)

Add a new role to the customized roles.

Parameters:role (Role) – A new role to add.
set_role(member, primary_key)

Change the permissions for a specific server member.

Parameters:
  • member (discord.Member) – The user to change the permissions of.
  • primary_key (int) – The role’s primary key.
inspect(member)

Return the member’s role if possible. A member that is not in the member roles collection has an User role (primary_key = 1).

Parameters:member (discord.Member) – The user to get the permissions of.

:return; The Role of the member if any.

compare_role(r1, r2, strict=False)

Check that r1 has as at least as many permissions as r2. If strict is True, check a strict inequality.

This compares the GID and not the commands that are denied or allowed for each role. A role that has no parent inherits by default the -1 gid and is always below anything.

import_configuration(exporter)

Redefine the current server’s configuration from exporter.

Parameters:exporter (Exporter) – The exporter object.
on_user_join_fill(member)

Return the JOIN message with filled placeholders or None.

on_user_quit_fill(member)

Return the LEAVE message with filled placeholders or None.

locks

py314.pattern.behavioral.lock.MultiLock – Server locks.

is_ready()

Return True if the server accepts bot interaction.

load_blacklist()

Load the command blacklist from database and skip the channels that do not exist anymore on the server.

load_roles()

Load the customized roles from the SQL database.

save()

Update the SQL Database with the current server data.

reload()

Reload some or all possible attributes from the database.

reset()

Reset the public fields of the server configuration.

delete()

Fully delete the server and all logs.

change_owner(before, after)

Delegate to the change_owner() method to change the owner roles.

class shellbot.server.model.ServerSet

An associative array of servers IDs and Server instances.

has(key)

Check that key is a valid server ID.

resolve(server_id, default=None)

Return the Server associated with the identifier if any.

Parameters:
  • identifier (int) – A server ID or guild instance.
  • default (object [optional]) – The default value to return.
random()

Return a random instance of Server.

destroy(guild)

Delete the server from the database and from this set.

Parameters:guild (discord.Guild) – A valid Discord guild.
register(server)

Attempt to register a server and replace existing servers.

Parameters:server (Server) – The server to register.
Raise:KeyError – The server is already registered.
coroutine load_server(bot, parent)

Load a server from bot and parent and return it.

Parameters:
  • bot (ShellBotClient) – A parent bot.
  • parent (discord.Server) – Discord Server.
Returns:

The registered Server.

save_all()

Call Server.save() on all servers.

update_all()

Call Server.update() on all servers.

reload_all()

Call Server.reload() on all servers.

class shellbot.server.role.Role(primary_key, group, name=None, commands=None)

The primary_key and group help to uniquely identify a Role within a same server.

Integers from 0 to 5 are reserved for default roles that are in fact defined to be different shellbot.enums.GID groups wrapped inside a Role for convenience. Therefore, these integers denote a valid role primary key as well as their associated group.

If the group argument is not an GID instance, it is converted into one to ensure a coherent and portable type.

Parameters:
  • primary_key (int) – The unique role id.
  • group (GID) – The group role (GUEST, USER, ORDINAL, ADMIN).
  • name (str [optional]) – A role name (default: group name).
  • commands (set [optional]) – A set of allowed commands.
is_above(role, strict=False)

Return whether the current role is higher or not in the GID hierarchy than role_or_gid. The comparison can be strict or not, depending on the strict parameter.

Parameters:
  • role (Role) – A role.
  • strict (bool [optional]) – Force strict comparisons.
in_group(group, strict=False)

Compare strictly or not the current role’s group with group.

Parameters:
  • group (GID) – A group.
  • strict (bool [optional]) – Force strict comparisons.
allows(command)

Check that the role has permissions to execute command. If the set of commands for this role is None, always allows the command. If the set of commands for this role is an empty set, deny it.

conform()

Return a dictionary, serializable through marshal.

class shellbot.server.role.MemberRoles(owner=None)

A mapping whose key are users ID and values are server Role.

Parameters:owner (discord.Member) – Optional server owner.
has(member)

Check if member has an associated role.

get(member, default=None)

Return the role associated with member or default.

Parameters:
  • member (discord.Member) – A Discord guild member.
  • default (object [optional]) – Value to return if there is no associated role.
register(member, role)

Register a member with a new role. Any previous role is replaced.

Parameters:
  • member (discord.Member) – A Discord guild member.
  • role (Role) – A role to associate with.
register_owner(owner)

Register an owner with an OWNER role given by Role(4, 4).

Parameters:owner (discord.Member) – A Discord guild owner.
change_owner(before, after)

Revoke owner role for before and grant owner role for after.

Parameters:
discard(member)

Remove the member from the set if it belongs to; otherwise do nothing.

Parameters:member (discord.Member) – A Discord guild member to remove.
conform()

Convert the current instance to a marshal-dumpable data.

classmethod converter(blob)

Return an instance of MemberRoles constructed from blob, which is a serialized dict whose keys are users ID and values are dictionary obtained from Role.conform().

Parameters:blob (bytes) – An SQL BLOB object.
class shellbot.server.role.ServerRoles

A mapping whose key are expected to be integers denoting a primary key and values are instances of Role.

has(role_or_primary_key)

Determine if role_or_primary_key has an associated role.

Parameters:role_or_primary_key (Union[int, Role]) – A role or a primary key.
get(role_or_primary_key, default=None)

Return the role associated with role_or_primary_key or default.

Parameters:
  • role_or_primary_key (Union[int, Role]) – A role or a primary key.
  • default (object [optional]) – Value to return if there is no associated role.
register(role)

Register a new role.

Parameters:role (Role) – The role to register.
discard(role_or_primary_key)

Remove the member from the set if it belongs to; otherwise do nothing.

Parameters:role_or_primary_key (Union[int, Role]) – A role or a primary key to remove.
conform()

Convert the current instance to a marshal-dumpable data.

classmethod converter(blob)

Return an instance of ServerRoles constructed from blob, which is a serialized list whose values are dict obtained from Role.conform().

Parameters:blob (bytes) – An SQL BLOB object.
class shellbot.server.config.Exporter(source, *, author, roles=False)

A configuration exporter controller.

Parameters:
  • source (Server) – The server’s model.
  • author (discord.Member) – The author of this configuration.
date

datetime – The configuration’s date.

record

Export the configuration with roles or not.

source

The original server where the configuration comes from.

class shellbot.server.config.ServerConfiguration(data)

A server configuration model.

See welcome_ and goodbye_ for the welcome and goodbye messages.

Parameters:data (sqlite3.Row) – The SQL row record.
from_conformed(**kwargs)

Construct an instance from data obtained via conform().

Identity cls.from_conformed(self.conform()) = self is always true.

reset_stderr()

Forget the standard error channel.

reset_job()

Remove the sleeping task.

verbosity

Servlogs – Verbosity logging level.

class shellbot.server.events.ServerEvent(name, message=None)

A server event whose formatted string is [name]: instance.

Parameters:
  • name (Servlogs) – The event name.
  • message (str [optional]) – Message to log.
name

str – The event name.

class shellbot.server.events.ServerEventDispatcher(service)
Parameters:service (py314.pattern.behavioral.publish_subscribe.Service) – A service.
dispatch(name, description=None, cause=None)

Dispatch an event named name caused by cause.

class shellbot.server.events.ServerSubscriber(name, service, logger, level)

Server event subscriber.

Parameters:
process(event)

Log a formatted string describing the server event.

Parameters:event (ServerEvent) – An event to log.
class shellbot.server.events.ServerLogger(sid, verbosity)

A server logger.

Parameters:
  • sid (int) – A server ID.
  • verbosity (int) – A minimum logging verbosity.
update()

Close the current logger and create a new handler if needed.

log(level, content)

Log some message with some logging level.

Parameters:
  • level (int) – The logging level.
  • content (str) – The message to log.
  • cause (object [optional]) – Something that did something.
fetch(date=None, compressed=False)

Return a str containing the path of the current logfile.

class shellbot.server.enums.Servlogs

Server logging events enumeration.

classmethod adapter()

Return the enumeration value.

classmethod converter(blob)

Convert a blob into a GID object via Servlogs(int(blob)).

DEFAULT

An upper bound denoting the maximum logging level for default events. The default events are the following ones.

PARENT_CHANGED

Parent server has been updated.

CONF_RESET

ShellBot server configuration has been reset.

CONF_UPDATE

ShellBot server configuration has been updated.

PARENT

An upper bound denoting the maximum logging level for parent events. The parent events are the following ones.

USER_JOINED

An user joined the server.

USER_LEFT

A server member left.

NEW_CHANNEL

A channel has been created.

DEL_CHANNEL

A channel has been deleted.

MODS

An upper bound denoting the maximum logging level for mods events. The mods events are the following ones.

BANISHED

A member has been banished by the ShellBot or a moderator.

UNBANNED

An user has been granted access again by the ShellBot.

KICKED

A member has been kicked by the ShellBot or a moderator.

MUTED

A member or a channel has been muted by the ShellBot

UNMUTED

A member or a channel has been unmuted by the ShellBot

PRESENCE

An upper bound denoting the maximum logging level for presence events. Presence updates are logged when a member changes its status and the following values describe the valid states.

LOGIN
LOGOUT
AVAILABLE
BUSY
IDLE
ALL

The maximal verbosity value. All previous events are logged.

class shellbot.server.enums.GID

Group permissions enumeration.

classmethod adapter()

Return the enumeration value.

classmethod converter(blob)

Convert a blob into a GID instance via GID(int(blob)).

GUEST

Permission assigned to a member that cannot use commands.

USER

Permission assigned to a member that can use default commands. This is the default group permissions for any member.

ORDINAL

Permission assigned to a member that can use default and some moderation commands.

ADMIN

Permission assigned to a member that can use all commands, except those that require superuser privileges.

OWNER

Permission assigned to the server owner.

class shellbot.server.enums.ServerBits

An enumeration.

class shellbot.server.job.ServerJob(start=None, stop=None)

Future sleep task.

start

float – The timestamp in seconds for the start point.

stop

float – The timestamp in seconds for the start point.

now

float – The timestamp in seconds for the last update.

literals

tuple – The tuple literal_start, literal_stop.

literal_start

str – Starting time point message.

literal_stop

str – Ending time point message.

set_points(start, stop)

Schedule a sleep task with the given parameters.

update()

Update now, check that it belongs to the current time interval and reset the start and stop points if needed.

cancel()

Cancel the current sleeping task.

is_degenerate()

Check that the time points are defined.

is_running()

Check that interval is not degenerated and contains current time.

conform()

Convert the current instance to a marshal-dumpable data.

class shellbot.server.record.ServerConfigRecord(record=None)

A server configuration SQL record.

server_id

int – Server ID.

prefix

str – Server command prefix.

verbosity

Servlogs – Server logging level.

listener_states

int – Listener states convertible to binary output.

stderr_id

int – Standard error channel ID.

server_job

ServerJob – The sleeping task.

locale

str – The server localization.

user_join_message

str – Message to send when users join.

user_quit_message

str – Message to send when users quit.

Message and Interactions

An event is defined by the following property: any event must be constructible from a Discord Server and a Discord Guild member. Private messages are not handled by the following modules and must be therefore specifically treated.

Messages

class shellbot.message.PrefixType

An enumeration.

shellbot.message.parse_message(expression, server_prefix)

Partition expression with respect to the server_prefix and return a triplet of strings containing the command name, command body and a member of PrefixType describing the prefix type.

Parameters:
  • expression (str) – The expression to parse.
  • server_prefix (str) – Server prefix.
shellbot.message.is_valid_abstract_message(m)

Check that the message can be considered as an abstract message.

Parameters:m (discord.Message) – A Discord message.
class shellbot.message.Invoker(subject, permissions, role)

A command invoker member.

Parameters:
  • subject (discord.Member) – The parent user.
  • permissions (PermissionsRecord) – The user permissions.
  • role (Role) – The member’s role.
superuser

Return True if the invoker is (temporarily) a superuser.

promote()

Temporarily grants the invoker superusers privileges.

demote()

Temporarily removes the invoker superusers privileges.

class shellbot.message.StreamState(wake_up, prefix_type, policy)

Represent message’s attribute states for transition.

Parameters:
  • wake_up (bool) – The mentioned user ID matches the client ID.
  • prefix_type (PrefixType) – A superuser user prefix is present.
  • policy (bool) – Mentions are required on the server.
wake_up

bool – The mentioned user ID matches the model.

prefix

bool – The prefix is valid.

invoker

bool – Check for an user or a su transition.

su

bool – A superuser prefix exists and wake_up is valid.

user

bool – The command prefix matches the server prefix and no sudo prefix is present.

command

bool – Check the prefix and the invoker transitions.

class shellbot.message.ParentMessage(parent, server)

A Discord message wrapper.

Parameters:
parent

discord.Message – The associated Discord message.

content

str – The message content.

author

discord.Member – The message’s author.

channel

discord.TextChannel – The message’s text channel.

server

Server – The attached server.

data

Tuple[discord.Member, discord.TextChannel, Server] – Public data.

coroutine delete()

Delete the record and the parent message.

class shellbot.message.MessageRecord(superid, parent, server, invoker)

Represent a message event coming from a registered Discord server and from any discord.Member (and not just discord.User) that may denote a command message (that is, either the prefix is valid or there is an explicit mention for the bot).

Parameters:
  • superid (int) – The Client Discord ID.
  • parent (discord.Message) – The message to attach to this event.
  • server (Server) – The server attached to this event.
  • invoker (Invoker) – The command invoker.
invoker

Invoker – The command invoker.

accepted

bool – Describe whether the record is valid or not.

user_transition

bool – The transition is done as an user or not.

invoked_with

str – The command name if any.

parse_args()

Return a list containing the arguments present in the message.

exception

InternalError – Optional exception.

throw(exception)

Define an internal error for this record.

Parameters:exception (InternalError) – Exception to set.
format_exception()

Return the formatted exception attached to this record.

logs

str – Formatted log record.

Context

class shellbot.context.Context(bot, record, command, args)

Represent the context in which a command is being invoked under and some properties refer to MessageRecord’s.

Parameters:
  • bot (ShellBotClient) – A reference to the ShellBot.
  • record (MessageRecord) – The Discord message wrapper.
  • command (Command) – The command that got invoked.
  • args (list) – The parsed record arguments.
contains_help()

Return True if the context contains an help option.

message

Resolve shellbot.message.ParentMessage.parent property.

author

Resolve shellbot.message.ParentMessage.author property.

invoker

Resolve shellbot.message.MessageRecord.invoker property.

voice_data

Tuple[discord.VoiceChannel, discord.VoiceClient] – Public voice context data.

has_voice()

Check that the invoker’s voice channel is not None.

voice

discord.VoiceState – Author’s voice state if any.

voice_channel

discord.VoiceChannel – Author’s voice channel if any.

voice_client

discord.VoiceClient – Server voice client if any.

channel

Resolve shellbot.message.ParentMessage.channel property.

server

Resolve shellbot.message.ParentMessage.server property.

data

Resolve shellbot.message.ParentMessage.data property.

Interactive messages

Messages may have an interactive user interface, such as pages navigation or votes. The following modules implement those functionalities.

analysis module

class shellbot.analysis.AnalyzedView(message, *, peer=None)

Analyzed message with reactions. Emojis with no callbacks are ignored. Callbacks are py314.callback.Function instances.

The internal data is an py314.volatile.Volatile object and its max age is usually 600 seconds (10 minutes).

Parameters:
  • message (discord.Message) – The parent message that acts as a book view.
  • peer (discord.Member [optional]) – Deny interaction from other members, but them.
register(emoji, callback, *args, **kwargs)
coroutine initialize()

Clear all reactions if needed and add default ones..

coroutine edit(content)

Edit the message with content.

Parameters:content (str) – The new content to replace the message with.
coroutine edit(embed)

Overload edit() for discord.Embed objects.

Parameters:embed (discord.Embed) – The new embed to replace the message with.
coroutine delete()

Delete the message and delete the attribute.

coroutine on_reaction_add(reaction, member)

Analyze the reaction from member and execute a callback associated with the reaction if any.

Parameters:
coroutine on_reaction_remove(reaction, member)

Analyze the reaction from member and execute a callback associated with the reaction if any.

Parameters:
coroutine on_timeout()

Execute a callback when a timeout occurs.

check_reaction(reaction, member)

Check that reaction from member is accepted and lock is released.

If the message is not for everyone and the member that reacts to is not the expected author, then the reaction is ignored, yet kept.

Parameters:
coroutine add_reaction(emoji)

Add a reaction coming from the client.

Parameters:emoji (str) – The emoji to add.
coroutine remove_reaction(emoji, member=None)

Remove a reaction from a specific member or from oneself.

Parameters:
  • emoji (str) – The emoji to remove.
  • member (discord.Member [optional]) – An optional reaction’s author.
class shellbot.analysis.BookView(message, pages, *, peer=None)

Implement a paginator that queries the user for the pagination interface.

Parameters:
class shellbot.analysis.ImageView(message, *, threshold=3)

An embed view message that can be deleted after some votes.

An ImageView instance is public, hence there is no receiver. Still, there may be receiver in the message, if for instance the latter is constructed via Embed.

Parameters:threshold (int [optional]) – Minimal amount of (+1) to avoid automatic image deletion.

interactive module

class shellbot.interactive.Waiter(func, location, timeout, peer=None, check=None)

A listener waiting for an event on a specific location to occur and such that a check, evaluated on the messages, is satisfied.

Waiting for an answer is delegated to discord.Client.wait_for() and thus the waiter parameter is essential. To give more flexibility, it is possible to parse only messages from a whitelisted author, defined via the peer parameter. Complex predicate can be provided through check.

Parameters:
class shellbot.interactive.InteractiveQuery(content, *args, on_timeout=None, **kwargs)

An InteractiveQuery is a question sent on a guild channel and a listener, waiting for an answer which triggers optional callbacks.

An internal py314.callback.ChainMap instance holds the callbacks to execute after a specific answer. All the undocumented keyword arguments pass to the constructor of the chain map.

All positional arguments but content yield an Waiter instance.

An on_timeout callback can be executed when a timeout occurs before an answer is given.

Parameters:
  • content (str) – Message to send before waiting for an answer.
  • on_timeout (py314.callback.Function [optional]) – Callback to execute on timeout.
  • predicate (callable [optional]) – The predicate parameter to pass to waiter.
coroutine initialize()

Send the question.

coroutine listen()

Start the main listener.

register(key, callback, *args, **kwargs)

Surrogate for py314.callback.ChainMap.register().

coroutine run()

A helper for initialize() and listen().

remove(key)

Surrogate for py314.callback.ChainMap.remove().

Enumerations

class shellbot.enums.State

Enumeration containing two flags used for an enabled and disabled state.

States are represented by integers and not booleans.

DISABLED

Field representing a DISABLED state. Bool evaluation to False.

ENABLED

Field representing an ENABLED state. Bool evaluation to False.

NEGATIVE

Alias for NEGATIVE.

POSITIVE

Alias for ENABLED.

class shellbot.enums.Scope

Default, user, channel, server or global scopes.

DEFAULT

A default scope.

USER

An user scope. shell

CHANNEL

A channel scope.

SERVER

A server-wide scope.

GLOBAL

A Discord scope englobing all servers the bot belongs to.

class shellbot.enums.WWW

Discord permissions enumeration.

Exceptions

Generic exceptions

class shellbot.errors.InternalError

Exception base class.

class shellbot.errors.OperationWarning

Generic exception raised during processing operations.

Data consistency

class shellbot.errors.PrefixError

Exception raised when the given prefix cannot be used.

class shellbot.errors.NotFound

Generic exception for not found object.

Network errors

class shellbot.errors.HTTPError(error)

A network error describing a request’s error either builtins or constructed by the requests module.

Permissions errors

class shellbot.errors.PAMError

Exception raised when permissions checks fail.

class shellbot.errors.AuthFailure

Exception raised when authentication as a superuser failed.

State errors

class shellbot.errors.DaemonError

Generic exception raised when a service encountered an error.

class shellbot.errors.BadState

Exception raised when the state of a server, plugin, or command cannot be changed or when the data is unavailable.

Miscellaneous errors

class shellbot.errors.VoiceError

Exception for Voice Process errors.

Constant data

ShellBot constants are implemented in the shellbot.const module.

const module

shellbot.const.SUPPRESS

An alias for argparse.SUPPRESS. Avoid to import argparse.

shellbot.const.SU_PREFIX

A reserved token denoting superuser commands.

class shellbot.const.RESERVED

Reserved characters namespace.

Text formatting

shellbot.formats.mixins.format_permissions(rows)

Return a tuple of py314.formats.document.Document that describes rows.

Parameters:rows (list) – A list of permission records.
shellbot.formats.mixins.format_library(library)

Return a tuple of py314.formats.document.Document that describes library.

Parameters:library (Library) – A library of plugins.
shellbot.formats.mixins.format_servers(servers)

Return a tuple of py314.formats.document.Document that describes servers.

Parameters:servers (ServerSet) – A server set.

page module

shellbot.formats.page.paginate(cover, *pages)

Paginate all pages. The cover page is here to provide a type annotation.

Parameters:
shellbot.formats.page.paginate(message, *messages)

Overload paginate() for "shellbot.formats.messages.Message.

shellbot.formats.page.paginate(mapping, *mappings)

Overload paginate() for dict.

shellbot.formats.page.paginate(embed, *embeds)

Overload paginate() for discord.Embed.

Messages formatting

messages module

shellbot.formats.messages.get_mention(peer)

Return a mention string for peer if any.

Parameters:peer (discord.User) – A Discord user to mention.
shellbot.formats.messages.peered_message(content, peer=None, endl=False, *, fallback=Embed.Empty)

Format a content with the given parameters.

Parameters:
  • content (str) – The content to send.
  • peer (discord.User [optional]) – A Discord user to mention.
  • endl (bool [optional]) – Add an endline character after the mention if any.
  • fallback (str [optional]) – The text to return if content and peer are None.
class shellbot.formats.messages.Message

Prepare a message with the given arguments. If peer is given, append a string at the end containg a mention to peer and Request by.

If furthermore title is given, insert title and an endline character before the content.

Parameters:
  • body (str) – The message body.
  • peer (discord.User [optional]) – A Discord user to mention.
  • header (str [optional]) – A header to insert after the mention.
  • footer (str [optional]) – A footer to insert at the end of the text.

embeds module

class shellbot.formats.embeds.AuthorEmbed(name=Embed.Empty, url=Embed.Empty, icon_url=Embed.Empty)

Attributes holder for author embed field.

class shellbot.formats.embeds.FooterEmbed(text=Embed.Empty, icon_url=Embed.Empty)

Attributes holder for footer embed field.

copy()

Return a copy of this object.

shellbot.formats.embeds.embedize_message(text, peer=None, *, colour=15792383, endl=False)

Create an discord.Embed with description given by text.

class shellbot.formats.embeds.Embed(peer=None, *, colour=None, title=Embed.Empty, url=Embed.Empty, description=None, author=None, image=None, thumbnail=None, footer=None, inline=False, inlined=False, endl=False, **kwargs)

An discord.Embed created with the given parameters.

All parameters are optional. Explicit keyword arguments are described below and all other keyword arguments are considered as embed’s fields along with their content.

Parameters:
  • peer (discord.Member [optional]) – Describes the user to mention.
  • colour (hex [optional]) – Optional embed’s colour.
  • title (str [optional]) – Optional embed’s title.
  • url (str [optional]) – Optional keyword argument containing the embed’s url.
  • description (str [optional]) – Optional embed’s description.
  • author (AuthorEmbed [optional]) – Optional embed’s author.
  • image (str [optional]) – Optional embed’s image URL.
  • thumbnail (str [optional]) – Optional thumnail’s image URL.
  • footer (FooterEmbed [optional]) – Optional embed’s footer.
  • inlined (list [optional]) – A list of inlined fields identifiers.
  • inline (bool [optional]) – Inline the fields or not.
  • endl (bool [optional]) – Separate the mention from the rest of the body.

Miscellaneous

mixins module

class shellbot.mixins.Component(*, state=<State.ENABLED: 1>)

A ShellBot component with a runtime state attribute.

Parameters:state (State [optional]) – Default state.
state

State – Runtime component’s state.

enabled

bool – Component is globally enabled.

disabled

bool – Component is globally disabled.

enable()

Globally enable the component.

disable()

Globally disable the component.

toggle_state()

Toggle the current component’s state.

loggers module

class shellbot.loggers.FileLogger(name, filename)
log(level, msg, *args, **kwargs)

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

logger.log(level, “We have a %s”, “mysterious problem”, exc_info=1)

class shellbot.loggers.ErrorLogger(filename)
class shellbot.loggers.SecurityLogger(filename)

requests module

class shellbot.requests.BaseAPIClient

API Client meta class.

classmethod gather_error(error)

Analyze a possible error and raise an exception on error.

coroutine request(method, url, **kwargs)

Reimplement request() behaviour.