API Reference

The following section outlines the API of stoat.py’s command extension module.

Bots

Bot

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 to True allows using !    help. Defaults to False.

  • 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.

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.

Note

The before_invoke() and after_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.

Parameters:

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@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 type Context and can only raise exceptions inherited from CommandError.

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 Context sent to a group subcommand may only parse the parent command and not the subcommands due to it being invoked once per Bot.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 type Context and can only raise exceptions inherited from CommandError.

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 via add_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 via add_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.

Parameters:
  • http (bool) – Whether to clean up HTTP sessions.

  • cleanup_websocket (bool) – Whether to clean up WebSocket.

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() and check_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 per invoke() 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 with call_once=True in the Bot.add_check() call or using check_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’s gear_load() method will be propagated to the caller.

Parameters:

gear (Gear) – The gear to register to the bot.

Raises:
  • TypeError – The gear does not inherit from Gear.

  • 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, None is returned instead.

Parameters:

name (str) – The name of the gear you are requesting. This is equivalent to the name passed via keyword argument in class creation or the class name if unspecified.

Returns:

The gear that was requested. If not found, returns None.

Return type:

Optional[Gear]

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.

Parameters:

name (str) – The name of the gear to remove.

Returns:

The gear that was removed. None if not found.

Return type:

Optional[Gear]

property gears[source]

A read-only mapping of gear name to gear.

Type:

Mapping[str, Gear]

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, setup defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the bot.

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.test if you want to import foo/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 to None.

Raises:
  • ExtensionNotFound – The extension could not be imported. This is also raised if the name of the extension could not be resolved using the provided package parameter.

  • 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, the bot, similar to setup from load_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.test if you want to import foo/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 to None.

Raises:
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 a load_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.test if you want to import foo/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 to None.

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 provided package parameter.

  • 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]

await get_prefix(ctx, /)[source]

List[str]: Return prefixes possible in this context.

property self_bot[source]

Whether the bot is a self-bot (listens only to me).

Type:

bool

property traditional_bot[source]

Whether the bot is a traditional bot (does not listen to me).

Type:

bool

property user_bot[source]

Whether the bot is an userbot (listens to everyone).

Type:

bool

add_command(command, /)[source]

Adds a Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
all_subscriptions()[source]

List[EventSubscription[BaseEvent]]: Returns all event subscriptions.

property channels[source]

Mapping of cached channels.

Type:

Mapping[str, Channel]

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 PrivateChannelCreateEvent for 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 for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    GroupTooLarge

    The group exceeded maximum count of recipients.

    MissingPermission

    You do not have the proper permissions to add the recipient.

    NotFriends

    You’re not friends with the users you want to create group with.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    One of recipients was not found, or the provided file for icon was not found.

  • InternalServerError – Possible values for type:

Returns:

The new group.

Return type:

GroupChannel

await create_server(name, *, http_overrides=None, description=None, nsfw=None)[source]

This function is a coroutine.

Create a new server.

Fires ServerCreateEvent for 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 for type:

    Value

    Reason

    FailedValidation

    The payload was invalid.

    IsBot

    The current token belongs to bot account.

    TooManyChannels

    The instance was incorrectly configured. (?)

    TooManyServers

    You’re in too many servers than the instance allows.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • InternalServerError – Possible values for type:

Returns:

The created server.

Return type:

Server

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:

asyncio.Task

property dm_channel_ids[source]

Mapping of user IDs to cached DM channel IDs.

Type:

Mapping[str, str]

property dm_channels[source]

Mapping of user IDs to cached DM channels.

Type:

Mapping[str, DMChannel]

property emojis[source]

Mapping of cached emojis.

Type:

Mapping[str, Emoji]

await fetch_channel(channel_id, /, *, http_overrides=None)[source]

This function is a coroutine.

Fetch a Channel with the specified ID.

You must have view_channel to 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 for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

Returns:

The retrieved channel.

Return type:

Channel

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().

Parameters:
  • emoji (ULIDOr[BaseEmoji]) – The emoji to retrieve.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Raises:

NotFound – Possible values for type:

Value

Reason

NotFound

