API Reference¶
The following section outlines the API of stoat.py’s command extension module.
Bots¶
Bot¶
- def add_check
- def add_command
- async add_gear
- @ after_invoke
- def all_subscriptions
- @ before_invoke
- @ check
- @ check_once
- async close
- @ command
- async create_group
- async create_server
- def dispatch
- async fetch_channel
- async fetch_emoji
- async fetch_server
- async fetch_user
- def get_channel
- def get_command
- def get_emoji
- def get_gear
- async get_prefix
- def get_read_state
- def get_server
- def get_user
- @ group
- def listen
- async load_extension
- def on
- async on_command_error
- async on_library_error
- async on_user_error
- async reload_extension
- def remove_check
- def remove_command
- async remove_gear
- def run
- async setup_hook
- async start
- def subscribe
- def subscriptions_count_for
- def subscriptions_for
- async unload_extension
- async wait_for
- def walk_commands
- class stoat.ext.commands.Bot(command_prefix, *, description=None, self_bot=False, strip_after_prefix=False, user_bot=False, **options)[source]¶
Represents a Stoat bot.
- Parameters:
case_insensitive (
bool) –Whether the commands should be case insensitive. Defaults to
False.Added in version 1.2.
command_prefix (Union[MaybeAwaitableFunc[[
Context], List[str]], List[str],str]) – The command’s prefix.description (Optional[
str]) – The bot’s description.owner_ids (Set[
str]) – The bot owner’s IDs.self_bot (
bool) – Whether the bot should listen only to logged in user.skip_check (Optional[MaybeAwaitableFunc[[
Context],bool]]) – A callable that checks whether the command should skipped.strip_after_prefix (
bool) – Whether to strip whitespace after prefix. Setting this toTrueallows using! help. Defaults toFalse.user_bot (
bool) – Whether the bot should listen to everyone, including themselves.
- @after_invoke[source]¶
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it an useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a
Context.Note
Similar to
before_invoke(), this is not called unless checks and argument parsing procedures succeed. This hook is, however, always called regardless of the internal command callback raising an error (i.e.CommandInvokeError). This makes it ideal for clean-up scenarios.
- @before_invoke[source]¶
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it an useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a
Context.Note
The
before_invoke()andafter_invoke()hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.
- @check[source]¶
A decorator that adds a global check to the bot.
A global check is similar to a
check()that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.Note
This function can either be a regular function or a coroutine.
Similar to a command
check(), this takes a single parameter of typeContextand can only raise exceptions inherited fromCommandError.Example
@bot.check def check_commands(ctx): return ctx.command.qualified_name in allowed_commands
- @check_once[source]¶
A decorator that adds a “call once” global check to the bot.
Unlike regular global checks, this one is called only once per
invoke()call.Regular global checks are called whenever a command is called or
Command.can_run()is called. This type of check bypasses that and ensures that it’s called only once, even inside the default help command.Note
When using this function the
Contextsent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once perBot.invoke()call.Note
This function can either be a regular function or a coroutine.
Similar to a command
check(), this takes a single parameter of typeContextand can only raise exceptions inherited fromCommandError.Example
@bot.check_once def whitelist(ctx): return ctx.message.author_id in my_whitelist
- @command(*args, **kwargs)[source]¶
A shortcut decorator that invokes
command()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
Callable[…,
Command]
- @group(*args, **kwargs)[source]¶
A shortcut decorator that invokes
group()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
Callable[…,
Group]
- @listen(event=None, /)[source]¶
Register an event listener.
There is an alias for this called
on().Examples
Ping Pong:
@client.listen() async def on_message_create(event: stoat.MessageCreateEvent): message = event.message if message.content == '!ping': await message.reply('pong!') # It returns :class:`EventSubscription`, so you can do ``on_message_create.remove()``
- Parameters:
event (Optional[Type[EventT]]) – The event to listen to.
- @on(event=None, /)[source]¶
Register an event listener.
This is an alias of
listen().Examples
Ping Pong:
@client.on() async def on_message_create(event: stoat.MessageCreateEvent): message = event.message if message.content == '!ping': await message.reply('pong!') # It returns :class:`EventSubscription`, so you can do ``on_message_create.remove()``
- Parameters:
event (Optional[Type[EventT]]) – The event to listen to.
- await close(*, http=True, cleanup_websocket=True)[source]¶
This function is a coroutine.
Closes all HTTP sessions, and WebSocket connections.
- await on_command_error(event, /)[source]¶
This function is a coroutine.
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
- add_check(func, /, *, call_once=False)[source]¶
Adds a global check to the bot.
This is the non-decorator interface to
check()andcheck_once().See also
The
check()decorator- Parameters:
func – The function that was used as a global check.
call_once (
bool) – If the function should only be called once perinvoke()call.
- remove_check(func, /, *, call_once=False)[source]¶
Removes a global check from the bot.
This function is idempotent and will not raise an exception if the function is not in the global checks.
- Parameters:
func – The function to remove from the global checks.
call_once (
bool) – If the function was added withcall_once=Truein theBot.add_check()call or usingcheck_once().
- await add_gear(gear, /)[source]¶
This function is a coroutine.
Adds a “gear” to the bot.
A gear is a class that has its own event listeners and commands.
Note
Exceptions raised inside a
Gear’sgear_load()method will be propagated to the caller.- Parameters:
gear (
Gear) – The gear to register to the bot.- Raises:
CommandError– An error happened during loading.ClientException– A gear with the same name is already loaded.
- get_gear(name, /)[source]¶
Gets the gear instance requested.
If the gear is not found,
Noneis returned instead.
- await remove_gear(name, /)[source]¶
This function is a coroutine.
Removes a gear from the bot and returns it.
All registered commands and event listeners that the gear has registered will be removed as well.
If no gear is found then this method has no effect.
- await load_extension(name, *, package=None)[source]¶
This function is a coroutine.
Loads an extension.
An extension is a python module that contains commands, gears, or listeners.
An extension must have a global function,
setupdefined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, thebot.- Parameters:
name (
str) – The extension name to load. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.testif you want to importfoo/test.py.package (Optional[
str]) – The package name to resolve relative imports with. This is required when loading an extension using a relative path, e.g.foo.test. Defaults toNone.
- Raises:
ExtensionNotFound– The extension could not be imported. This is also raised if the name of the extension could not be resolved using the providedpackageparameter.ExtensionAlreadyLoaded– The extension is already loaded.NoEntryPointError– The extension does not have a setup function.ExtensionFailed– The extension or its setup function had an execution error.
- await unload_extension(name, *, package=None)[source]¶
This function is a coroutine.
Unloads an extension.
When the extension is unloaded, all commands, listeners, and gears are removed from the bot and the module is un-imported.
The extension can provide an optional global function,
teardown, to do miscellaneous clean-up if necessary. This function takes a single parameter, thebot, similar tosetupfromload_extension().- Parameters:
name (
str) – The extension name to unload. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.testif you want to importfoo/test.py.package (Optional[
str]) – The package name to resolve relative imports with. This is required when unloading an extension using a relative path, e.g.foo.test. Defaults toNone.
- Raises:
ExtensionNotFound– The name of the extension could not be resolved using the providedpackageparameter.ExtensionNotLoaded– The extension was not loaded.
- await reload_extension(name, *, package=None)[source]¶
This function is a coroutine.
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a
unload_extension()followed by aload_extension()except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.- Parameters:
name (
str) – The extension name to reload. It must be dot separated like regular Python imports if accessing a sub-module. e.g.foo.testif you want to importfoo/test.py.package (Optional[
str]) – The package name to resolve relative imports with. This is required when reloading an extension using a relative path, e.g.foo.test. Defaults toNone.
- Raises:
ExtensionNotLoaded– The extension was not loaded.ExtensionNotFound– The extension could not be imported. This is also raised if the name of the extension could not be resolved using the providedpackageparameter.NoEntryPointError– The extension does not have a setup function.ExtensionFailed– The extension setup function had an execution error.
- property extensions[source]¶
A read-only mapping of extension name to extension.
- Type:
Mapping[
str,types.ModuleType]
- property traditional_bot[source]¶
Whether the bot is a traditional bot (does not listen to
me).- Type:
- add_command(command, /)[source]¶
Adds a
Commandinto the internal list of commands.This is usually not called, instead the
command()orgroup()shortcut decorators are used instead.- Parameters:
command (
Command) – The command to add.- Raises:
CommandRegistrationError– If the command or its alias is already registered by different command.TypeError– If the command passed is not a subclass ofCommand.
- property commands[source]¶
An unique set of commands without aliases that are registered.
- Type:
Set[
Command]
- await create_group(name, *, http_overrides=None, description=None, icon=None, recipients=None, nsfw=None)[source]¶
This function is a coroutine.
Creates a new group.
Fires
PrivateChannelCreateEventfor the current user and all specified recipients.Note
This can only be used by non-bot accounts.
- Parameters:
name (
str) – The group name. Must be between 1 and 32 characters long.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.description (Optional[
str]) – The group description. Can be only up to 1024 characters.icon (Optional[
ResolvableResource]) – The group’s icon.recipients (Optional[List[ULIDOr[
BaseUser]]]) – The users to create the group with, only up to 49 users. You must be friends with these users.nsfw (Optional[
bool]) – To mark the group as NSFW or not.
- Raises:
HTTPException– Possible values fortype:Value
Reason
FailedValidationThe payload was invalid.
IsBotThe current token belongs to bot account.
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
GroupTooLargeThe group exceeded maximum count of recipients.
MissingPermissionYou do not have the proper permissions to add the recipient.
NotFriendsYou’re not friends with the users you want to create group with.
NotFound– Possible values fortype:Value
Reason
NotFoundOne of recipients was not found, or the provided file for icon was not found.
InternalServerError– Possible values fortype:
- Returns:
The new group.
- Return type:
- await create_server(name, *, http_overrides=None, description=None, nsfw=None)[source]¶
This function is a coroutine.
Create a new server.
Fires
ServerCreateEventfor the current user.Note
This can only be used by non-bot accounts.
- Parameters:
name (
str) – The server name. Must be between 1 and 32 characters long.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.description (Optional[
str]) – The server description. Can be only up to 1024 characters.nsfw (Optional[
bool]) – Whether this server is age-restricted.
- Raises:
HTTPException– Possible values fortype:Value
Reason
FailedValidationThe payload was invalid.
IsBotThe current token belongs to bot account.
TooManyChannelsThe instance was incorrectly configured. (?)
TooManyServersYou’re in too many servers than the instance allows.
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
InternalServerError– Possible values fortype:
- Returns:
The created server.
- Return type:
- dispatch(event, /)[source]¶
Dispatches an event.
Examples
Dispatch an event when someone sends silent message:
from attrs import define, field import stoat # ... @define(slots=True) class SilentMessageEvent(stoat.BaseEvent): message: stoat.Message = field(repr=True, kw_only=True) @client.on(stoat.MessageCreateEvent) async def on_message_create(event): message = event.message if message.flags.suppress_notifications: event = SilentMessageEvent(message=message) # Block until event gets fully handled (run hooks, calling event handlers, cache received data). await client.dispatch(event) # Note, that `dispatch` returns `asyncio.Task`, as such you may just do `client.dispatch(event)`.
- Parameters:
event (
BaseEvent) – The event to dispatch.- Returns:
The asyncio task.
- Return type:
- await fetch_channel(channel_id, /, *, http_overrides=None)[source]¶
This function is a coroutine.
Fetch a
Channelwith the specified ID.You must have
view_channelto do this.This is shortcut to
stoat.HTTPClient.get_channel().- Parameters:
channel (ULIDOr[
BaseChannel]) – The channel to fetch.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.
- Raises:
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to view the channel.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel was not found.
- Returns:
The retrieved channel.
- Return type:
- await fetch_emoji(emoji_id, /, *, http_overrides=None)[source]¶
This function is a coroutine.
Retrieves a custom emoji.
This is shortcut to
stoat.HTTPClient.get_emoji().
- await fetch_server(server_id, *, http_overrides=None, populate_channels=None)[source]¶
This function is a coroutine.
Retrieves a
Server.This is shortcut to
stoat.HTTPClient.get_server().- Parameters:
server (ULIDOr[
BaseServer]) – The server to retrieve.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.populate_channels (Optional[
bool]) – Whether to populatechannels.
- Raises:
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
NotFound– Possible values fortype:Value
Reason
NotFoundThe server was not found.
- Returns:
The retrieved server.
- Return type:
- await fetch_user(user_id, /, *, http_overrides=None)[source]¶
This function is a coroutine.
Retrieves an user from API. This is shortcut to
stoat.HTTPClient.get_user().
- get_channel(channel_id, /, *, partial=False)[source]¶
Retrieves a channel from cache.
- Parameters:
channel_id (
str) – The channel ID.partial (
bool) – Whether to returnPartialMessageableinstead ofNoneif server was not found.
- Returns:
The channel or
Noneif not found.- Return type:
Optional[Union[
Channel,PartialMessageable]]
- get_command(name, /)[source]¶
Get a
Commandfrom the internal list of commands.This could also be used as a way to get aliases.
The name could be fully qualified (e.g.
'foo bar') will get the subcommandbarof the group commandfoo. If a subcommand is not found thenNoneis returned just as usual.
- get_server(server_id, /, *, partial=False)[source]¶
Retrieves a server from cache.
- Parameters:
server_id (
str) – The server ID.partial (
bool) – Whether to returnBaseServerinstead ofNoneif server was not found.
- Returns:
The server or
Noneif not found.- Return type:
Optional[Union[
Server,BaseServer]]
- await on_library_error(shard, payload, exc, /)[source]¶
Handles library errors. By default, this logs exception.
Note
This won’t be called if handling
Readywill raise an exception as it is fatal.
- await on_user_error(event, /)[source]¶
Handles user errors that came from handlers. You can get current exception being raised via
sys.exc_info().By default, this logs exception.
- property ordered_private_channels[source]¶
The list of private channels in new client’s order.
- Type:
List[Union[
DMChannel,GroupChannel]]
- property ordered_private_channels_old[source]¶
The list of private channels in Revite order.
- Type:
List[Union[
DMChannel,GroupChannel]]
- property private_channels[source]¶
Mapping of channel IDs to private channels.
- Type:
Mapping[
str, Union[DMChannel,GroupChannel]]
- remove_command(name, /)[source]¶
Remove a
Commandfrom the internal list of commands.This could also be used as a way to remove aliases.
- run(token='', *, bot=UNDEFINED, log_handler=UNDEFINED, log_formatter=UNDEFINED, log_level=UNDEFINED, root_logger=False, asyncio_debug=False, cleanup=True)[source]¶
A blocking call that abstracts away the event loop initialization from you.
If you want more control over the event loop then this function should not be used. Use
start()coroutine.This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing
Noneto thelog_handlerparameter.Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
- Parameters:
log_handler (Optional[
logging.Handler]) –The log handler to use for the library’s logger. If this is
Nonethen the library will not set up anything logging related. Logging will still work ifNoneis passed, though it is your responsibility to set it up.The default log handler if not provided is
logging.StreamHandler.log_formatter (
logging.Formatter) – The formatter to use with the given log handler. If not provided then it defaults to a color based logging formatter (if available).log_level (
int) – The default log level for the library’s logger. This is only applied if thelog_handlerparameter is notNone. Defaults tologging.INFO.root_logger (
bool) –Whether to set up the root logger rather than the library logger. By default, only the library logger (
'stoat') is set up. If this is set toTruethen the root logger is set up as well.Defaults to
False.asyncio_debug (
bool) –Whether to run with asyncio debug mode enabled or not.
Defaults to
False.cleanup (
bool) –Whether to close aiohttp sessions or not.
Defaults to
True.
- property saved_notes[source]¶
The Saved Notes channel.
- Type:
Optional[
SavedMessagesChannel]
- await setup_hook()[source]¶
This function is a coroutine.
A hook that is called when client starts up.
- await start()[source]¶
This function is a coroutine.
Starts up the client.
Calls
setup_hook()before connecting.
- subscribe(event, /, callback)[source]¶
Subscribes to event.
- Parameters:
event (Type[EventT]) – The type of the event.
callback (MaybeAwaitableFunc[[EventT], None]) – The callback for the event.
- subscriptions_count_for(event, /, *, include_subclasses=False)[source]¶
int: Returns the subscriptions for event.- Parameters:
event (Type[EventT]) – The event to get subscription count to.
include_subclasses (class:bool) – Whether to include subclassed events. Defaults to
False.
- subscriptions_for(event, /, *, include_subclasses=False)[source]¶
List[EventSubscription[EventT]]: Returns the subscriptions for event.
- Parameters:
event (Type[EventT]) – The event to get subscriptions to.
include_subclasses (
bool) – Whether to include subclassed events. Defaults toFalse.
- property user[source]¶
The currently logged in user.
Noneif not logged in.Alias to
me.- Type:
Optional[
OwnUser]
- property voice_states[source]¶
Mapping of cached voice states.
- Type:
Mapping[
str,ChannelVoiceStateContainer]
- wait_for(event, /, *, check=None, count=1, timeout=None, manual_process=False, stop_dispatching_on_success=True)[source]¶
This function is a coroutine.
Waits for a WebSocket event to be dispatched.
This could be used to wait for an user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The
timeoutparameter is passed ontoasyncio.wait_for(). By default, it does not timeout. Note that this does propagate theasyncio.TimeoutErrorfor you in case of timeout and is provided for ease of use.This function returns the first event that meets the requirements.
Examples
Waiting for an user reply:
@client.on(stoat.MessageCreateEvent) async def on_message_create(event): message = event.message if message.content.startswith('$greet'): channel = message.channel await channel.send('Say hello!') def check(event): return event.message.content == 'hello' and event.message.channel.id == channel.id msg = await client.wait_for(stoat.MessageCreateEvent, check=check) await channel.send(f'Hello {msg.author}!')
Waiting for a thumbs up reaction from the message author:
@client.on(stoat.MessageCreateEvent) async def on_message_create(event): message = event.message if message.content.startswith('$thumb'): channel = message.channel await channel.send('Send me that 👍 reaction, mate') def check(event): return event.user_id == message.author.id and event.emoji == '👍' try: await client.wait_for(stoat.MessageReactEvent, timeout=60.0, check=check) except asyncio.TimeoutError: await channel.send('👎') else: await channel.send('👍')
- Parameters:
event (Type[EventT]) – The event to wait for.
check (Optional[Callable[[EventT],
bool]]) – A predicate to check what to wait for.timeout (Optional[
float]) – The number of seconds to wait before timing out and raisingasyncio.TimeoutError.manual_process (
bool) – Whether to not process the event at all when it gets dispatched. Defaults toFalse.stop_dispatching_on_success (
bool) – Whether to stop dispatching when event arrives. Defaults toTrue.
- Raises:
TypeError– Ifcountparameter was negative or zero.asyncio.TimeoutError– If a timeout is provided and it was reached.
- Returns:
The subscription. This can be
await’ed.- Return type:
Prefix Helpers¶
- stoat.ext.commands.when_mentioned(ctx, /)[source]¶
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the
Bot.command_prefixattribute.
- stoat.ext.commands.when_mentioned_or(*prefixes)[source]¶
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the
Bot.command_prefixattribute.Example
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
Note
This callable returns another callable, so if this is done inside a custom callable, you must call the returned callable, for example:
async def get_prefix(ctx): extras = await prefixes_for(message.server) # returns a list return commands.when_mentioned_or(*extras)(ctx)
See also
Event Reference¶
CommandErrorEvent¶
- async abefore_dispatch
- async aprocess
- def before_dispatch
- def cancel
- def process
- def set_canceled
- def uncancel
- class stoat.ext.commands.CommandErrorEvent(*, is_canceled=False, context, error)[source]¶
Dispatched when an error is raised inside a command either through user input error, check failure, or an error in your own code.
- error¶
The error that was raised.
- Type:
- await abefore_dispatch()[source]¶
This function is a coroutine.
Asynchronous version of
before_dispatch().
- cancel()[source]¶
Cancels the event processing (updating cache).
- Returns:
Whether the event was not canceled before.
- Return type:
CommandEvent¶
- async abefore_dispatch
- async aprocess
- def before_dispatch
- def cancel
- def process
- def set_canceled
- def uncancel
- class stoat.ext.commands.CommandEvent(*, is_canceled=False, context)[source]¶
Dispatched when a command is found and about to be invoked.
- await abefore_dispatch()[source]¶
This function is a coroutine.
Asynchronous version of
before_dispatch().
- cancel()[source]¶
Cancels the event processing (updating cache).
- Returns:
Whether the event was not canceled before.
- Return type:
CommandCompletionEvent¶
- async abefore_dispatch
- async aprocess
- def before_dispatch
- def cancel
- def process
- def set_canceled
- def uncancel
- class stoat.ext.commands.CommandCompletionEvent(*, is_canceled=False, context)[source]¶
Dispatched when a command has completed its invocation.
This event is dispatched only if the command succeeded, i.e. all checks have passed and the user input it correctly.
- await abefore_dispatch()[source]¶
This function is a coroutine.
Asynchronous version of
before_dispatch().
- cancel()[source]¶
Cancels the event processing (updating cache).
- Returns:
Whether the event was not canceled before.
- Return type:
- process()[source]¶
Any: Called when handlers got invoked and temporary subscriptions were handled and removed.
Commands¶
Decorators¶
- @stoat.ext.commands.command(name=None, cls=None, **attrs)[source]¶
A decorator that transforms a function into a
Commandor if called withgroup(),Group.By default the
helpattribute is received automatically from the docstring of the function and is cleaned up with the use ofinspect.cleandoc. If the docstring isbytes, then it is decoded intostrusing utf-8 encoding.All checks added using the
check()& co. decorators are added into the function. There is no way to supply your own checks through this decorator.- Parameters:
- Raises:
TypeError– If the function is not a coroutine or is already a command.
Command¶
- async __call__
- def add_check
- @ after_invoke
- @ before_invoke
- async can_run
- def copy
- @ error
- def has_error_handler
- def remove_check
- def update
- class stoat.ext.commands.Command(*_, **kwargs)[source]¶
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
- enabled¶
A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then
DisabledCommandis raised to theCommandErrorEventevent. Defaults toTrue.- Type:
- parent¶
The parent group that this command belongs to.
Noneif there isn’t one.- Type:
Optional[
Group]
- checks¶
A list of predicates that verifies if the command could be executed with the given
Contextas the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited fromCommandErrorshould be used. Note that if the checks fail thenCheckFailureexception is raised to theCommandErrorEventevent.
If
True, the default help command does not show this in the help output.- Type:
- rest_is_raw¶
If
Falseand a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handlesMissingRequiredArgumentand default values in a regular matter rather than passing the rest completely raw. IfTruethen the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults toFalse.- Type:
- require_var_positional¶
If
Trueand a variadic positional argument is specified, requires the user to specify at least one argument. Defaults toFalse.- Type:
- ignore_extra¶
If
True, ignores extraneous strings passed to a command if all its requirements are met (e.g.?foo a b cwhen only expectingaandb). OtherwiseCommandErrorEventis dispatched and local error handlers are called withTooManyArguments.Defaults to
True.- Type:
- cooldown_after_parsing¶
If
True, cooldown processing is done after argument parsing, which calls converters. IfFalsethen cooldown processing is done first and then the converters are called second. Defaults toFalse.- Type:
- extras¶
A dict of user provided extras to attach to the Command.
Note
This object may be copied by the library.
- Type:
- @after_invoke[source]¶
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it an useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a
Context.See
Bot.after_invoke()for more info.- Parameters:
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- @before_invoke[source]¶
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it an useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a
Context.See
Bot.before_invoke()for more info.
- @error[source]¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
CommandErrorEventevent limited to a single command. However, theCommandErrorEventis still invoked afterwards as the catch-all.
- add_check(func, /)[source]¶
Adds a check to the command.
This is the non-decorator interface to
check().See also
The
check()decorator- Parameters:
func – The function that will be used as a check.
- remove_check(func, /)[source]¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func – The function to remove from the checks.
- update(**kwargs)[source]¶
Updates
Commandinstance with updated attribute.This works similarly to the
command()decorator in terms of parameters in that they are passed to theCommandor subclass constructors, sans the name and callback.
- await __call__(context, /, *args, **kwargs)[source]¶
This function is a coroutine.
Calls the internal callback that the command holds.
Note
This bypasses all mechanisms – including checks, converters, invoke hooks, cooldowns, etc. You must take care to pass the proper arguments and types to this function.
- copy()[source]¶
Creates a copy of this command.
- Returns:
A new instance of this command.
- Return type:
- property clean_params[source]¶
Dict[
str,Parameter]: Retrieves the parameter dictionary without the context or self parameters.Useful for inspecting signature.
- property cooldown[source]¶
The cooldown of a command when invoked or
Noneif the command doesn’t have a registered cooldown.- Type:
Optional[
Cooldown]
- property full_parent_name[source]¶
Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example, in
?one two threethe parent name would beone two.- Type:
- property parents[source]¶
Retrieves the parents of this command.
If the command has no parents then it returns an empty
list.For example in commands
?a b c test, the parents are[c, b, a].- Type:
List[
Group]
- property root_parent[source]¶
Retrieves the root parent of this command.
If the command has no parents then it returns
None.For example in commands
?a b c test, the root parent isa.- Type:
Optional[
Group]
- property qualified_name[source]¶
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in
?one two threethe qualified name would beone two three.- Type:
- await can_run(ctx, /)[source]¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute. This also checks whether the command is disabled.- Parameters:
ctx (
Context) – The ctx of the command currently being invoked.- Raises:
CommandError– Any command error that was raised during a check call will be propagated by this function.- Returns:
A boolean indicating if the command can be invoked.
- Return type:
Group¶
- def add_check
- def add_command
- @ after_invoke
- @ before_invoke
- async can_run
- @ command
- def copy
- @ error
- def get_command
- @ group
- def has_error_handler
- def remove_check
- def remove_command
- def update
- def walk_commands
- class stoat.ext.commands.Group(*_, **kwargs)[source]¶
A class that implements a grouping protocol for commands to be executed as subcommands.
This class is a subclass of
Commandand thus all options valid inCommandare valid in here as well.- invoke_without_command¶
Indicates if the group callback should begin parsing and invocation only if no subcommand was found. Useful for making it an error handling function to tell the user that no subcommand was found or to have different functionality in case no subcommand was found. If this is
False, then the group callback will always be invoked first. This means that the checks and the parsing dictated by its parameters will be executed. Defaults toFalse.- Type:
- case_insensitive¶
Indicates if the group’s commands should be case insensitive. Defaults to
False.- Type:
- @after_invoke[source]¶
A decorator that registers a coroutine as a post-invoke hook.
A post-invoke hook is called directly after the command is called. This makes it an useful function to clean-up database connections or any type of clean up required.
This post-invoke hook takes a sole parameter, a
Context.See
Bot.after_invoke()for more info.- Parameters:
coro (coroutine) – The coroutine to register as the post-invoke hook.
- Raises:
TypeError – The coroutine passed is not actually a coroutine.
- @before_invoke[source]¶
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it an useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a
Context.See
Bot.before_invoke()for more info.
- @command(*args, **kwargs)[source]¶
A shortcut decorator that invokes
command()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
Callable[…,
Command]
- @error[source]¶
A decorator that registers a coroutine as a local error handler.
A local error handler is an
CommandErrorEventevent limited to a single command. However, theCommandErrorEventis still invoked afterwards as the catch-all.
- @group(*args, **kwargs)[source]¶
A shortcut decorator that invokes
group()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
Callable[…,
Group]
- add_check(func, /)[source]¶
Adds a check to the command.
This is the non-decorator interface to
check().See also
The
check()decorator- Parameters:
func – The function that will be used as a check.
- add_command(command, /)[source]¶
Adds a
Commandinto the internal list of commands.This is usually not called, instead the
command()orgroup()shortcut decorators are used instead.- Parameters:
command (
Command) – The command to add.- Raises:
CommandRegistrationError– If the command or its alias is already registered by different command.TypeError– If the command passed is not a subclass ofCommand.
- await can_run(ctx, /)[source]¶
This function is a coroutine.
Checks if the command can be executed by checking all the predicates inside the
checksattribute. This also checks whether the command is disabled.- Parameters:
ctx (
Context) – The ctx of the command currently being invoked.- Raises:
CommandError– Any command error that was raised during a check call will be propagated by this function.- Returns:
A boolean indicating if the command can be invoked.
- Return type:
- property clean_params[source]¶
Dict[
str,Parameter]: Retrieves the parameter dictionary without the context or self parameters.Useful for inspecting signature.
- property commands[source]¶
An unique set of commands without aliases that are registered.
- Type:
Set[
Command]
- property cooldown[source]¶
The cooldown of a command when invoked or
Noneif the command doesn’t have a registered cooldown.- Type:
Optional[
Cooldown]
- property full_parent_name[source]¶
Retrieves the fully qualified parent command name.
This the base command name required to execute it. For example, in
?one two threethe parent name would beone two.- Type:
- get_command(name, /)[source]¶
Get a
Commandfrom the internal list of commands.This could also be used as a way to get aliases.
The name could be fully qualified (e.g.
'foo bar') will get the subcommandbarof the group commandfoo. If a subcommand is not found thenNoneis returned just as usual.
- property parents[source]¶
Retrieves the parents of this command.
If the command has no parents then it returns an empty
list.For example in commands
?a b c test, the parents are[c, b, a].- Type:
List[
Group]
- property qualified_name[source]¶
Retrieves the fully qualified command name.
This is the full parent name with the command name as well. For example, in
?one two threethe qualified name would beone two three.- Type:
- remove_check(func, /)[source]¶
Removes a check from the command.
This function is idempotent and will not raise an exception if the function is not in the command’s checks.
- Parameters:
func – The function to remove from the checks.
- remove_command(name, /)[source]¶
Remove a
Commandfrom the internal list of commands.This could also be used as a way to remove aliases.
- property root_parent[source]¶
Retrieves the root parent of this command.
If the command has no parents then it returns
None.For example in commands
?a b c test, the root parent isa.- Type:
Optional[
Group]
GroupMixin¶
- def add_command
- @ command
- def get_command
- @ group
- def remove_command
- def walk_commands
- class stoat.ext.commands.GroupMixin(*args, **kwargs)[source]¶
A mixin that implements common functionality for classes that behave similar to
Groupand are allowed to register commands.- @command(*args, **kwargs)[source]¶
A shortcut decorator that invokes
command()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Command, adds it to the bot, then returns it.
- Return type:
Callable[…,
Command]
- @group(*args, **kwargs)[source]¶
A shortcut decorator that invokes
group()and adds it to the internal command list viaadd_command().- Returns:
A decorator that converts the provided method into a Group, adds it to the bot, then returns it.
- Return type:
Callable[…,
Group]
- property commands[source]¶
An unique set of commands without aliases that are registered.
- Type:
Set[
Command]
- add_command(command, /)[source]¶
Adds a
Commandinto the internal list of commands.This is usually not called, instead the
command()orgroup()shortcut decorators are used instead.- Parameters:
command (
Command) – The command to add.- Raises:
CommandRegistrationError– If the command or its alias is already registered by different command.TypeError– If the command passed is not a subclass ofCommand.
- remove_command(name, /)[source]¶
Remove a
Commandfrom the internal list of commands.This could also be used as a way to remove aliases.
- for ... in walk_commands()[source]¶
An iterator that recursively walks through all commands and subcommands.
Gears¶
Gear¶
- cls Gear.listener
- def bot_check
- def bot_check_once
- async gear_after_invoke
- async gear_before_invoke
- def gear_check
- async gear_command_error
- async gear_load
- async gear_unload
- def get_commands
- def get_listeners
- def has_error_handler
- def walk_commands
- class stoat.ext.commands.Gear(*_, **__)[source]¶
The base class that all gears must inherit from.
A gear is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the Gears page.
When inheriting from this class, the options shown in
GearMetaare equally valid here.- property description[source]¶
Returns the gear’s description, typically the cleaned docstring.
- Type:
- for ... in walk_commands()[source]¶
An iterator that recursively walks through this gear’s commands and subcommands.
- get_listeners()[source]¶
Returns a
listof (event, function) listener pairs that are defined in this gear.- Returns:
The listeners defined in this gear.
- Return type:
List[Tuple[Type[
stoat.BaseEvent], coroutine]]
- classmethod listener(to=None)[source]¶
A decorator that marks a function as a listener.
This is the gear equivalent of
Bot.listen().- Parameters:
to (Optional[Type[
BaseEvent]]) – The class of the event being listened to. If not provided, it defaults to the argument’s type.- Raises:
TypeError– The event was not passed.
- await gear_load()[source]¶
This function could be a coroutine.
A special method that is called when the gear gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the
__init__special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
- await gear_unload()[source]¶
This function could be a coroutine.
A special method that is called when the gear gets removed.
Subclasses must replace this if they want special unloading behaviour.
Exceptions raised in this method are ignored during extension unloading.
- bot_check_once(ctx, /)[source]¶
A special method that registers as a
Bot.check_once()check.This function can be a coroutine and must take a sole parameter,
ctx, to represent theContext.
- bot_check(ctx, /)[source]¶
A special method that registers as a
Bot.check()check.This function can be a coroutine and must take a sole parameter,
ctx, to represent theContext.
- gear_check(ctx, /)[source]¶
A special method that registers as a
check()for every command and subcommand in this gear.This function can be a coroutine and must take a sole parameter,
ctx, to represent theContext.
- await gear_command_error(ctx, error, /)[source]¶
This function is a coroutine.
A special method that is called whenever an error is dispatched inside this gear.
This is similar to
CommandErrorEventexcept only applying to the commands inside this gear.This must be a coroutine.
- Parameters:
ctx (
Context) – The invocation context where the error happened.error (
CommandError) – The error that happened.
- await gear_before_invoke(ctx, /)[source]¶
This function is a coroutine.
A special method that acts as a gear local pre-invoke hook.
This is similar to
Command.before_invoke().This must be a coroutine.
- Parameters:
ctx (
Context) – The invocation context.
- await gear_after_invoke(ctx, /)[source]¶
This function is a coroutine.
A special method that acts as a gear local post-invoke hook.
This is similar to
Command.after_invoke().This must be a coroutine.
- Parameters:
ctx (
Context) – The invocation context.
GearMeta¶
- class stoat.ext.commands.GearMeta(*args, **kwargs)[source]¶
A metaclass for defining a gear.
Note that you should probably not use this directly. It is exposed purely for documentation purposes along with making custom metaclasses to intermix with other metaclasses such as the
abc.ABCMetametaclass.For example, to create an abstract gear mixin class, the following would be done.
import abc class GearABCMeta(commands.GearMeta, abc.ABCMeta): pass class SomeMixin(metaclass=abc.ABCMeta): pass class SomeGearMixin(SomeMixin, commands.Gear, metaclass=GearABCMeta): pass
Note
When passing an attribute of a metaclass that is documented below, note that you must pass it as a keyword-only argument to the class creation like the following example:
class MyGear(commands.Gear, name='My Gear'): pass
- command_attrs¶
A list of attributes to apply to every command inside this gear. The dictionary is passed into the
Commandoptions at__init__. If you specify attributes inside the command attribute in the class, it will override the one specified inside this attribute. For example:class MyGear(commands.Gear, command_attrs={'hidden': True}): @commands.command() async def foo(self, ctx): pass # hidden -> True @commands.command(hidden=False) async def bar(self, ctx): pass # hidden -> False
- Type:
Enums¶
- class stoat.ext.commands.BucketType[source]¶
Specifies a type of bucket for, e.g. a cooldown.
- default¶
The default bucket operates on a global basis.
- user¶
The user bucket operates on a per-user basis.
- server¶
The server bucket operates on a per-server basis.
- channel¶
The channel bucket operates on a per-channel basis.
- member¶
The member bucket operates on a per-member basis.
- category¶
The category bucket operates on a per-category basis.
- role¶
The role bucket operates on a per-role basis.
Checks¶
- @stoat.ext.commands.check(predicate)[source]¶
A decorator that adds a check to the
Commandor its subclasses. These checks could be accessed viaCommand.checks.These checks should be predicates that take in a single parameter taking a
Context. If the check returns aFalse-like value then during invocation aCheckFailureexception is raised and sent to theCommandErrorEventevent.If an exception should be thrown in the predicate then it should be a subclass of
CommandError. Any exception not subclassed from it will be propagated while those subclassed will be sent toCommandErrorEvent.A special attribute named
predicateis bound to the value returned by this decorator to retrieve the predicate passed to the decorator. This allows the following introspection and chaining to be done:def owner_or_permissions(**perms): original = commands.has_permissions(**perms).predicate async def extended_check(ctx): if ctx.server is None: return False return ctx.server.owner_id == ctx.author_id or await original(ctx) return commands.check(extended_check)
Note
The function returned by
predicateis always a coroutine, even if the original function was not a coroutine.Examples
Creating a basic check to see if the command invoker is you.
def check_if_it_is_me(ctx): return ctx.author_id == '01H1QAGNCAP1VHW0CYXBZ5P176' @bot.command() @commands.check(check_if_it_is_me) async def only_for_me(ctx): await ctx.send('I know you!')
Transforming common checks into its own decorator:
def is_me(): def predicate(ctx): return ctx.author_id == '01H1QAGNCAP1VHW0CYXBZ5P176' return commands.check(predicate) @bot.command() @is_me() async def only_me(ctx): await ctx.send('Only you!')
- @stoat.ext.commands.check_any(*checks)[source]¶
A
check()that is added that checks if any of the checks passed will pass, i.e. using logical OR.If all checks fail then
CheckAnyFailureis raised to signal the failure. It inherits fromCheckFailure.Note
The
predicateattribute for this function is a coroutine.- Parameters:
*checks (Callable[[
Context],bool]) – An argument list of checks that have been decorated with thecheck()decorator.- Raises:
TypeError– A check passed has not been decorated with thecheck()decorator.
Examples
Creating a basic check to see if it’s the bot owner or the server owner:
def is_server_owner(): def predicate(ctx): return ctx.server is not None and ctx.server.owner_id == ctx.author_id return commands.check(predicate) @bot.command() @commands.check_any(commands.is_owner(), is_server_owner()) async def only_for_owners(ctx): await ctx.send('Hello mister owner!')
- @stoat.ext.commands.has_role(item)[source]¶
A
check()that is added that checks if the member invoking the command has the role specified via the ID specified.If the message is invoked in a private message context then the check will return
False.This check raises one of two special exceptions,
MissingRoleif the user is missing a role, orNoPrivateMessageif it is used in a private message. Both inherit fromCheckFailure.- Parameters:
item (
str) – The ID of the role to check.
- @stoat.ext.commands.has_permissions(**perms)[source]¶
A
check()that is added that checks if the member has all of the permissions necessary.Note that this check operates on the current channel permissions, not the server wide permissions.
The permissions passed in must be exactly like the properties shown under
stoat.Permissions.This check raises a special exception,
MissingPermissionsthat is inherited fromCheckFailure.- Parameters:
perms – An argument list of permissions to check for.
Example
@bot.command() @commands.has_permissions(manage_messages=True) async def test(ctx): await ctx.send('You can manage messages.')
- @stoat.ext.commands.has_server_permissions(**perms)[source]¶
Similar to
has_permissions(), but operates on server wide permissions instead of the current channel permissions.If this check is called in a DM context, it will raise an exception,
NoPrivateMessage.
- @stoat.ext.commands.has_any_role(*items)[source]¶
A
check()that is added that checks if the member invoking the command has any of the roles specified. This means that if they have one out of the three roles specified, then this check will returnTrue.Similar to
has_role(), the IDs passed in must be exact.This check raises one of two special exceptions,
MissingAnyRoleif the user is missing all roles, orNoPrivateMessageif it is used in a private message. Both inherit fromCheckFailure.- Parameters:
items (List[
str]) – An argument list of IDs to check that the member has roles wise.
Example
@bot.command() @commands.has_any_role('01J35ZZX7FJH21YCCMYQHET5H9') async def cool(ctx): await ctx.send('You are cool indeed')
- @stoat.ext.commands.bot_has_role(item)[source]¶
Similar to
has_role()except checks if the bot itself has the role.This check raises one of two special exceptions,
BotMissingRoleif the bot is missing the role, orNoPrivateMessageif it is used in a private message. Both inherit fromCheckFailure.
- @stoat.ext.commands.bot_has_permissions(**perms)[source]¶
Similar to
has_permissions()except checks if the bot itself has the permissions listed.This check raises a special exception,
BotMissingPermissionsthat is inherited fromCheckFailure.
- @stoat.ext.commands.bot_has_server_permissions(**perms)[source]¶
Similar to
has_server_permissions(), but checks the bot members server permissions.
- @stoat.ext.commands.bot_has_any_role(*items)[source]¶
Similar to
has_any_role()except checks if the bot itself has any of the roles listed.This check raises one of two special exceptions,
BotMissingAnyRoleif the bot is missing all roles, orNoPrivateMessageif it is used in a private message. Both inherit fromCheckFailure.
- @stoat.ext.commands.cooldown(rate, per, type=stoat.ext.commands.BucketType.default)[source]¶
A decorator that adds a cooldown to a
Command.A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-server, per-channel, per-user, per-role or global basis. Denoted by the third argument of
typewhich must be of enum typeBucketType.If a cooldown is triggered, then
CommandOnCooldownis triggered inCommandErrorEventand the local error handler.A command can only have a single cooldown.
- Parameters:
rate (
int) – The number of times a command can be used before triggering a cooldown.per (
float) – The amount of seconds to wait for a cooldown when it’s been triggered.type (Union[
BucketType, Callable[[Context], Any]]) – The type of cooldown to have. If callable, it must return a key for the mapping.
- @stoat.ext.commands.dynamic_cooldown(cooldown, type)[source]¶
A decorator that adds a dynamic cooldown to a
Command.This differs from
cooldown()in that it takes a function that accepts a single parameter of typeContextand must return aCooldownorNone. IfNoneis returned then that cooldown is effectively bypassed.A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-server, per-channel, per-user, per-role or global basis. Denoted by the third argument of
typewhich must be of enum typeBucketType.If a cooldown is triggered, then
CommandOnCooldownis triggered inCommandErrorEventand the local error handler.A command can only have a single cooldown.
- Parameters:
cooldown (Callable[[
Context], Optional[Cooldown]]) – A function that takes a message and returns a cooldown that will apply to this invocation orNoneif the cooldown should be bypassed.type (
BucketType) – The type of cooldown to have.
- @stoat.ext.commands.max_concurrency(number, per=stoat.ext.commands.BucketType.default, *, wait=False)[source]¶
A decorator that adds a maximum concurrency to a
Commandor its subclasses.This enables you to only allow a certain number of command invocations at the same time, for example if a command takes too long or if only one user can use it at a time. This differs from a cooldown in that there is no set waiting period or token bucket – only a set number of people can run the command.
- Parameters:
number (
int) – The maximum number of invocations of this command that can be running at the same time.per (
BucketType) – The bucket that this concurrency is based on, e.g.BucketType.serverwould allow it to be used up tonumbertimes per server.wait (
bool) – Whether the command should wait for the queue to be over. If this is set toFalsethen instead of waiting until the command can run again, the command raisesMaxConcurrencyReachedto its error handler. If this is set toTruethen the command waits until it can be executed.
- @stoat.ext.commands.before_invoke(coro)[source]¶
A decorator that registers a coroutine as a pre-invoke hook.
This allows you to refer to one before invoke hook for several commands that do not have to be within the same gear.
Example
async def record_usage(ctx): print(ctx.author, 'used', ctx.command, 'at', ctx.message.created_at) @bot.command() @commands.before_invoke(record_usage) async def who(ctx): # Output: <User> used who at <Time> await ctx.send('i am a bot') class What(commands.Gear): @commands.before_invoke(record_usage) @commands.command() async def when(self, ctx): # Output: <User> used when at <Time> await ctx.send(f'and i have existed since {ctx.bot.user.created_at}') @commands.command() async def where(self, ctx): # Output: <Nothing> await ctx.send('on Stoat') @commands.command() async def why(self, ctx): # Output: <Nothing> await ctx.send('because someone made me')
- @stoat.ext.commands.after_invoke(coro)[source]¶
A decorator that registers a coroutine as a post-invoke hook.
This allows you to refer to one after invoke hook for several commands that do not have to be within the same gear.
- @stoat.ext.commands.server_only()[source]¶
A
check()that indicates this command must only be used in a server context only. Basically, no private messages are allowed when using the command.This check raises a special exception,
NoPrivateMessagethat is inherited fromCheckFailure.
- @stoat.ext.commands.dm_only()[source]¶
A
check()that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.This check raises a special exception,
PrivateMessageOnlythat is inherited fromCheckFailure.
- @stoat.ext.commands.is_owner()[source]¶
A
check()that checks if the person invoking this command is the owner of the bot.This check raises a special exception,
NotOwnerthat is derived fromCheckFailure.
- @stoat.ext.commands.is_nsfw()[source]¶
A
check()that checks if the channel is a NSFW channel.This check raises a special exception,
NSFWChannelRequiredthat is derived fromCheckFailure.If used on hybrid commands, this will be equivalent to setting the application command’s
nsfwattribute toTrue. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
Context¶
- async acknowledge
- async begin_typing
- async end_typing
- async fetch_channel_id
- async fetch_message
- def get_channel_id
- def get_message
- async history
- async search
- async send
- def typing
- class stoat.ext.commands.Context(*, args=None, bot, command=None, command_failed=False, current_argument=None, current_parameter=None, event=None, kwargs=None, invoked_parents=None, invoked_subcommand=None, label='', message, shard, subcommand_passed=None, view)[source]¶
A invoking context for commands.
These are not created manually, instead they are created via
Bot.get_context()method.- channel¶
The channel the context was created in.
- Type:
Union[
TextableChannel,PartialMessageable]
- view¶
The string view, used to parse command parameters.
- Type:
StringView
- async with typing()[source]¶
Returns an asynchronous context manager that allows you to send a typing indicator in destination channel for an indefinite period of time.
- property gear[source]¶
Returns the gear associated with this context’s command. None if it does not exist.
- Type:
Optional[
Gear]
- await acknowledge(message=UNDEFINED, *, channel_http_overrides=None, http_overrides=None)[source]¶
This function is a coroutine.
Marks the destination channel as read.
You must have
view_channelto do this.Fires
MessageAckEventfor the current user.Note
This can only be used by non-bot accounts.
- Parameters:
message (ULIDOr[
BaseMessage]) – The message to mark as read.channel_http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides for getting channel.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.
- Raises:
HTTPException– Possible values fortype:Value
Reason
IsBotThe current token belongs to bot account.
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to view the channel.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel was not found.
- await begin_typing(*, http_overrides=None)[source]¶
Begins typing in channel, until
end_typing()is called.
- await fetch_channel_id(*, http_overrides=None)[source]¶
This function is a coroutine.
Retrieves the channel’s ID.
- Parameters:
http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.- Returns:
The channel’s ID.
- Return type:
- await fetch_message(message, /, *, channel_http_overrides=None, http_overrides=None)[source]¶
This function is a coroutine.
Retrieves a message.
- Parameters:
message (ULIDOr[
BaseMessage]) – The message to retrieve.channel_http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides for getting channel.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.
- Raises:
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to view the channel.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel/message was not found.
InternalServerError– Possible values fortype:
- Returns:
The retrieved message.
- Return type:
- await history(*, channel_http_overrides=None, http_overrides=None, limit=None, before=None, after=None, sort=None, nearby=None, populate_users=None)[source]¶
This function is a coroutine.
Retrieve message history from destination channel.
You must have
read_message_historyto do this.- Parameters:
channel_http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides for getting channel.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.limit (Optional[
int]) –The maximum number of messages to get. Must be between 1 and 100. Defaults to 50.
If
nearbyis provided, then this is(limit + 2).before (Optional[ULIDOr[
BaseMessage]]) – The message before which messages should be fetched.after (Optional[ULIDOr[
BaseMessage]]) – The message after which messages should be fetched.sort (Optional[
MessageSort]) – The message sort direction. Defaults tolatestnearby (Optional[ULIDOr[
BaseMessage]]) –The message to search around.
Providing this parameter will discard
before,afterandsortparameters.It will also take half of limit rounded as the limits to each side. It also fetches the message specified.
populate_users (
bool) – Whether to populate user (and member, if server channel) objects.
- Raises:
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to read the message history.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel was not found.
InternalServerError– Possible values fortype:Value
Reason
Populated attributes
DatabaseErrorSomething went wrong during querying database.
- Returns:
The messages retrieved.
- Return type:
List[
Message]
- await search(query=None, *, channel_http_overrides=None, http_overrides=None, pinned=None, limit=None, before=None, after=None, sort=None, populate_users=None)[source]¶
This function is a coroutine.
Searches for messages in destination channel.
For
queryandpinned, only one parameter can be provided, otherwise aHTTPExceptionwill be thrown withInvalidOperationtype.You must have
read_message_historyto do this.Note
This can only be used by non-bot accounts.
- Parameters:
query (Optional[
str]) – The full-text search query. See MongoDB documentation for more information.channel_http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides for getting channel.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.pinned (Optional[
bool]) – Whether to search for (un-)pinned messages or not.limit (Optional[
int]) –The maximum number of messages to get. Must be between 1 and 100. Defaults to 50.
If
nearbyis provided, then this is(limit + 2).before (Optional[ULIDOr[
BaseMessage]]) – The message before which messages should be fetched.after (Optional[ULIDOr[
BaseMessage]]) – The message after which messages should be fetched.sort (Optional[
MessageSort]) – The message sort direction. Defaults tolatestnearby (Optional[ULIDOr[
BaseMessage]]) –The message to search around.
Providing this parameter will discard
before,afterandsortparameters.It will also take half of limit rounded as the limits to each side. It also fetches the message specified.
populate_users (
bool) – Whether to populate user (and member, if server channel) objects.
- Raises:
HTTPException– Possible values fortype:Value
Reason
FailedValidationOne of
before,afterornearbyparameters were invalid IDs.InvalidOperationYou provided both
queryandpinnedparameters.IsBotThe current token belongs to bot account.
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to search messages.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel was not found.
InternalServerError– Possible values fortype:Value
Reason
Populated attributes
DatabaseErrorSomething went wrong during querying database.
- Returns:
The messages matched.
- Return type:
List[
Message]
- await send(content=None, *, channel_http_overrides=None, http_overrides=None, nonce=None, attachments=None, replies=None, embeds=None, masquerade=None, interactions=None, silent=None, mention_everyone=None, mention_online=None)[source]¶
This function is a coroutine.
Sends a message to destination channel.
You must have
send_messagesto do this.If message mentions “@everyone” or “@online”, you must have
mention_everyoneto do that.If message mentions any roles, you must
mention_rolesto do that.Fires
MessageCreateEventand optionallyMessageAppendEvent, both for all users who can see destination channel.- Parameters:
content (Optional[
str]) – The message content.channel_http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides for getting channel.http_overrides (Optional[
HTTPOverrideOptions]) – The HTTP request overrides.nonce (Optional[
str]) – The message nonce.attachments (Optional[List[
ResolvableResource]]) –The attachments to send the message with.
You must have
upload_filesto provide this.replies (Optional[List[Union[
Reply, ULIDOr[BaseMessage]]]]) – The message replies.embeds (Optional[List[
SendableEmbed]]) –The embeds to send the message with.
You must have
send_embedsto provide this.masquerade (Optional[
MessageMasquerade]) –The message masquerade.
You must have
use_masqueradeto provide this.If
coloris provided,use_masqueradeis also required.interactions (Optional[
MessageInteractions]) –The message interactions.
silent (Optional[
bool]) – Whether to suppress notifications or not.mention_everyone (Optional[
bool]) –Whether to mention all users who can see the channel. This cannot be mixed with
mention_onlineparameter.Note
User accounts cannot set this to
True.mention_online (Optional[
bool]) –Whether to mention all users who are online and can see the channel. This cannot be mixed with
mention_everyoneparameter.Note
User accounts cannot set this to
True.
- Raises:
stoat.HTTPException– Possible values fortype:Value
Reason
EmptyMessageThe message was empty.
FailedValidationThe payload was invalid.
InvalidFlagValueBoth
mention_everyoneandmention_onlinewereTrue.InvalidOperationThe passed nonce was already used. One of
reactionselements was invalid.InvalidPropertyrestrict_reactionswasTruebutreactionswas empty.IsBotThe current token belongs to bot account.
IsNotBotThe current token belongs to user account.
PayloadTooLargeThe message was too large.
TooManyAttachmentsYou provided more attachments than allowed on this instance.
TooManyEmbedsYou provided more embeds than allowed on this instance.
TooManyRepliesYou were replying to more messages than was allowed on this instance.
Unauthorized– Possible values fortype:Value
Reason
InvalidSessionThe current bot/user token is invalid.
Forbidden– Possible values fortype:Value
Reason
MissingPermissionYou do not have the proper permissions to send messages.
NotFound– Possible values fortype:Value
Reason
NotFoundThe channel/file/reply was not found.
stoat.InternalServerError– Possible values fortype:Value
Reason
Populated attributes
DatabaseErrorSomething went wrong during querying database.
InternalErrorSomehow something went wrong during message creation.
- Returns:
The message that was sent.
- Return type:
Converters¶
- async convert
- class stoat.ext.commands.Converter(*args, **kwargs)[source]¶
The base class of custom converters that require the
Contextto be passed to be useful.This allows you to implement converters that function similar to the special cased
stoatclasses.Classes that derive from this should override the
convert()method to do its conversion logic. This method must be a coroutine.- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.BaseConverter(*args, **kwargs)[source]¶
Converts to a
Base.The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by member, role, or channel mention.
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.MemberConverter(*args, **kwargs)[source]¶
Converts to a
Member.All lookups are done via the local server. If in a DM context, then the lookup fails.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
3. Lookup by username#discriminator. 5. Lookup by user name. 6. Lookup by global name. 7. Lookup by server nickname.
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.UserConverter(*args, **kwargs)[source]¶
Converts to a
User.All lookups are done via the global user cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by username#discriminator.
Lookup by user name.
Lookup by global name.
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.MessageConverter(*args, **kwargs)[source]¶
Converts to a
stoat.Message.The lookup strategy is as follows (in order):
Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
Lookup by message ID (the message must be in the context channel)
Lookup by message URL
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.BaseMessageConverter(*args, **kwargs)[source]¶
Converts to a
stoat.BaseMessage.The creation strategy is as follows (in order):
By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
By message ID (The message is assumed to be in the context channel.)
By message URL
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.ServerChannelConverter(*args, **kwargs)[source]¶
Converts to a
ServerChannel.All lookups are via the local server. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name.
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.TextChannelConverter(*args, **kwargs)[source]¶
Converts to a
TextChannel.All lookups are via the local server. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.VoiceChannelConverter(*args, **kwargs)[source]¶
Converts to a
VoiceChannel.All lookups are via the local server. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by channel URL.
Lookup by name
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.CategoryConverter(*args, **kwargs)[source]¶
Converts to a
Category.All lookups are via the local server. If in a DM context, then the lookup fails.
The lookup strategy is as follows (in order):
Lookup by ID
Lookup by title
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.InviteConverter(*args, **kwargs)[source]¶
Converts to a
PublicInvite.This is done via a HTTP request using
stoat.HTTPClient.get_invite().- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.ServerConverter(*args, **kwargs)[source]¶
Converts to a
Server.The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by name. (There is no disambiguation for Servers with multiple matching names).
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.RoleConverter(*args, **kwargs)[source]¶
Converts to a
Role.All lookups are via the local server. If in a DM context, the converter raises
NoPrivateMessageexception.The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by mention.
Lookup by name
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- async convert
- class stoat.ext.commands.EmojiConverter(*args, **kwargs)[source]¶
Converts to a
Emoji.All lookups are done for the local server first, if available. If that lookup fails, then it checks the client’s global cache.
The lookup strategy is as follows (in order):
Lookup by ID.
Lookup by extracting ID from the emoji.
Lookup by name
- await convert(ctx, argument, /)[source]¶
This function is a coroutine.
The method to override to do conversion logic.
If an error is found while converting, it is recommended to raise a
CommandErrorderived exception as it will properly propagate to the error handlers.Note that if this method is called manually,
Exceptionshould be caught to handle the cases where a subclass does not explicitly inherit fromCommandError.- Parameters:
- Raises:
CommandError– A generic exception occurred when converting the argument.BadArgument– The converter failed to convert the argument.
- class stoat.ext.commands.Greedy[source]¶
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
@commands.command() async def test(ctx, numbers: Greedy[int], reason: str): await ctx.send('numbers: {}, reason: {}'.format(numbers, reason))
An invocation of
[p]test 1 2 3 4 5 6 hellowould passnumberswith[1, 2, 3, 4, 5, 6]andreasonwithhello.For more information, check ext_commands_special_converters.
- await stoat.ext.commands.run_converters(ctx, converter, argument, param, /)[source]¶
This function is a coroutine.
Runs converters for a given converter, argument, and parameter.
This function does the same work that the library does under the hood.
- Parameters:
- Raises:
CommandError– The converter failed to convert.- Returns:
The resulting conversion.
- Return type:
Any
Defaults¶
- async get_default
- def replace
- class stoat.ext.commands.Parameter[source]¶
A class that stores information on a
Command's parameter.This is a subclass of
inspect.Parameter.- replace(*, name=..., kind=..., default=..., annotation=..., description=..., displayed_default=..., displayed_name=...)[source]¶
Creates a customized copy of the Parameter.
- property name¶
The parameter’s name.
- property kind¶
The parameter’s kind.
- property default¶
The parameter’s default.
- property annotation¶
The parameter’s annotation.
- property displayed_default[source]¶
The displayed default in
Command.signature.- Type:
Optional[
str]
- stoat.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)[source]¶
A way to assign custom metadata for a
Command's parameter.Examples
A custom default can be used to have late binding behaviour.
@bot.command() async def wave(ctx, to: stoat.User = commands.parameter(default=lambda ctx: ctx.author)): await ctx.send(f'Hello {to.mention} :wave:')
- Parameters:
converter (Any) – The converter to use for this parameter, this replaces the annotation at runtime which is transparent to type checkers.
default (Any) – The default value for the parameter, if this is a callable or a coroutine it is called with a positional
Contextargument.description (
str) – The description of this parameter.displayed_default (
str) – The displayed default inCommand.signature.displayed_name (
str) – The name that is displayed to the user.
- stoat.ext.commands.param(*, converter, default, description, displayed_default, displayed_name)[source]¶
param(*, converter=…, default=…, description=…, displayed_default=…, displayed_name=…)
An alias for
parameter().
- stoat.ext.commands.CurrentServer¶
A default
Parameterwhich returns theserverfor this context. This will never beNone. If the command is called in a DM context thenNoPrivateMessageis raised to the error handlers.
Cooldowns¶
- def copy
- def get_retry_after
- def get_tokens
- def reset
- def update_rate_limit
- class stoat.ext.commands.Cooldown(rate, per)[source]¶
Represents a cooldown for a command.
- get_tokens(current=None)[source]¶
Returns the number of available tokens before rate limiting is applied.
- Parameters:
current (Optional[
float]) – The time in seconds since Unix epoch to calculate tokens at. If not supplied thentime.time()is used.- Returns:
The number of tokens available before the cooldown is to be applied.
- Return type:
- get_retry_after(current=None)[source]¶
Returns the time in seconds until the cooldown will be reset.
- Parameters:
current (Optional[
float]) – The current time in seconds since Unix epoch. If not supplied, thentime.time()is used.- Returns:
The number of seconds to wait before this cooldown will be reset.
- Return type:
- update_rate_limit(current=None, *, tokens=1)[source]¶
Updates the cooldown rate limit.
- Parameters:
current (Optional[
float]) – The time in seconds since Unix epoch to update the rate limit at. If not supplied, thentime.time()is used.tokens (
int) – The amount of tokens to deduct from the rate limit.
- Returns:
The retry-after time in seconds if rate limited.
- Return type:
Optional[
float]
Exceptions¶
- exception stoat.ext.commands.CommandError(*args, message=None)[source]¶
The base exception type for all command related errors.
This inherits from
stoat.PyvoltException.This exception and exceptions inherited from it are handled in a special way as they are caught and passed into a special event from
Bot,CommandErrorEvent.
- exception stoat.ext.commands.ConversionError(*, converter, original)[source]¶
Exception raised when a Converter class raises non-CommandError.
This inherits from
CommandError.- converter¶
The converter that failed.
- exception stoat.ext.commands.MissingRequiredArgument(*, parameter)[source]¶
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from
UserInputError.
- exception stoat.ext.commands.MissingRequiredAttachment(*, parameter)[source]¶
Exception raised when parsing a command and a parameter that requires an attachment is not given.
This inherits from
UserInputError.
- exception stoat.ext.commands.ArgumentParsingError(*args, message=None)[source]¶
An exception raised when the parser fails to parse an user’s input.
This inherits from
UserInputError.There are child classes that implement more granular parsing errors for i18n purposes.
- exception stoat.ext.commands.UnexpectedQuoteError(*, quote)[source]¶
An exception raised when the parser encounters a quote mark inside a non-quoted string.
This inherits from
ArgumentParsingError.
- exception stoat.ext.commands.InvalidEndOfQuotedStringError(*, received)[source]¶
An exception raised when a space is expected after the closing quote in a string but a different character is found.
This inherits from
ArgumentParsingError.
- exception stoat.ext.commands.ExpectedClosingQuoteError(*, close_quote)[source]¶
An exception raised when a quote character is expected but not found.
This inherits from
ArgumentParsingError.
- exception stoat.ext.commands.BadArgument(*args, message=None)[source]¶
Exception raised when a parsing or conversion failure is encountered on an argument to pass into a command.
This inherits from
UserInputError
- exception stoat.ext.commands.BadUnionArgument(*, param, converters, errors)[source]¶
Exception raised when a
typing.Unionconverter fails for all its associated types.This inherits from
UserInputError.- param¶
The parameter that failed being converted.
- Type:
- converters¶
A tuple of converters attempted in conversion, in order of failure.
- Type:
Tuple[Type,
...]
- errors¶
A list of errors that were caught from failing the conversion.
- Type:
List[
CommandError]
- exception stoat.ext.commands.BadLiteralArgument(*, param, literals, errors, argument='')[source]¶
Exception raised when a
typing.Literalconverter fails for all its associated values.This inherits from
UserInputError.- param¶
The parameter that failed being converted.
- Type:
- literals¶
A tuple of values compared against in conversion, in order of failure.
- Type:
Tuple[Any,
...]
- errors¶
A list of errors that were caught from failing the conversion.
- Type:
List[
CommandError]
- exception stoat.ext.commands.PrivateMessageOnly(*, message=None)[source]¶
Exception raised when an operation does not work outside of private message contexts.
This inherits from
CheckFailure.
- exception stoat.ext.commands.NoPrivateMessage(*, message=None)[source]¶
Exception raised when an operation does not work in private message contexts.
This inherits from
CheckFailure.
- exception stoat.ext.commands.CheckFailure(*args, message=None)[source]¶
Exception raised when the predicates in
Command.checkshave failed.This inherits from
CommandError
- exception stoat.ext.commands.CheckAnyFailure(checks, errors)[source]¶
Exception raised when all predicates in
check_any()fail.This inherits from
CheckFailure.- errors¶
A list of errors that were caught during execution.
- Type:
List[
CheckFailure]
- exception stoat.ext.commands.CommandNotFound(*args, message=None)[source]¶
Exception raised when a command is attempted to be invoked but no command under that name is found.
This is not raised for invalid subcommands, rather just the initial main command that is attempted to be invoked.
This inherits from
CommandError.
- exception stoat.ext.commands.DisabledCommand(*args, message=None)[source]¶
Exception raised when the command being invoked is disabled.
This inherits from
CommandError.
- exception stoat.ext.commands.CommandInvokeError(*, original)[source]¶
Exception raised when the command being invoked raised an exception.
This inherits from
CommandError.
- exception stoat.ext.commands.TooManyArguments(*args, message=None)[source]¶
Exception raised when the command was passed too many arguments and its
Command.ignore_extraattribute was not set toTrue.This inherits from
UserInputError
- exception stoat.ext.commands.UserInputError(*args, message=None)[source]¶
The base exception type for errors that involve errors regarding user input.
This inherits from
CommandError.
- exception stoat.ext.commands.CommandOnCooldown(*, cooldown, retry_after, type)[source]¶
Exception raised when the command being invoked is on cooldown.
This inherits from
CommandError.- cooldown¶
A class with attributes
rateandpersimilar to thecooldown()decorator.- Type:
- type¶
The type associated with the cooldown.
- Type:
- exception stoat.ext.commands.MaxConcurrencyReached(*, number, per)[source]¶
Exception raised when the command being invoked has reached its maximum concurrency.
This inherits from
CommandError.- per¶
The bucket type passed to the
max_concurrency()decorator.- Type:
- exception stoat.ext.commands.NotOwner(*args, message=None)[source]¶
Exception raised when the message author is not the owner of the bot.
This inherits from
CheckFailure.
- exception stoat.ext.commands.MessageNotFound(*, argument)[source]¶
Exception raised when the message provided was not found in the channel.
This inherits from
BadArgument.
- exception stoat.ext.commands.MemberNotFound(*, argument)[source]¶
Exception raised when the member provided was not found in the bot’s cache.
This inherits from
BadArgument.
- exception stoat.ext.commands.ServerNotFound(*, argument)[source]¶
Exception raised when the server provided was not found in the bot’s cache.
This inherits from
BadArgument.
- exception stoat.ext.commands.UserNotFound(*, argument)[source]¶
Exception raised when the user provided was not found in the bot’s cache.
This inherits from
BadArgument.
- exception stoat.ext.commands.ChannelNotFound(*, argument)[source]¶
Exception raised when the bot can not find the channel.
This inherits from
BadArgument.
- exception stoat.ext.commands.ChannelNotReadable(*, argument)[source]¶
Exception raised when the bot does not have permission to read messages in the channel.
This inherits from
BadArgument.- argument¶
The channel supplied by the caller that was not readable.
- Type:
- exception stoat.ext.commands.RoleNotFound(*, argument)[source]¶
Exception raised when the bot can not find the role.
This inherits from
BadArgument.
- exception stoat.ext.commands.BadInviteArgument(*, argument)[source]¶
Exception raised when the invite is invalid.
This inherits from
BadArgument.
- exception stoat.ext.commands.EmojiNotFound(*, argument)[source]¶
Exception raised when the bot can not find the emoji.
This inherits from
BadArgument.
- exception stoat.ext.commands.BadBoolArgument(*, argument)[source]¶
Exception raised when a boolean argument was not convertable.
This inherits from
BadArgument.
- exception stoat.ext.commands.RangeError(*, value, minimum, maximum)[source]¶
Exception raised when an argument is out of range.
This inherits from
BadArgument
- exception stoat.ext.commands.MissingPermissions(*args, missing_permissions)[source]¶
Exception raised when the command invoker lacks permissions to run a command.
This inherits from
CheckFailure.
- exception stoat.ext.commands.BotMissingPermissions(*args, missing_permissions)[source]¶
Exception raised when the bot’s member lacks permissions to run a command.
This inherits from
CheckFailure.
- exception stoat.ext.commands.MissingRole(*, missing_role)[source]¶
Exception raised when the command invoker lacks a role to run a command.
This inherits from
CheckFailure.- missing_role¶
The required role that is missing. This is the parameter passed to
has_role().- Type:
- exception stoat.ext.commands.BotMissingRole(*, missing_role)[source]¶
Exception raised when the bot’s member lacks a role to run a command.
This inherits from
CheckFailure.- missing_role¶
The required role that is missing. This is the parameter passed to
has_role().- Type:
- exception stoat.ext.commands.MissingAnyRole(*, missing_roles)[source]¶
Exception raised when the command invoker lacks any of the roles specified to run a command.
This inherits from
CheckFailure.- missing_roles¶
The roles that the invoker is missing. These are the parameters passed to
has_any_role().- Type:
List[
str]
- exception stoat.ext.commands.BotMissingAnyRole(*, missing_roles)[source]¶
Exception raised when the bot’s member lacks any of the roles specified to run a command.
This inherits from
CheckFailure.- missing_roles¶
The roles that the bot’s member is missing. These are the parameters passed to
has_any_role().- Type:
List[
str]
- exception stoat.ext.commands.NSFWChannelRequired(*, channel)[source]¶
Exception raised when a channel does not have the required NSFW setting.
This inherits from
CheckFailure.
- exception stoat.ext.commands.ExtensionError(*args, message=None, name)[source]¶
Base exception for extension related errors.
This inherits from
DiscordException.
- exception stoat.ext.commands.ExtensionAlreadyLoaded(*, name)[source]¶
An exception raised when an extension has already been loaded.
This inherits from
ExtensionError.
- exception stoat.ext.commands.ExtensionNotLoaded(*, name)[source]¶
An exception raised when an extension was not loaded.
This inherits from
ExtensionError.
- exception stoat.ext.commands.NoEntryPointError(*, name)[source]¶
An exception raised when an extension does not have a
setupentry point function.This inherits from
ExtensionError.
- exception stoat.ext.commands.ExtensionFailed(*, name, original)[source]¶
An exception raised when an extension failed to load during execution of the module or
setupentry point.This inherits from
ExtensionError.
- exception stoat.ext.commands.ExtensionNotFound(*, name)[source]¶
An exception raised when an extension is not found.
This inherits from
ExtensionError.
- exception stoat.ext.commands.CommandRegistrationError(*, name, alias_conflict=False)[source]¶
An exception raised when the command can’t be added because the name is already taken by a different command.
This inherits from
stoat.PyvoltException.
Exception Hierarchy¶
PyvoltException
ClientException