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.
-
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: - destination (
discord.abc.Messageable) – The destination to notify. - body (str) – The body message to send.
- style (
py314.formats.codeblock.Style[optional]) – Optional text style.
- destination (
-
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: - destination (
discord.abc.Messageable) – The destination the embed is to be sent to. - embed (
discord.Embed) – The embed object to send. - peer (
discord.User[optional]) – The user to mention.
- destination (
-
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: - destination (
discord.abc.Messageable) – The destination the content is to be sent to. - content (str) – Message to send.
Returns: The
discord.Messagethat was sent.- destination (
-
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
MessageRecordinstances are meant to be constructed using Discord servers and messages, this method must reply on a public server’s channel.Parameters: - record (
MessageRecord) – The record to reply to. - body (str) – Message body to send.
- style (
py314.formats.codeblock.Style[optional]) – Optional codeblock style. - override (bool [optional]) – Override security protocols.
Returns: The
discord.Messagethat was sent if any.- record (
-
coroutine
send(destination, body, delete_after=None, **kwargs)¶ Make a
Messagewith 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.Messagethat was sent.- destination (
-
coroutine
send_analyzed_embed(destination, *, peer=None, **kwargs)¶ Delegate to
Embedthe construction of adiscord.Embedsent to destination and enable voting analysis viaImageView.Parameters: - destination (
discord.abc.Messageable) – The destination the embed is to be sent to. - peer (
discord.Member[optional]) – Optional argument denoting the user to mention.
- destination (
-
coroutine
send_book(destination, pages, broadcaster, *, peer=None)¶ Send the output pages of
prepare_book()to destination via a suitable broadcaster.Parameters: - destination (
discord.abc.Messageable) – The destination the message is to be sent. - pages (tuple) – The output of
prepare_book(). - peer (
discord.Member) – A receiver member. - broadcaster (coroutine) – Coroutine used to send pages.
- destination (
-
coroutine
send_embed(destination, *, peer=None, **kwargs)¶ Delegate to
Embedthe construction of thediscord.Embedsent to destination.Parameters: - destination (
discord.abc.Messageable) – The destination the embed is to be sent to. - peer (
discord.User[optional]) – An user to mention.
- destination (
-
coroutine
send_embeds(destination, *messages, peer=None)¶ Send a book to destination via
send_book().A page in pages is expected to be a
dictwhich matches the signature ofEmbed, or an instance of the latter already.Parameters: - destination (
discord.abc.Messageable) – The destination the message is to be sent to. - peer (
discord.Member[optional]) – An optional receiver.
- destination (
-
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
Messageinstances.Parameters: - destination (
discord.abc.Messageable) – The destination the message is to be sent to. - peer (
discord.Member[optional]) – An optional receiver.
- destination (
-
coroutine
system_announce(content)¶ Send an administration message to all servers.
Parameters: - content (str) – The content to send.
- style (
py314.formats.codeblock.Style[optional]) – Optional text style. - mention (bool [optional]) – Mention everyone.
-
coroutine
wait_for(*args, **kwargs)¶ Proxy for the
discord.Client.wait_for()method.
-
classmethod
Internal Events¶
ShellBotClient.on_exception(location=None)¶Log a message where into the runtime logging file with a
FATALflag 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) – Adiscord.Messageof the current message.See also
- coroutine
ShellBotClient.on_message_delete(message)¶Called when a self (i.e. from the bot itself) message is deleted.
Parameters: message ( discord.Message) – Thediscord.Messagebeing 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:
- reaction (
discord.Reaction) – A reaction showing the current state of the reaction.- member (
discord.Member) – The user who added the reaction.See also
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.serverscache.Load a new instance of the server in the set of servers if needed.
Parameters: parent ( discord.Guild) – The guild that has changed availability.See also
Called when a parent server becomes unavailable. The server must have existed in the
discord.Client.serverscache.
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.Guildupdates, for example:
- Changed name
- Changed AFK channel
- Changed AFK timeout
- etc
Parameters:
- before (
discord.Guild) – The guild prior to being updated.- after (
discord.Guild) – The guild after being updated.
- coroutine
ShellBotClient.on_guild_join(parent)¶Called when either a
discord.Guildis either created by thediscord.Clientor thediscord.Clientjoins 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.Clientmust have been part of the server to begin with. (i.e. it is part ofdiscord.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.Guildcreates adiscord.Role.
Parameters: role ( discord.Role) – The role that was created.
- coroutine
ShellBotClient.on_guild_role_delete(role)¶Called when a
discord.Guilddeletes adiscord.Role.
Parameters: role ( discord.Role) – Thediscord.Rolethat was deleted.
- coroutine
ShellBotClient.on_guild_role_update(_, after)¶Called when a
discord.Roleis 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.See also
- 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.Memberjoins a server.
Parameters: member ( discord.Member) – The member that joined.
- coroutine
ShellBotClient.on_member_remove(member)¶Called when a
discord.Memberleaves a server.
Parameters: member ( discord.Member) – The member that left.
- coroutine
ShellBotClient.on_member_ban(guild, member)¶Called when a
discord.Memberis banished from a server.
Parameters:
- guild (
discord.Guild) – The guild the user got banned from.- member (
discord.Member) – The banished member.
- coroutine
ShellBotClient.on_member_unban(guild, user)¶Called when a
discord.Usergets unbanned from a server.
Parameters:
- guild (
discord.Guild) – The guild the user got unbanned from.- user (
discord.User) – The user that got unbanned from.
- coroutine
ShellBotClient.on_member_update(before, after)¶Called when a
discord.Memberchanges its Discord status.
Parameters:
- before (
discord.Member) – The member prior to being updated.- after (
discord.Member) – The member after being updated.
- coroutine
ShellBotClient.on_voice_state_update(member, *_)¶Called when a
discord.Memberchanges 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.See also
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 stmtstatement to execute
-
coroutine
status(_, action, value=None)¶ Brief Define Discord status. Usage status [set VALUE | reset]Options Description set VALUEtry to change presence and then status resetreset status to default status
-
coroutine
chgroup(user, prefix, gid, uid)¶ Brief Change user group. Usage chgroup <prefix> <gid> <rid>Options Description prefixeither ‘+’ or ‘-‘ for an up or down action gida valid group (blacklisted, sudo, root) uiduser id
-
coroutine
chmod(user, prefix, mode, name)¶ Brief Enable or disable command or plugin. Usage chmod <prefix> <mode> <name>Options Description prefixeither ‘+’ or ‘-‘ for an up or down action modeeither ‘c’ or ‘p’ for command or plugin mode namea command or plugin name Raise: CommandError.
-
coroutine
config(user, path, cast, value)¶ Brief Change credentials values. Usage config path [--cast CAST] <VALUE>Options Description paththe dictionary tree path --castbuiltins constructor string VALUEnew 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 namesecurity, error, all or a server ID lsfetch logs in T clearclear all .gz logs of server ID T clear-allclear all logs of server ID T
-
coroutine
ls(user, group)¶ Brief List specific collections. Usage ls <group>Groups Description cmdsthe Administration commands blcmdsblacklisted commands pluginsplugins serversservers usersusers with additional permissions blusersblacklisted users sudosuperusers rootroot 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 IDmessage 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 +denter DEBUG_MODE -dleave DEBUG_MODE +rleave RELEASE_MODE -rleave RELEASE_MODE -v Nchange verbosity to N timeout Nchange SQL timeout to N (-1 for none)
-
coroutine
systemd(user, action)¶ Brief Execute a systemd action. Usage systemd <action>Actions Description savesave the current state stopstop the Python script rebootrestart the Python script reloadreload configurations
-
coroutine
top(user, action=None)¶ Brief Display stats usage. Usage top --[cpu | memory | disk | uptime]Options Description --cpudisplay CPU usage --memorydisplay RAM usage --diskdisplay DISK usage --uptimedisplay bot uptime
-
coroutine
warn(_, location, message)¶ Brief Send an administration message. Usage warn [-g | -G | [id]] <message>Options Description -gmessage is sent everywhere -Gmessage is sent everywhere with @everyone IDmessage is sent to an explicit location ID Raise: CommandError.
-
coroutine
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: - shared (
SharedView) – Thesharedattribute. - callback (coroutine) – Command callback.
-
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
dictor 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.
- shared (
-
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()andexit()as the first and the last decorators respectively. Usedecorate()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 aCommandSpecsinstance 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.
-
classmethod
misc(*names, metaname=None, cooldown=<class 'py314.globals.SENTINEL'>, **kwargs)¶ Add a
MiscSpecsattribute 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:
-
classmethod
options(**kwargs)¶ Partialization of
specify()with name set to __options__ and typespecs toOptionsSpecs.
-
classmethod
permissions(**kwargs)¶ Partialization of
specify()with name set to __permissions__ and typespecs toPermissionsSpecs.
-
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
--argis-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
dictwith a single arrow field → value. - Arrow key → obj yields an arrow key → attrs, where attrs
is a
dictdefined to be either obj updated with the arrow field → value if obj is itself adict, or the associative array [field → value, action → obj] otherwise.
Raises: AssertionError– Duplicated arguments.- Positional arguments yield arrows key → attrs, where attrs
is a
-
classmethod
switch(*names)¶ Define optional
CommandOptionwhose names are given by names. The underlying parser attributes is given byenable.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
--fooand--bar.@commands.exit @commands.switch('foo', 'bar') @commands.enter async def my_command(ctx, *args, **kwargs): pass
Define the options
--fooand--barand a mutually exclusive group formed by--bazand--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_exclusiveto make mutually exclusive flags groups. A name in names is interpreted as a common flag name for a single group.Example
Mutually exclusive flags
+xand-xwith 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
inclusiveto make many inclusive flags groups. Each keyword is interpreted as the base flag name for a single group.Example
Inclusive flags
+xand-xwith 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
-
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
CommandOptioninstances withPOStypeinfo.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
CommandOptioninstances withOPTtypeinfo.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
--thiswith a default value set tothat@commands.exit @commands.optin(this={'default': 'that'}) @commands.enter async def my_command(ctx, *args, **kwargs): pass
-
classmethod
weak_optin(*args, **kwargs)¶ Define weak
CommandOptioninstances withOPTtypeinfo.Example
Define an option
--thiswith an action set toappend@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
-
classmethod
optex(*groups)¶ Add the optional exclusive arguments.
-
static
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: A
py314.globals.SENTINELcooldown 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.
-
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: - misc (
MiscSpecs) – Command miscellaneous meta-data. - options (
OptionsSpecs) – Command options meta-data. - permissions (
PermissionsSpecs) – Command permissions meta-data.
-
set_doc(manual)¶ Define help text for all options.
Parameters: manual ( CommandManual) – A command manual.
- misc (
Cooldowns and errors¶
-
class
shellbot.ext.cooldown.Cooldown(tokens, dt, scope)¶ A command cooldown object.
Parameters: -
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.
-
-
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
UNIXParserobject. Implement more actions in addition to those provided inargparse.The destination value is filled with the output of
adapter()and thus children classes must re-implement the internal methodfeed().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.destto 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
DataViewinstance 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 BadArgumentexception.
-
classmethod
-
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.
See also
-
__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
appendaction and then join them in a single string.See also
-
__call__(parser, namespace, values, option_string=None)¶ Call self as a function.
-
-
__weakref__¶ list of weak references to the object (if defined)
-
class
-
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()anddefault()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
hydrate(data)¶ Given a sanitized data, return a tuple of slot converted values.
Parameters: data (str) – A data passed through sanitize().See also
-
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().
-
classmethod
-
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.Patterninstance 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.Matchinstance 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 onDataView.data.
-
properties(*fields)¶ Return a tuple of properties in subclasses.
-
classmethod
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.
-
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.HTTPMethodinstances.-
classmethod
feed(string)¶ Return the member in
py314.requests.HTTPMethoddescribed by string.Parameters: string (str) – A string satisfying check().
-
classmethod
check(string)¶ Check that string contains a
py314.requests.HTTPMethodmember name (case insensitive check).Parameters: string (str) – A string to check.
-
classmethod
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.
-
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.
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
NoneorFalseis 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
floatconversion.Parameters: string (str) – A string satisfying check().
-
classmethod
-
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.
-
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.
-
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.
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
-
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
Argumentsassociated data type.
-
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.
-
-
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.
-
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.
-
classmethod
-
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
ComponentMatchbased 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.
-
classmethod
-
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.
-
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.
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
noworhh:mm:ss).
-
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
TimeExpressionbased on string.Parameters: string (str) – A string satisfying check().
-
classmethod
-
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>).
-
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>).
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
Noneif theCommandOptionconstructor 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 option name.
-
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.
-
-
class
shellbot.ext.options.Attributes¶ Factory class to make parser attributes as
dictassociating valid parser attributes forCommandOptionwith some pre-defined values.-
classmethod
suppress()¶ Make parser attributes describing a weak
CommandOptionvia the arrow default → SUPPRESS.Returns: Keyword default for CommandOption.See also
-
classmethod
required()¶ Make parser attributes
dictfor 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
dictfor 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
dictfor a weak store_true action.Returns: Keywords action and default for CommandOption.See also
-
classmethod
disable()¶ Make parser attributes
dictfor a weak store_false action.Returns: Keywords action and default for CommandOption.See also
-
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
dictor with action → attrs otherwise, and return it.Parameters: attrs (Union[object, dict]) – An action or parser attributes. Returns: Keyword arguments for CommandOption.See also
-
classmethod
-
class
shellbot.ext.options.XORGroup(*options, **kwargs)¶ Represent a group of mutually exclusive optional arguments.
Positional arguments are instances of
CommandOptionthat are then directly added to the group without modification. It is expected that the options haveCommandOption.typeinfoset toTypeInfo.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.
-
-
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
XORGroupof two members representing a positive and a negative flag named+nameand-name. The option action is given byAttributes.enable()andAttributes.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
CommandOptioninstances ofTypeInfo.OPTtypeinfo 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: Returns: A pair of
CommandOptioninstances.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
CommandOptioninstances ofTypeInfo.OPTtypeinfo describing inclusive positive and negative flags whose names are given by+nameand-nameand parser attributes dictionaries by p_attrs and n_attrs.Parameters: Returns: A pair of
CommandOptioninstances.
-
classmethod
parser module¶
-
class
shellbot.ext.parser.UNIXParser(specs, manual)¶ An UNIX parser-like but for ShellBot commands.
Parameters: - specs (
CommandSpecs) – The associated command specifications. - manual (
CommandManual) – The command manual.
-
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
BadArgumentexception.Parameters: message (str) – The message to print.
- specs (
Servers¶
-
class
shellbot.server.model.Server(parent, sql, plugins)¶ Provide information about Discord servers the bot client is connected to.
Parameters: - parent (
discord.Guild) – The parent Discord server. - sql (
py314.sql.driver.SqlDriver) – A sql connection to the global database. - plugins (set) – A set of names of available plugins.
-
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
Trueif 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.
- shared (
-
has_command(command, channel, bypass=False)¶ Return
Trueif 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.
- command (
-
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.
- component (
-
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: Returns: The associated
Roleif 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.
- member (
-
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.
- member (
-
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
Roleof 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
Trueif 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.
- parent (
-
class
shellbot.server.model.ServerSet¶ An associative array of servers IDs and
Serverinstances.-
has(key)¶ Check that key is a valid server ID.
-
resolve(server_id, default=None)¶ Return the
Serverassociated with the identifier if any.Parameters:
-
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.- bot (
-
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
Rolewithin a same server.Integers from 0 to 5 are reserved for default roles that are in fact defined to be different
shellbot.enums.GIDgroups wrapped inside aRolefor convenience. Therefore, these integers denote a valid role primary key as well as their associated group.If the group argument is not an
GIDinstance, it is converted into one to ensure a coherent and portable type.Parameters: -
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:
-
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.
- group (
-
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 emptyset, 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.
- member (
-
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.
- member (
-
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: - before (
discord.Member) – The previous guild owner. - after (
discord.Member) – The current guild owner.
- before (
-
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
MemberRolesconstructed from blob, which is a serializeddictwhose keys are users ID and values are dictionary obtained fromRole.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:
-
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
ServerRolesconstructed from blob, which is a serializedlistwhose values aredictobtained fromRole.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.
- source (
-
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.
- 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: - name (str) – Subscriber’s name.
- service (
py314.pattern.behavioral.publish_subscribe.Service) – Service center. - logger (
ServerLogger) – AServerLoggerto log events. - level (
Servlogs) – Logging level.
-
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: -
update()¶ Close the current logger and create a new handler if needed.
-
log(level, content)¶ Log some message with some logging level.
Parameters:
-
-
class
shellbot.server.enums.Servlogs¶ Server logging events enumeration.
-
classmethod
adapter()¶ Return the enumeration value.
-
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.
-
classmethod
-
class
shellbot.server.enums.GID¶ Group permissions enumeration.
-
classmethod
adapter()¶ Return the enumeration value.
-
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.
-
classmethod
-
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.
-
listener_states¶ int – Listener states convertible to binary output.
-
stderr_id¶ int – Standard error channel ID.
-
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
PrefixTypedescribing the prefix type.Parameters:
-
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
Trueif the invoker is (temporarily) a superuser.
-
promote()¶ Temporarily grants the invoker superusers privileges.
-
demote()¶ Temporarily removes the invoker superusers privileges.
- subject (
-
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.
-
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 parent Discord message. - server (
Server) – A server wrapper.
-
parent¶ discord.Message– The associated Discord message.
-
content¶ str – The message content.
discord.Member– The message’s author.
-
channel¶ discord.TextChannel– The message’s text channel.
-
data¶ Tuple[
discord.Member,discord.TextChannel,Server] – Public data.
-
coroutine
delete()¶ Delete the record and the parent message.
- parent (
-
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 justdiscord.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.
-
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
Trueif the context contains an help option.
-
message¶ Resolve
shellbot.message.ParentMessage.parentproperty.
Resolve
shellbot.message.ParentMessage.authorproperty.
-
invoker¶ Resolve
shellbot.message.MessageRecord.invokerproperty.
-
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.channelproperty.
-
server¶ Resolve
shellbot.message.ParentMessage.serverproperty.
-
data¶ Resolve
shellbot.message.ParentMessage.dataproperty.
- bot (
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.Functioninstances.The internal data is an
py314.volatile.Volatileobject 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()fordiscord.Embedobjects.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: - reaction (
discord.Reaction) – The reaction that was added. - member (
discord.Member) – The member that adds the reaction.
- reaction (
-
coroutine
on_reaction_remove(reaction, member)¶ Analyze the reaction from member and execute a callback associated with the reaction if any.
Parameters: - reaction (
discord.Reaction) – The reaction that was removed. - member (
discord.Member) – The member that removes the reaction.
- reaction (
-
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: - reaction (
discord.Reaction) – The reaction that was added or removed. - member (
discord.Member) – The member that adds or removes the reaction.
- reaction (
-
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.
- message (
-
class
shellbot.analysis.BookView(message, pages, *, peer=None)¶ Implement a paginator that queries the user for the pagination interface.
Parameters: - pages (list) – List of
strordiscord.Embed. - peer (
discord.User[optional]) – Ignore all other members, but them.
- pages (list) – List of
-
class
shellbot.analysis.ImageView(message, *, threshold=3)¶ An embed view message that can be deleted after some votes.
An
ImageViewinstance is public, hence there is no receiver. Still, there may be receiver in the message, if for instance the latter is constructed viaEmbed.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: - func (coroutine) – Reference to
discord.Client.wait_for(). - location (
discord.TextChannel) – The location channel. - timeout (float) – Number of seconds to wait before timing out.
- peer (
discord.Member) – Whitelisted author. - check (callable [optional]) – A predicate on messages.
- func (coroutine) – Reference to
-
class
shellbot.interactive.InteractiveQuery(content, *args, on_timeout=None, **kwargs)¶ An
InteractiveQueryis a question sent on a guild channel and a listener, waiting for an answer which triggers optional callbacks.An internal
py314.callback.ChainMapinstance 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
Waiterinstance.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()andlisten().
-
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.
-
-
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.
See also
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.
Constant data¶
ShellBot constants are implemented in the shellbot.const module.
Text formatting¶
-
shellbot.formats.mixins.format_permissions(rows)¶ Return a
tupleofpy314.formats.document.Documentthat describes rows.Parameters: rows (list) – A list of permission records.
-
shellbot.formats.mixins.format_library(library)¶ Return a
tupleofpy314.formats.document.Documentthat describes library.Parameters: library ( Library) – A library of plugins.
-
shellbot.formats.mixins.format_servers(servers)¶ Return a
tupleofpy314.formats.document.Documentthat 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: - cover (Union[
Message,discord.Embed,dict]) – A suitable cover page. - *pages – The rest of the pages.
- cover (Union[
-
shellbot.formats.page.paginate(message, *messages) Overload
paginate()for"shellbot.formats.messages.Message.
-
shellbot.formats.page.paginate(mapping, *mappings) Overload
paginate()fordict.
-
shellbot.formats.page.paginate(embed, *embeds) Overload
paginate()fordiscord.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.
Attributes holder for footer embed field.
Return a copy of this object.
-
shellbot.formats.embeds.embedize_message(text, peer=None, *, colour=15792383, endl=False)¶ Create an
discord.Embedwith 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.Embedcreated 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.
- peer (
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.-
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)¶