The emoji was not found.

Returns:

The retrieved emoji.

Return type:

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 populate channels.

Raises:
  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The server was not found.

Returns:

The retrieved server.

Return type:

stoat.Server

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().

Parameters:
  • user_id (str) – The user ID.

  • http_overrides (Optional[HTTPOverrideOptions]) – The HTTP request overrides.

Returns:

The user.

Return type:

User

get_channel(channel_id, /, *, partial=False)[source]

Retrieves a channel from cache.

Parameters:
  • channel_id (str) – The channel ID.

  • partial (bool) – Whether to return PartialMessageable instead of None if server was not found.

Returns:

The channel or None if not found.

Return type:

Optional[Union[Channel, PartialMessageable]]

get_command(name, /)[source]

Get a Command from 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 subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

get_emoji(emoji_id, /)[source]

Retrieves an emoji from cache.

Parameters:

emoji_id (str) – The emoji ID.

Returns:

The emoji or None if not found.

Return type:

Optional[Emoji]

get_read_state(channel_id, /)[source]

Retrieves a read state from cache.

Parameters:

channel_id (str) – The channel ID of read state.

Returns:

The read state or None if not found.

Return type:

Optional[ReadState]

get_server(server_id, /, *, partial=False)[source]

Retrieves a server from cache.

Parameters:
  • server_id (str) – The server ID.

  • partial (bool) – Whether to return BaseServer instead of None if server was not found.

Returns:

The server or None if not found.

Return type:

Optional[Union[Server, BaseServer]]

get_user(user_id, /, *, partial=False)[source]

Retrieves an user from cache.

Parameters:
  • user_id (str) – The user ID.

  • partial (bool) – Whether to return BaseUser instead of None if server was not found.

Returns:

The user or None if not found.

Return type:

Optional[Union[User, BaseUser]]

property http[source]

The HTTP client.

Type:

HTTPClient

property me[source]

The currently logged in user. None if not logged in.

Type:

Optional[OwnUser]

property members[source]

Mapping of cached server members.

Type:

Mapping[str, Mapping[str, Member]]

await on_library_error(shard, payload, exc, /)[source]

Handles library errors. By default, this logs exception.

Note

This won’t be called if handling Ready will 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]]

property read_states[source]

Mapping of cached read states.

Type:

Mapping[str, ReadState]

remove_command(name, /)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

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 None to the log_handler parameter.

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 None then the library will not set up anything logging related. Logging will still work if None is 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 the log_handler parameter is not None. Defaults to logging.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 to True then 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]

property servers[source]

Mapping of cached servers.

Type:

Mapping[str, Server]

property settings[source]

The current user settings.

Type:

UserSettings

await setup_hook()[source]

This function is a coroutine.

A hook that is called when client starts up.

property shard[source]

The Stoat WebSocket client.

Type:

Shard

await start()[source]

This function is a coroutine.

Starts up the client.

Calls setup_hook() before connecting.

property state[source]

The controller for all entities and components.

Type:

State

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 to False.

property system[source]

The Stoat sentinel user.

Type:

User

property user[source]

The currently logged in user. None if not logged in.

Alias to me.

Type:

Optional[OwnUser]

property users[source]

Mapping of cached users.

Type:

Mapping[str, User]

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 timeout parameter is passed onto asyncio.wait_for(). By default, it does not timeout. Note that this does propagate the asyncio.TimeoutError for 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 raising asyncio.TimeoutError.

  • manual_process (bool) – Whether to not process the event at all when it gets dispatched. Defaults to False.

  • stop_dispatching_on_success (bool) – Whether to stop dispatching when event arrives. Defaults to True.

Raises:
Returns:

The subscription. This can be await’ed.

Return type:

Union[TemporarySubscription, TemporarySubscriptionList]

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

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_prefix attribute.

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_prefix attribute.

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

when_mentioned()

Event Reference

CommandErrorEvent

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.

context

The invocation context.

Type:

Context

error

The error that was raised.

Type:

CommandError

await abefore_dispatch()[source]

This function is a coroutine.

Asynchronous version of before_dispatch().

await aprocess()[source]

This function is a coroutine.

Asynchronous version of process().

before_dispatch()[source]

Called before handlers are invoked.

cancel()[source]

Cancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

is_canceled

Whether the event is canceled.

Type:

bool

process()[source]

Any: Called when handlers got invoked and temporary subscriptions were handled and removed.

set_canceled(value, /)[source]

Whether to cancel event processing (updating cache) or not.

uncancel()[source]

Uncancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

CommandEvent

Attributes
Methods
class stoat.ext.commands.CommandEvent(*, is_canceled=False, context)[source]

Dispatched when a command is found and about to be invoked.

context

The invocation context.

Type:

Context

await abefore_dispatch()[source]

This function is a coroutine.

Asynchronous version of before_dispatch().

await aprocess()[source]

This function is a coroutine.

Asynchronous version of process().

before_dispatch()[source]

Called before handlers are invoked.

cancel()[source]

Cancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

is_canceled

Whether the event is canceled.

Type:

bool

process()[source]

Any: Called when handlers got invoked and temporary subscriptions were handled and removed.

set_canceled(value, /)[source]

Whether to cancel event processing (updating cache) or not.

uncancel()[source]

Uncancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

CommandCompletionEvent

Attributes
Methods
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().

await aprocess()[source]

This function is a coroutine.

Asynchronous version of process().

before_dispatch()[source]

Called before handlers are invoked.

cancel()[source]

Cancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

is_canceled

Whether the event is canceled.

Type:

bool

process()[source]

Any: Called when handlers got invoked and temporary subscriptions were handled and removed.

set_canceled(value, /)[source]

Whether to cancel event processing (updating cache) or not.

uncancel()[source]

Uncancels the event processing (updating cache).

Returns:

Whether the event was not canceled before.

Return type:

bool

context

The invocation context.

Type:

Context

Commands

Decorators

@stoat.ext.commands.command(name=None, cls=None, **attrs)[source]

A decorator that transforms a function into a Command or if called with group(), Group.

By default the help attribute is received automatically from the docstring of the function and is cleaned up with the use of inspect.cleandoc. If the docstring is bytes, then it is decoded into str using 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:
  • name (str) – The name to create the command with. By default this uses the function name unchanged.

  • cls – The class to construct with. By default this is Command. You usually do not change this.

  • attrs – Keyword arguments to pass into the construction of the class denoted by cls.

Raises:

TypeError – If the function is not a coroutine or is already a command.

@stoat.ext.commands.group(name=None, cls=None, **attrs)[source]

A decorator that transforms a function into a Group.

This is similar to the command() decorator but the cls parameter is set to Group by default.

Command

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.

name

The name of the command.

Type:

str

callback[source]

The coroutine that is executed when the command is called.

Type:

coroutine

help

The long help text for the command.

Type:

Optional[str]

brief

The short help text for the command.

Type:

Optional[str]

usage

A replacement for arguments in the default help text.

Type:

Optional[str]

aliases

The list of aliases the command can be invoked under.

Type:

Union[List[str], Tuple[str]]

enabled

A boolean that indicates if the command is currently enabled. If the command is invoked while it is disabled, then DisabledCommand is raised to the CommandErrorEvent event. Defaults to True.

Type:

bool

parent

The parent group that this command belongs to. None if there isn’t one.

Type:

Optional[Group]

gear[source]

The gear that this command belongs to. None if there isn’t one.

Type:

Optional[Gear]

checks

A list of predicates that verifies if the command could be executed with the given Context as the sole parameter. If an exception is necessary to be thrown to signal failure, then one inherited from CommandError should be used. Note that if the checks fail then CheckFailure exception is raised to the CommandErrorEvent event.

Type:

List[Callable[[Context], bool]]

description

The message prefixed into the default help command.

Type:

str

hidden

If True, the default help command does not show this in the help output.

Type:

bool

rest_is_raw

If False and a keyword-only argument is provided then the keyword only argument is stripped and handled as if it was a regular argument that handles MissingRequiredArgument and default values in a regular matter rather than passing the rest completely raw. If True then the keyword-only argument will pass in the rest of the arguments in a completely raw matter. Defaults to False.

Type:

bool

invoked_subcommand

The subcommand that was invoked, if any.

Type:

Optional[Command]

require_var_positional

If True and a variadic positional argument is specified, requires the user to specify at least one argument. Defaults to False.

Type:

bool

ignore_extra

If True, ignores extraneous strings passed to a command if all its requirements are met (e.g. ?foo a b c when only expecting a and b). Otherwise CommandErrorEvent is dispatched and local error handlers are called with TooManyArguments.

Defaults to True.

Type:

bool

cooldown_after_parsing

If True, cooldown processing is done after argument parsing, which calls converters. If False then cooldown processing is done first and then the converters are called second. Defaults to False.

Type:

bool

extras

A dict of user provided extras to attach to the Command.

Note

This object may be copied by the library.

Type:

dict

@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.

Parameters:

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@error[source]

A decorator that registers a coroutine as a local error handler.

A local error handler is an CommandErrorEvent event limited to a single command. However, the CommandErrorEvent is still invoked afterwards as the catch-all.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

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 Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or 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:

Command

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 None if 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 three the parent name would be one two.

Type:

str

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 is a.

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 three the qualified name would be one two three.

Type:

str

has_error_handler()[source]

bool: Checks whether the command has an error handler registered.

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

await can_run(ctx, /)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. 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:

bool

Group

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 Command and thus all options valid in Command are 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 to False.

Type:

bool

case_insensitive

Indicates if the group’s commands should be case insensitive. Defaults to False.

Type:

bool

@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.

Parameters:

coro (coroutine) – The coroutine to register as the pre-invoke hook.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_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 CommandErrorEvent event limited to a single command. However, the CommandErrorEvent is still invoked afterwards as the catch-all.

Parameters:

coro (coroutine) – The coroutine to register as the local error handler.

Raises:

TypeError – The coroutine passed is not actually a coroutine.

@group(*args, **kwargs)[source]

A shortcut decorator that invokes group() and adds it to the internal command list via add_command().

Returns:

A decorator that converts the provided method into a Group, adds it to the bot, then returns it.

Return type:

Callable[…, Group]

copy()[source]

Creates a copy of this Group.

Returns:

A new instance of this group.

Return type:

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 Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
await can_run(ctx, /)[source]

This function is a coroutine.

Checks if the command can be executed by checking all the predicates inside the checks attribute. 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:

bool

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 None if 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 three the parent name would be one two.

Type:

str

get_command(name, /)[source]

Get a Command from 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 subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

has_error_handler()[source]

bool: Checks whether the command has an error handler registered.

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 three the qualified name would be one two three.

Type:

str

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 Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

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 is a.

Type:

Optional[Group]

property signature[source]

Returns a POSIX-like signature useful for help command output.

Type:

str

update(**kwargs)[source]

Updates Command instance with updated attribute.

This works similarly to the command() decorator in terms of parameters in that they are passed to the Command or subclass constructors, sans the name and callback.

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

GroupMixin

class stoat.ext.commands.GroupMixin(*args, **kwargs)[source]

A mixin that implements common functionality for classes that behave similar to Group and are allowed to register commands.

all_commands

A mapping of command name to Command objects.

Type:

dict

case_insensitive

Whether the commands should be case insensitive. Defaults to False.

Type:

bool

@command(*args, **kwargs)[source]

A shortcut decorator that invokes command() and adds it to the internal command list via add_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 via add_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 Command into the internal list of commands.

This is usually not called, instead the command() or group() shortcut decorators are used instead.

Parameters:

command (Command) – The command to add.

Raises:
remove_command(name, /)[source]

Remove a Command from the internal list of commands.

This could also be used as a way to remove aliases.

Parameters:

name (str) – The name of the command to remove.

Returns:

The command that was removed. If the name is not valid then None is returned instead.

Return type:

Optional[Command]

for ... in walk_commands()[source]

An iterator that recursively walks through all commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the internal list of commands.

get_command(name, /)[source]

Get a Command from 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 subcommand bar of the group command foo. If a subcommand is not found then None is returned just as usual.

Parameters:

name (str) – The name of the command to get.

Returns:

The command that was requested. If not found, returns None.

Return type:

Optional[Command]

Gears

Gear

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 GearMeta are equally valid here.

get_commands()[source]

Returns the commands that are defined inside this gear.

Returns:

A list of Commands that are defined inside this gear, not including subcommands.

Return type:

List[Command]

property qualified_name[source]

Returns the gear’s specified name, not the class name.

Type:

str

property description[source]

Returns the gear’s description, typically the cleaned docstring.

Type:

str

for ... in walk_commands()[source]

An iterator that recursively walks through this gear’s commands and subcommands.

Yields:

Union[Command, Group] – A command or group from the gear.

get_listeners()[source]

Returns a list of (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.

has_error_handler()[source]

bool: Checks whether the gear has an error handler.

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 the Context.

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 the Context.

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 the Context.

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 CommandErrorEvent except 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.ABCMeta metaclass.

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
name

The gear name. By default, it is the name of the class with no modification.

Type:

str

description

The gear description. By default, it is the cleaned docstring of the class.

Type:

str

command_attrs

A list of attributes to apply to every command inside this gear. The dictionary is passed into the Command options 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:

dict

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 Command or its subclasses. These checks could be accessed via Command.checks.

These checks should be predicates that take in a single parameter taking a Context. If the check returns a False-like value then during invocation a CheckFailure exception is raised and sent to the CommandErrorEvent event.

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 to CommandErrorEvent.

A special attribute named predicate is 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 predicate is 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!')
Parameters:

predicate (Callable[[Context], bool]) – The predicate to check if the command should be invoked.

@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 CheckAnyFailure is raised to signal the failure. It inherits from CheckFailure.

Note

The predicate attribute for this function is a coroutine.

Parameters:

*checks (Callable[[Context], bool]) – An argument list of checks that have been decorated with the check() decorator.

Raises:

TypeError – A check passed has not been decorated with the check() 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, MissingRole if the user is missing a role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

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, MissingPermissions that is inherited from CheckFailure.

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 return True.

Similar to has_role(), the IDs passed in must be exact.

This check raises one of two special exceptions, MissingAnyRole if the user is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

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, BotMissingRole if the bot is missing the role, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

@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, BotMissingPermissions that is inherited from CheckFailure.

@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, BotMissingAnyRole if the bot is missing all roles, or NoPrivateMessage if it is used in a private message. Both inherit from CheckFailure.

@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 type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in CommandErrorEvent and 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 type Context and must return a Cooldown or None. If None is 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 type which must be of enum type BucketType.

If a cooldown is triggered, then CommandOnCooldown is triggered in CommandErrorEvent and 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 or None if 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 Command or 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.server would allow it to be used up to number times per server.

  • wait (bool) – Whether the command should wait for the queue to be over. If this is set to False then instead of waiting until the command can run again, the command raises MaxConcurrencyReached to its error handler. If this is set to True then 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, NoPrivateMessage that is inherited from CheckFailure.

@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, PrivateMessageOnly that is inherited from CheckFailure.

@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, NotOwner that is derived from CheckFailure.

@stoat.ext.commands.is_nsfw()[source]

A check() that checks if the channel is a NSFW channel.

This check raises a special exception, NSFWChannelRequired that is derived from CheckFailure.

If used on hybrid commands, this will be equivalent to setting the application command’s nsfw attribute to True. In an unsupported context, such as a subcommand, this will still fallback to applying the check.

Context

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.

author[source]

The user who created this context.

Type:

Union[Member, User]

author_id

The user’s ID who created this context.

Type:

str

bot

The bot in this context.

Type:

Bot

channel

The channel the context was created in.

Type:

Union[TextableChannel, PartialMessageable]

command

The command used in this context.

Type:

Optional[Command]

command_failed

Whether invoking the command failed.

Type:

bool

label

The substring used to invoke the command. May be empty sometimes.

Type:

str

me

The bot user in this context.

Type:

Union[Member, OwnUser]

message

The message that caused this context to be created.

Type:

Message

prefix

The prefix used to invoke command. May be empty sometimes.

Type:

str

server

The server this command invoked in.

Type:

Optional[Server]

shard

The shard the context was created on.

Type:

Shard

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]

get_channel_id()[source]

str: Retrieves the channel’s ID, if possible.

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_channel to do this.

Fires MessageAckEvent for 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 for type:

    Value

    Reason

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

await begin_typing(*, http_overrides=None)[source]

Begins typing in channel, until end_typing() is called.

await end_typing(*, http_overrides=None)[source]

Ends typing in channel.

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:

str

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 for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to view the channel.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/message was not found.

  • InternalServerError – Possible values for type:

Returns:

The retrieved message.

Return type:

Message

get_message(message_id, /)[source]

Retrieves a channel message from cache.

Parameters:

message_id (str) – The message ID.

Returns:

The message or None if not found.

Return type:

Optional[Message]

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_history to 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 nearby is 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 to latest

  • nearby (Optional[ULIDOr[BaseMessage]]) –

    The message to search around.

    Providing this parameter will discard before, after and sort parameters.

    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 for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to read the message history.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

Returns:

The messages retrieved.

Return type:

List[Message]

property messages[source]

Returns all messages in this channel.

Type:

Mapping[str, 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 query and pinned, only one parameter can be provided, otherwise a HTTPException will be thrown with InvalidOperation type.

You must have read_message_history to 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 nearby is 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 to latest

  • nearby (Optional[ULIDOr[BaseMessage]]) –

    The message to search around.

    Providing this parameter will discard before, after and sort parameters.

    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 for type:

    Value

    Reason

    FailedValidation

    One of before, after or nearby parameters were invalid IDs.

    InvalidOperation

    You provided both query and pinned parameters.

    IsBot

    The current token belongs to bot account.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to search messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel was not found.

  • InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

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_messages to do this.

If message mentions “@everyone” or “@online”, you must have mention_everyone to do that.

If message mentions any roles, you must mention_roles to do that.

Fires MessageCreateEvent and optionally MessageAppendEvent, 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_files to 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_embeds to provide this.

  • masquerade (Optional[MessageMasquerade]) –

    The message masquerade.

    You must have use_masquerade to provide this.

    If color is provided, use_masquerade is also required.

  • interactions (Optional[MessageInteractions]) –

    The message interactions.

    If reactions is provided, react is required.

  • 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_online parameter.

    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_everyone parameter.

    Note

    User accounts cannot set this to True.

Raises:
  • stoat.HTTPException – Possible values for type:

    Value

    Reason

    EmptyMessage

    The message was empty.

    FailedValidation

    The payload was invalid.

    InvalidFlagValue

    Both mention_everyone and mention_online were True.

    InvalidOperation

    The passed nonce was already used. One of reactions elements was invalid.

    InvalidProperty

    restrict_reactions was True but reactions was empty.

    IsBot

    The current token belongs to bot account.

    IsNotBot

    The current token belongs to user account.

    PayloadTooLarge

    The message was too large.

    TooManyAttachments

    You provided more attachments than allowed on this instance.

    TooManyEmbeds

    You provided more embeds than allowed on this instance.

    TooManyReplies

    You were replying to more messages than was allowed on this instance.

  • Unauthorized – Possible values for type:

    Value

    Reason

    InvalidSession

    The current bot/user token is invalid.

  • Forbidden – Possible values for type:

    Value

    Reason

    MissingPermission

    You do not have the proper permissions to send messages.

  • NotFound – Possible values for type:

    Value

    Reason

    NotFound

    The channel/file/reply was not found.

  • stoat.InternalServerError – Possible values for type:

    Value

    Reason

    Populated attributes

    DatabaseError

    Something went wrong during querying database.

    collection, operation

    InternalError

    Somehow something went wrong during message creation.

Returns:

The message that was sent.

Return type:

Message

Converters

Methods
class stoat.ext.commands.Converter(*args, **kwargs)[source]

The base class of custom converters that require the Context to be passed to be useful.

This allows you to implement converters that function similar to the special cased stoat classes.

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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class stoat.ext.commands.BaseConverter(*args, **kwargs)[source]

Converts to a Base.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by username#discriminator.

  4. Lookup by user name.

  5. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class stoat.ext.commands.MessageConverter(*args, **kwargs)[source]

Converts to a stoat.Message.

The lookup strategy is as follows (in order):

  1. Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. Lookup by message ID (the message must be in the context channel)

  3. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class stoat.ext.commands.BaseMessageConverter(*args, **kwargs)[source]

Converts to a stoat.BaseMessage.

The creation strategy is as follows (in order):

  1. By “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)

  2. By message ID (The message is assumed to be in the context channel.)

  3. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by channel URL.

  4. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by channel URL.

  4. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. Lookup by mention.

  3. Lookup by channel URL.

  4. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID

  2. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
class stoat.ext.commands.ServerConverter(*args, **kwargs)[source]

Converts to a Server.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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 NoPrivateMessage exception.

The lookup strategy is as follows (in order):

  1. Lookup by ID.

  2. Lookup by mention.

  3. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

Raises:
  • CommandError – A generic exception occurred when converting the argument.

  • BadArgument – The converter failed to convert the argument.

Methods
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):

  1. Lookup by ID.

  2. Lookup by extracting ID from the emoji.

  3. 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 CommandError derived exception as it will properly propagate to the error handlers.

Note that if this method is called manually, Exception should be caught to handle the cases where a subclass does not explicitly inherit from CommandError.

Parameters:
  • ctx (Context) – The invocation context that the argument is being used in.

  • argument (str) – The argument that is being converted.

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 hello would pass numbers with [1, 2, 3, 4, 5, 6] and reason with hello.

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:
  • ctx (Context) – The invocation context to run the converters under.

  • converter (Any) – The converter to run, this corresponds to the annotation in the function.

  • argument (str) – The argument to convert to.

  • param (Parameter) – The parameter being converted. This is mainly for error reporting.

Raises:

CommandError – The converter failed to convert.

Returns:

The resulting conversion.

Return type:

Any

Defaults

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 required[source]

Whether this parameter is required.

Type:

bool

property converter[source]

The converter that should be used for this parameter.

property description[source]

The description of this parameter.

Type:

Optional[str]

property displayed_default[source]

The displayed default in Command.signature.

Type:

Optional[str]

property displayed_name[source]

The name that is displayed to the user.

Type:

Optional[str]

await get_default(ctx, /)[source]

This function is a coroutine.

Gets this parameter’s default value.

Parameters:

ctx (Context) – The invocation context that is used to get the default argument.

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 Context argument.

  • description (str) – The description of this parameter.

  • displayed_default (str) – The displayed default in Command.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.Author

A default Parameter which returns the author for this context.

stoat.ext.commands.CurrentChannel

A default Parameter which returns the channel for this context.

stoat.ext.commands.CurrentServer

A default Parameter which returns the server for this context. This will never be None. If the command is called in a DM context then NoPrivateMessage is raised to the error handlers.

Cooldowns

class stoat.ext.commands.MaxConcurrency(number, *, per, wait)[source]
Attributes
Methods
class stoat.ext.commands.Cooldown(rate, per)[source]

Represents a cooldown for a command.

rate

The total number of tokens available per per seconds.

Type:

float

per

The length of the cooldown period in seconds.

Type:

float

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 then time.time() is used.

Returns:

The number of tokens available before the cooldown is to be applied.

Return type:

int

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, then time.time() is used.

Returns:

The number of seconds to wait before this cooldown will be reset.

Return type:

float

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, then time.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]

reset()[source]

Reset the cooldown to its initial state.

copy()[source]

Creates a copy of this cooldown.

Returns:

A new instance of this cooldown.

Return type:

Cooldown

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.

Type:

stoat.ext.commands.Converter

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

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.

parameter

The argument that is missing.

Type:

Parameter

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.

parameter

The argument that is missing an attachment.

Type:

Parameter

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.

quote

The quote mark that was found inside the non-quoted string.

Type:

str

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.

received

The character found instead of the expected string.

Type:

str

exception stoat.ext.commands.ExpectedClosingQuoteError(*, close_quote)[source]

An exception raised when a quote character is expected but not found.

This inherits from ArgumentParsingError.

close_quote

The quote character expected.

Type:

str

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.Union converter fails for all its associated types.

This inherits from UserInputError.

param

The parameter that failed being converted.

Type:

inspect.Parameter

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.Literal converter fails for all its associated values.

This inherits from UserInputError.

param

The parameter that failed being converted.

Type:

inspect.Parameter

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]

argument

The argument’s value that failed to be converted. Defaults to an empty string.

Type:

str

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.checks have 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]

checks

A list of check predicates that failed.

Type:

List[Callable[[Context], bool]]

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.

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception stoat.ext.commands.TooManyArguments(*args, message=None)[source]

Exception raised when the command was passed too many arguments and its Command.ignore_extra attribute was not set to True.

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 rate and per similar to the cooldown() decorator.

Type:

Cooldown

type

The type associated with the cooldown.

Type:

BucketType

retry_after

The amount of seconds to wait before you can retry again.

Type:

float

exception stoat.ext.commands.MaxConcurrencyReached(*, number, per)[source]

Exception raised when the command being invoked has reached its maximum concurrency.

This inherits from CommandError.

number

The maximum number of concurrent invokers allowed.

Type:

int

per

The bucket type passed to the max_concurrency() decorator.

Type:

BucketType

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.

argument

The message supplied by the caller that was not found.

Type:

str

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.

argument

The member supplied by the caller that was not found.

Type:

str

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.

argument

The server supplied by the called that was not found.

Type:

str

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.

argument

The user supplied by the caller that was not found.

Type:

str

exception stoat.ext.commands.ChannelNotFound(*, argument)[source]

Exception raised when the bot can not find the channel.

This inherits from BadArgument.

argument

The channel supplied by the caller that was not found.

Type:

str

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:

ServerChannel

exception stoat.ext.commands.RoleNotFound(*, argument)[source]

Exception raised when the bot can not find the role.

This inherits from BadArgument.

argument

The role supplied by the caller that was not found.

Type:

str

exception stoat.ext.commands.BadInviteArgument(*, argument)[source]

Exception raised when the invite is invalid.

This inherits from BadArgument.

argument

The invite supplied by the caller that was not valid.

Type:

str

exception stoat.ext.commands.EmojiNotFound(*, argument)[source]

Exception raised when the bot can not find the emoji.

This inherits from BadArgument.

argument

The emoji supplied by the caller that was not found..

Type:

str

exception stoat.ext.commands.BadBoolArgument(*, argument)[source]

Exception raised when a boolean argument was not convertable.

This inherits from BadArgument.

argument

The boolean argument supplied by the caller that is not in the predefined list.

Type:

str

exception stoat.ext.commands.RangeError(*, value, minimum, maximum)[source]

Exception raised when an argument is out of range.

This inherits from BadArgument

minimum

The minimum value expected or None if there wasn’t one

Type:

Optional[Union[int, float]]

maximum

The maximum value expected or None if there wasn’t one

Type:

Optional[Union[int, float]]

value

The value that was out of range.

Type:

Union[int, float, str]

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.

missing_permissions

The required permissions that are missing.

Type:

List[str]

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.

missing_permissions

The required permissions that are missing.

Type:

List[str]

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:

str

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:

str

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.

channel

The channel that does not have NSFW enabled.

Type:

Channel

exception stoat.ext.commands.ExtensionError(*args, message=None, name)[source]

Base exception for extension related errors.

This inherits from DiscordException.

name

The extension that had an error.

Type:

str

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 setup entry 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 setup entry point.

This inherits from ExtensionError.

name

The extension that had the error.

Type:

str

original

The original exception that was raised. You can also get this via the __cause__ attribute.

Type:

Exception

exception stoat.ext.commands.ExtensionNotFound(*, name)[source]

An exception raised when an extension is not found.

This inherits from ExtensionError.

name

The extension that had the error.

Type:

str

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.

name

The command name that had the error.

Type:

str

alias_conflict

Whether the name that conflicts is an alias of the command we try to add.

Type:

bool

Exception Hierarchy