API Reference

Discord.py Changes

In order to make aspects of this library work, some aspects of the default Discord.py library have been modified. Though they present non-breaking behaviour, it’s important to note them here.

  • discord.abc.Messageable’s send method and discord.Message’s edit methods have been altered to have the components and ephemeral arguments. components refers to an instance of voxelbotutils.MessageComponents, and ephemeral refers to whether or not the sent message should be ephemeral (which only works with interactions responses - slash commands and components).

Utils

Bot

class voxelbotutils.MinimalBot(*args, **kwargs)

A minimal version of the VoxelBotUtils bot that inherits from discord.ext.commands.AutoShardedBot but gives new VBU features.

async get_application_id() int

Get the bot’s application client ID.

async create_message_log(messages: Union[List[discord.message.Message], discord.iterators.HistoryIterator]) str

Creates and returns an HTML log of all of the messages provided. This is an API method, and may raise an asyncio HTTP error.

Parameters

messages (typing.Union[typing.List[discord.Message], discord.iterators.HistoryIterator]) – The messages you want to create into a log.

Returns

The HTML for a log file.

Return type

str

async create_global_application_command(command: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand) voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand

Add a global slash command for the bot.

Parameters

command (interactions.ApplicationCommand) – The command that you want to add.

async create_guild_application_command(guild: discord.guild.Guild, command: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand) voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand

Add a guild-level slash command for the bot.

Parameters
  • guild (discord.Guild) – The guild you want to add the command to.

  • command (interactions.ApplicationCommand) – The command you want to add.

async bulk_create_global_application_commands(commands: List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]) List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]

Bulk add a global slash command for the bot.

Parameters

commands (typing.List[interactions.ApplicationCommand]) – The list of commands you want to add.

async bulk_create_guild_application_commands(guild: discord.guild.Guild, commands: List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]) List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]

Bulk add a guild-level slash command for the bot.

Parameters
  • guild (discord.Guild) – The guild you want to add the command to.

  • commands (typing.List[interactions.ApplicationCommand]) – The list of commands you want to add.

async get_global_application_commands() List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]

Add a global slash command for the bot.

Returns

A list of commands that have been added.

Return type

typing.List[interactions.ApplicationCommand]

async get_guild_application_commands(guild: discord.guild.Guild) List[voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand]

Add a guild-level slash command for the bot.

Parameters

guild (discord.Guild) – The guild you want to get commands for.

Returns

A list of commands that have been added.

Return type

typing.List[interactions.ApplicationCommand]

async delete_global_application_command(command: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand) None

Remove a global slash command for the bot.

Parameters

command (interactions.ApplicationCommand) – The command that you want to remove.

async delete_guild_application_command(guild: discord.guild.Guild, command: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand) None

Remove a guild-level slash command for the bot.

Parameters
  • guild (discord.Guild) – The guild that you want to remove the command on.

  • command (interactions.ApplicationCommand) – The command that you want to remove.

class voxelbotutils.Bot(config_file: str = 'config/config.toml', logger: Optional[logging.Logger] = None, activity: discord.activity.Activity = <Game name='Reconnecting...'>, status: discord.enums.Status = <Status.dnd: 'dnd'>, case_insensitive: bool = True, intents: Optional[discord.flags.Intents] = None, allowed_mentions: discord.mentions.AllowedMentions = AllowedMentions(everyone=False, users=True, roles=True, replied_user=True), *args, **kwargs)

A bot class that inherits from voxelbotutils.MinimalBot, detailing more VoxelBotUtils functions, as well as changing some of the default Discord.py library behaviour.

logger

A logger instance for the bot.

Type

logging.Logger

config

The config for the bot.

Type

dict

session

A session instance that you can use to make web requests.

Type

aiohttp.ClientSession

application_id

The ID of this bot application.

Type

int

database

The database connector, as connected using the data from your config file.

Type

DatabaseConnection

redis

The redis connector, as connected using the data from your config file.

Type

RedisConnection

stats

The stats connector, as connected using the data from your config file. May not be authenticated, but will fail silently if not.

Type

StatsdConnection

startup_method

The task that’s run when the bot is starting up.

Type

asyncio.Task

guild_settings

A dictionary from the guild_settings Postgres table.

Type

dict

user_settings

A dictionary from the user_settings Postgres table.

Type

dict

user_agent

The user agent that the bot should use for web requests as set in the config file. This isn’t used automatically anywhere, so it just here as a provided convenience.

Type

str

upgrade_chat

An UpgradeChat connector instance using the oauth information provided in your config file.

Type

upgradechat.UpgradeChat

clean_prefix

The default prefix for the bot.

Type

str

owner_ids

A list of the owners from the config file.

Type

typing.List[int]

embeddify

Whether or not messages should be embedded by default, as set in the config file.

Type

bool

__init__(config_file: str = 'config/config.toml', logger: Optional[logging.Logger] = None, activity: discord.activity.Activity = <Game name='Reconnecting...'>, status: discord.enums.Status = <Status.dnd: 'dnd'>, case_insensitive: bool = True, intents: Optional[discord.flags.Intents] = None, allowed_mentions: discord.mentions.AllowedMentions = AllowedMentions(everyone=False, users=True, roles=True, replied_user=True), *args, **kwargs)
Parameters
async startup()

Clears the custom caches for the bot (guild_settings and user_settings), re-reads the database tables for each of those items, and calls the voxelbotutils.Cog.cache_setup() method in each of the cogs again.

async fetch_support_guild() Optional[discord.guild.Guild]

Get the support guild as set in the bot’s config file.

Returns

The guild instance. Will be None if a guild ID has not been

provided, or cannot be found.

Return type

typing.Optional[discord.Guild]

Generate an invite link for the bot.

Parameters
  • base (str, optional) – The base URL that should be used for the invite command. For almost all cases, the default of https://discord.com/oauth2/authorize is probably fine.

  • client_id (int, optional) – The client ID that the invite command should use. Uses the passed argument, then the config's set client ID, and then the bot’s ID if nothing is found.

  • scope (str, optional) – The scope for the invite link.

  • response_type (str, optional) – The response type of the invite link.

  • redirect_uri (str, optional) – The redirect URI for the invite link.

  • guild_id (int, optional) – The guild ID that the invite link should default to.

  • permissions (discord.Permissions, optional) – A permissions object that should be used to make the permissions on the invite.

Returns

The URL for the invite.

Return type

str

async get_user_topgg_vote(user_id: int) bool

Returns whether or not the user has voted on Top.gg. If there’s no Top.gg token provided in your config file then this will always return False. This method doesn’t handle timeouts or errors in their API (such as outages); you are expected to handle them yourself.

Parameters

user_id (int) – The ID of the user you want to check.

Returns

Whether or not that user has registered a vote on Top.gg.

Return type

bool

get_event_webhook(event_name: str) Optional[discord.webhook.Webhook]

Get a discord.Webhook object based on the keys in the bot's config.

Parameters

event_name (str) – The name of the event you want to get a webhook for.

Returns

A webhook instance pointing to the URL as given.

Return type

typing.Optional[discord.Webhook]

async add_delete_reaction(message: discord.message.Message, valid_users: Optional[List[discord.user.User]] = None, *, delete: Optional[List[discord.message.Message]] = None, timeout: float = 60.0, wait: bool = False) None

Adds a delete reaction to the given message.

Parameters
  • message (discord.Message) – The message you want to add a delete reaction to.

  • valid_users (typing.List[discord.User], optional) – The users who have permission to use the message’s delete reaction.

  • delete (typing.List[discord.Message], optional) – The messages that should be deleted on clicking the delete reaction.

  • timeout (float, optional) – How long the delete reaction should persist for.

  • wait (bool, optional) – Whether or not to block (via async) until the delete reaction is pressed.

Raises

discord.HTTPException – The bot was unable to add a delete reaction to the message.

Sets a footer on the given embed based on the items in the bot's config.

Parameters

embed (discord.Embed) – The embed that you want to set a footer on.

get_extensions() List[str]

Gets a list of filenames of all the loadable cogs.

Returns

A list of the extensions found in the cogs/ folder,

as well as the cogs included with VoxelBotUtils.

Return type

typing.List[str]

load_all_extensions() None

Loads all the given extensions from voxelbotutils.Bot.get_extensions().

async set_default_presence(shard_id: Optional[int] = None) None

Sets the default presence for the bot as appears in the config file.

Parameters

shard_id (int, optional) – The shard to set the presence for.

reload_config() None

Re-reads the config file into cache.

get_context_message(messageable, content: str, *, embed: Optional[discord.embeds.Embed] = None, file: Optional[discord.file.File] = None, embeddify: Optional[bool] = None, image_url: Optional[str] = None, embeddify_file: bool = True, **kwargs) Tuple[str, discord.embeds.Embed]

Takes a set of messageable content and outputs a string/Embed tuple that can be pushed into a messageable object.

async launch_shard(gateway, shard_id: int, *, initial: bool = False)

Ask the shard manager if we’re allowed to launch.

async launch_shards()

Launch all of the shards using the shard manager.

async connect(*, reconnect=True)

This function is a coroutine.

Creates a websocket connection and lets the websocket listen to messages from Discord. This is a loop that runs the entire event system and miscellaneous aspects of the library. Control is not resumed until the WebSocket connection is terminated.

Parameters

reconnect (bool) – If we should attempt reconnecting, either due to internet failure or a specific failure on Discord’s part. Certain disconnects that lead to bad state will not be handled (such as invalid sharding payloads or bad tokens).

Raises
  • GatewayNotFound – If the gateway to connect to Discord is not found. Usually if this is thrown then there is a Discord API outage.

  • ConnectionClosed – The websocket connection has been terminated.

Cog

class voxelbotutils.Cog(*args, **kwargs)

A slightly modified cog class to allow for the cache_setup method and for the class’ logger instance.

bot

The bot instance that the cog was added to.

Type

Bot

logger

The logger that’s assigned to the cog instance. This will be used for logging command calls, even if you choose not to use it yourself.

Type

logging.Logger

qualified_name

The human-readable name for the cog.

class MyCog(voxelbotutils.Cog): pass
c = MyCog(bot)
c.qualified_name  # "My Cog"

class APICommands(voxelbotutils.Cog): pass
c = APICommands(bot)
c.qualified_name  # "API Commands"

class FuckMee6Owo(voxelbotutils.Cog): pass
c = FuckMee6Owo(bot)
c.qualified_name  # "Fuck Mee6 Owo"
Type

str

get_logger_name(*prefixes, sep: str = '.') str

Gets the name of the class with any given prefixes, with sep as a seperator. You tend to not need this yourself, but it is instead called internally by the bot when generating the logger instance.

async cache_setup(database: voxelbotutils.cogs.utils.database.DatabaseConnection)

A method that gets run when the bot’s startup method is run - intended for setting up cached information in the bot object that aren’t in the voxelbotutils.Bot.guild_settings or voxelbotutils.Bot.user_settings tables. This setup should clear your caches before setting them, as the voxelbotutils.Bot.startup() method may be called multiple times.

Command

class voxelbotutils.Command(*args, **kwargs)

A custom command class subclassing discord.ext.commands.Command so that we can add some more attirbutes to it. Unlike normal Discord.py, the cooldown_after_parsing attribute is set to True by default. Can be used in a normal @commands.command’s cls attribute, but easier is to just use this library’s @command;

@voxelbotutils.command()
async def example(self, ctx):
    ...
locally_handled_errors

A list of errors that are handled by the command’s on_error() method before being passed onto the main bot’s error handler.

Type

typing.List[discord.ext.commands.CommandError]

add_slash_command

Whether or not this command should be added as a slash command.

Type

bool

argument_descriptions

A list of descriptions for the command arguments to be used in slash commands.

Type

typing.List[str]

get_remaining_cooldown(ctx: discord.ext.commands.context.Context, current: Optional[float] = None) Optional[float]

Gets the remaining cooldown for a given command.

Parameters
  • ctx (commands.Context) – The context object for the command/author.

  • current (float, optional) – The current time.

Returns

The remaining time on the user’s cooldown or None.

Return type

typing.Optional[float]

async prepare(ctx: discord.ext.commands.context.Context)

This is entirely stolen from the original method so I could make prepare_cooldowns an async method.

https://github.com/Rapptz/discord.py/blob/a4d29e8cfdb91b5e120285b605e65be2c01f2c87/discord/ext/commands/core.py#L774-L795

async dispatch_error(ctx, error)

Like how we’d normally dispatch an error, but we deal with local lads

class voxelbotutils.Group(*args, **kwargs)
async can_run(ctx: discord.ext.commands.context.Context) bool

The normal discord.ext.Command.can_run() but it ignores cooldowns.

Parameters

ctx (commands.Context) – The command we want to chek if can be run.

Returns

Whether or not the command can be run.

Return type

bool

command(*args, **kwargs)

Add the usual voxelbotutils.Command to the mix.

group(*args, **kwargs)

Add the usual voxelbotutils.Group to the mix.

subcommand_group(*args, **kwargs)

Add the usual voxelbotutils.Group to the mix.

async dispatch_error(ctx, error)

Like how we’d normally dispatch an error, but we deal with local lads

Context

class voxelbotutils.Context(*args, **kwargs)

A modified version of the default discord.ext.commands.Context to allow for things like slash commands and interaction responses, as well as implementing Context.clean_prefix().

original_author_id

The ID of the original person to run the command. Persists through the bot’s sudo command, if you want to check the original author.

Type

int

clean_prefix

A clean version of the prefix that the command was invoked with.

Type

str

is_interaction

Whether or not the context was invoked via an interaction

Type

bool

async okay() None

Adds the okay hand reaction to a message.

async defer()

A defer method so we can use the same code for slash commands as we do for text commands.

get_mentionable_channel(channel_id: int, fallback: str = 'null') str

Get the mention string for a given channel ID.

Parameters
  • channel_id (int) – The ID of the object that you want to mention.

  • fallback (str, optional) – The string to fall back to if the object isn’t reachable.

Returns

The mention string.

Return type

str

get_mentionable_role(role_id: int, fallback: str = 'null') str

Get the mention string for a given role ID.

Parameters
  • role_id (int) – The ID of the object that you want to mention.

  • fallback (str, optional) – The string to fall back to if the object isn’t reachable.

Returns

The mention string.

Return type

str

DatabaseConnection

class voxelbotutils.DatabaseConnection(connection: Optional[asyncpg.connection.Connection] = None, transaction: Optional[asyncpg.transaction.Transaction] = None)

A helper class to wrap around an asyncpg.Connection object. This class is written so you don’t need to interface with asyncpg directly (though you can if you want by using the conn attribute), and can be easily accessed via the Bot.database attribute.

Examples

# The database can be used via context
async with bot.database() as db:
    values = await db("SELECT user_id FROM user_settings WHERE enabled=$1", True)
for row in values:
    print(row['user_id'])

# Or you can get a connection object that you can pass around
db = await bot.database.get_connection()
await db("DELETE FROM user_settings")
await db.disconnect()

# And transactions are also available
async with bot.database() as db:
    await db.start_transaction()
    await db("DELETE FROM guild_settings")
    await db.commit_transaction()
conn

The asyncpg connection object that we use internally.

Type

asyncpg.Connection

async classmethod create_pool(config: dict) None

Creates the database pool and plonks it in DatabaseConnection.pool.

Parameters

config (dict) – The configuration for the dictionary, passed directly to asyncpg.create_pool() as kwargs.

async classmethod get_connection() voxelbotutils.cogs.utils.database.DatabaseConnection

Acquires a connection to the database from the pool.

Returns

The connection that was aquired from the pool.

Return type

DatabaseConnection

async disconnect() None

Releases a connection from the pool back to the mix.

async start_transaction()

Creates a database object for a transaction.

async commit_transaction()

Commits the current transaction.

async execute_many(sql: str, *args) None

Runs an executemany query.

Parameters
  • sql (str) – The SQL that you want to run.

  • *args – A list of tuples of arguments to sent to the database.

async copy_records_to_table(table_name: str, *, records: List[Any], columns: Optional[Tuple[str]] = None, timeout: Optional[float] = None) str

Copies a series of records to a given table.

Parameters
  • table_name (str) – The name of the table you want to copy to.

  • records (typing.List[typing.Any]) – The list of records you want to input to the database.

  • columns (typing.Tuple[str], optional) – The columns (in order) that you want to insert to.

  • timeout (float, optional) – The timeout for the copy command.

Returns

The COPY status string.

Return type

str

RedisConnection

class voxelbotutils.RedisConnection(connection: Optional[aioredis.connection.RedisConnection] = None)

A wrapper for an aioredis.Redis object, provided in your bot object at Bot.redis for your convenience. Implemented are setter and getter methods for the redis database, as well as publish and subscribe via a decorator.

Examples

# In a command
async with bot.redis() as re:
    await re.publish("channel_name", {"foo": "bar"})
    await re.publish_str("channel_two", "baz")

# In a cog
@voxelbotutils.redis_channel_handler("channel_name")
async def handler(self, payload):
    self.logger.info(payload)
async classmethod create_pool(config: dict) None

Creates and connects the pool object.

Parameters

config (dict) – The config dictionary that should be passed directly to aioredis.create_redis_pool() directly as kwargs.

async classmethod get_connection()

Acquires a connection from the connection pool.

async disconnect() None

Releases a connection back into the connection pool.

async publish(channel: str, json: dict) None

Publishes some JSON to a given redis channel.

Parameters
  • channel (str) – The name of the channel that you want to publish redis to.

  • json (dict) – The JSON that you want to publish.

async publish_str(channel: str, message: str) None

Publishes a message to a given redis channel.

Parameters
  • channel (str) – The name of the channel that you want to publish redis to.

  • message (str) – The message that you want to publish.

async set(key: str, value: str) None

Sets a key/value pair in the redis DB.

Parameters
  • key (str) – The key you want to set the value of

  • value (str) – The data you want to set the key to

async get(key: str) str

Gets a value from the Redis DB given a key.

Parameters

key (str) – The key that you want to get from the Redis database.

Returns

The key from the database.

Return type

str

async mget(*keys) List[str]

Gets multiple values from the Redis DB given a list of keys.

Parameters

keys (str) – The keys that you want to get from the database.

Returns

The values from the Redis database associated with the given keys.

Return type

typing.List[str]

StatsdConnection

class voxelbotutils.StatsdConnection(connection: Optional[aiodogstatsd.client.Client] = None)

A helper class to wrap around an aiodogstatsd.Client object so as to make it a little easier to use. Statsd is unique in my wrapper utils in that it’ll fail silently if there’s no connection to be made.

async classmethod get_connection() voxelbotutils.cogs.utils.statsd.StatsdConnection

Acquires a connection to the database from the pool.

Returns

The connection that was aquired from the pool.

Return type

StatsdConnection

async disconnect() None

Releases a connection from the pool back to the mix.

Embed

class voxelbotutils.Embed(*args, use_random_colour: bool = False, **kwargs)

A modification for Discord.py’s discord.Embed class to allow for args where D.py uses kwargs, as well as inbuilt random colour generation and setting the author field to an instance of a user.

Examples

embed = voxelbotutils.Embed(use_random_colour=True)
embed.set_author_to_user(bot.get_user(141231597155385344))

# You can also use a with statement if you want to have your
# IDE fold the embed code.
# There is no other use for the with statement.
with embed:
    embed.set_image("https://example.com/image.png")
__init__(*args, use_random_colour: bool = False, **kwargs)
Parameters
  • use_random_colour (bool, optional) – Whether or not to automatically use a random colour.

  • **kwargs – Default args that go do discord.Embed.

use_random_colour() voxelbotutils.cogs.utils.context_embed.Embed

Sets the colour for the embed to a random one.

Returns

The embed instance.

Return type

Embed

Sets the footer of the embed.

Parameters
  • text (str) – The text to use in the footer.

  • *args – Default args that go do discord.Embed.set_footer.

  • **kwargs – Default args that go do discord.Embed.set_footer.

Returns

The embed instance.

Return type

Embed

set_image(url: str) voxelbotutils.cogs.utils.context_embed.Embed

Sets the image of the embed.

Parameters

url (str) – The URL to set the image to.

Returns

The embed instance.

Return type

Embed

set_thumbnail(url: str) voxelbotutils.cogs.utils.context_embed.Embed

Sets the thumbnail of the embed.

Parameters

url (str) – The URL to set the thumbnail to.

Returns

The embed instance.

Return type

Embed

set_author_to_user(user: discord.user.User, use_nick: bool = False) voxelbotutils.cogs.utils.context_embed.Embed

Sets the author of the embed to a given Discord user.

Parameters
  • user (discord.User) – The user you want to set the author to.

  • use_nick (bool) – Whether to use the guild nickname or regular username.

Returns

The embed instance.

Return type

Embed

add_field(name: str, value: str, inline: bool = True) voxelbotutils.cogs.utils.context_embed.Embed

Adds a field to the embed without using kwargs.

Parameters
  • name (str) – The name of the field.

  • value (str) – The value of the field.

  • inline (bool, optional) – Whether or not to set the field as inline.

Returns

The embed instance.

Return type

Embed

get_field_by_key(key: str) dict

Return the data from a field given its key

Parameters

key (str) – The name of the field you want to get the data for

Returns

A dictionary of the attrs for that field

Return type

dict

Raises

KeyError – If the given key doesn’t exist in the embed

edit_field_by_index(index: int, *, name: Optional[str] = None, value: Optional[str] = None, inline: Optional[bool] = None) voxelbotutils.cogs.utils.context_embed.Embed

Edit a field in the embed using its index.

Parameters
  • index (int) – The index of the field you want to edit.

  • name (str, optional) – What you want to set the name to.

  • value (str, optional) – What you want to set the value to.

  • inline (bool, optional) – Whether or not the field should be inline.

Returns

The embed instance.

Return type

Embed

edit_field_by_key(key: str, *, name: Optional[str] = None, value: Optional[str] = None, inline: Optional[bool] = None) voxelbotutils.cogs.utils.context_embed.Embed

Edit a field in the embed using its name as a key.

Parameters
  • key (str) – The key of the field to edit, based on its name.

  • name (str, optional) – What you want to set the name to.

  • value (str, optional) – What you want to set the value to.

  • inline (bool, optional) – Whether or not the field should be inline.

Returns

The embed instance.

Return type

Embed

Raises

KeyError – If the given key isn’t present in the embed.

classmethod from_native(embed: discord.embeds.Embed) voxelbotutils.cogs.utils.context_embed.Embed

Upgrade a native embed into a VoxelBotUtils embed.

Parameters

embed (discord.Embed) – The embed that you want to upgrade.

Returns

The upgraded embed instance.

Return type

Embed

Paginator

class voxelbotutils.Paginator(data: Union[Sequence, Generator, Callable[[int], Any]], *, per_page: int = 10, formatter: Optional[Callable[[voxelbotutils.cogs.utils.paginator.Paginator, Sequence[Any]], Union[str, discord.embeds.Embed, dict]]] = None, remove_reaction: bool = False)

An automatic paginator util that takes a list and listens for reactions on a message to change the content.

# Items will automatically be cast to strings and joined
my_list = list(range(30))
p = voxelbotutils.Paginator(my_list, per_page=5)
await p.start(ctx, timeout=15)

# Alternatively you can give a function, which can return a string, an embed, or a dict
# that gets unpacked directly into the message's edit method
def my_formatter(menu, items):
    output = []
    for i in items:
        output.append(f"The {i}th item")
    output_string = "\n".join(output)
    embed = voxelbotutils.Embed(description=output_string)
    embed.set_footer(f"Page {menu.current_page + 1}/{menu.max_pages}")

p = voxelbotutils.Paginator(my_list, formatter=my_formatter)
await p.start(ctx)
__init__(data: Union[Sequence, Generator, Callable[[int], Any]], *, per_page: int = 10, formatter: Optional[Callable[[voxelbotutils.cogs.utils.paginator.Paginator, Sequence[Any]], Union[str, discord.embeds.Embed, dict]]] = None, remove_reaction: bool = False)
Parameters
  • data (typing.Union[typing.Sequence, typing.Generator, typing.Callable[[int], typing.Any]]) – The data that you want to paginate. If a generator or function is given then the max_pages will start as the string “?”, and the per_page parameter will be ignored - the formatter will be passed the content of whatever your generator returns. If a function is given, then you will be passed the page number as an argument - raising StopIteration from this function will cause the max_pages attribute to be set, and the page will go back to what it was previously.

  • per_page (int, optional) – The number of items that appear on each page. This argument only works for sequences

  • formatter (typing.Callable[['Paginator', typing.Sequence[typing.Any]], typing.Union[str, discord.Embed, dict]], optional) – A function taking the paginator instance and a list of things to display, returning a dictionary of kwargs that get passed directly into a discord.Message.edit().

async start(ctx: discord.ext.commands.context.Context, *, timeout: float = 120)

Start and handle a paginator instance.

Parameters
  • ctx (commands.Context) – The context instance for the called command.

  • timeout (float, optional) – How long you should wait between getting a reaction and timing out.

async get_page(page_number: int) List[Any]

Get a list of items that appear for a given page.

Parameters

page_number (int) – The page number to get.

Returns

The list of items that would be on the page.

Return type

typing.List[typing.Any]

TimeValue

class voxelbotutils.TimeValue(duration: float)

An object that nicely converts an integer value into an easily readable string. This util is also available as an argument converter for your commands, though it can be used outide of being a converter as well via use of the parse() method.

Examples

>>> value = voxelbotutils.TimeValue(606)
>>> value.clean
'10m6s'
>>> value.clean_spaced
'10m 6s'
>>> value = voxelbotutils.TimeValue.parse('10m6s')
>>> value.duration
606

Note

This does not support partial seconds, and can only support a max of about 68 years (2^31 seconds).

duration

The entire duration, in seconds, of the timevalue object.

Type

int

years

The number of years that the object represents.

Type

int

days

The number of days that the object represents.

Type

int

hours

The number of hours that the object represents.

Type

int

minutes

The number of minutes that the object represents.

Type

int

seconds

The number of seconds that the object represents.

Type

int

clean_full

A string form of the object in form “10 hours 3 minutes”.

Type

str

clean_spaced

A string form of the object in form “10h 3m”.

Type

str

clean

A string form of the object in form “10h3m”.

Type

str

delta

A timedelta for the entire timevalue object.

Type

datetime.timedelta

__init__(duration: float)
Parameters

duration (float) – The duration to be converted.

Warning

Provided values will be rounded up to the nearest integer.

Raises

InvalidTimeDuration – If the provided time duration was invalid.

static get_quotient_and_remainder(value: int, divisor: int)

A divmod wrapper that just catches a zero division error.

async classmethod convert(ctx: discord.ext.commands.context.Context, value: str) voxelbotutils.cogs.utils.time_value.TimeValue

Takes a value (1h/30m/10s/2d etc) and returns a TimeValue instance with the duration. Provided for use of the Discord.py module.

Parameters
  • ctx (commands.Context) – The current context object that we want to convert under.

  • value (str) – The value string to be converted.

Returns

A time value instance.

Return type

TimeValue

Raises

InvalidTimeDuration – If the time could not be successfully converted.

classmethod parse(value: str) voxelbotutils.cogs.utils.time_value.TimeValue

Takes a value (1h/30m/10s/2d etc) and returns a TimeValue instance with the duration.

Parameters

value (str) – The value string to be converted.

Returns

A time value instance.

Return type

TimeValue

Raises

InvalidTimeDuration – If the time could not be successfully converted.

TimeFormatter

class voxelbotutils.TimeFormatter(time: datetime.datetime)

A Python datetime formatter.

short_time

The given time formatted as “14:11”.

Type

str

long_time

The given time formatted as “14:11:44”.

Type

str

number_date

The given time formatted as “06/07/2021”.

Type

str

short_date

The given time formatted as “6 July 2021”.

Type

str

short_datetime

The given time formatted as “6 July 2021 14:11”.

Type

str

long_datetime

The given time formatted as “Tuesday, 6 July 2021 14:11”.

Type

str

relative_time

The given time formatted as “10 hours ago”.

Type

str

__init__(time: datetime.datetime)
Params:

time (dt): The time that you want to format.

ComponentMessage

class voxelbotutils.ComponentMessage(*, state, channel, data)
__init__(*, state, channel, data)
class voxelbotutils.ComponentWebhookMessage(*, state, channel, data)

Slash Commands

Slash commands also have their own page for a basic integration guide.

ApplicationCommand

class voxelbotutils.ApplicationCommand(name: str, description: str)

An instance of an application command.

name

The name of this command.

Type

str

description

The description for this command.

Type

str

options

A list of the options added to this command.

Type

typing.List[ApplicationCommandOption]

id

The ID of this application command.

Type

int

application_id

The application ID that this command is attached to.

Type

int

__init__(name: str, description: str)
Parameters
  • name (str) – The name of this command.

  • description (str) – The description for this command.

add_option(option: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOption)

Add an option to this command instance.

ApplicationCommandOption

class voxelbotutils.ApplicationCommandOption(name: str, type: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOptionType, description: str, default: Optional[str] = None, required: bool = True)

An option displayed in a given application command.

name

The name of this option.

Type

str

type

The type of this command option.

Type

ApplicationCommandOptionType

description

The description given to this argument.

Type

str

default

The default value given to the command option.

Type

typing.Any

required

Whether or not this option is required for the command to run.

Type

bool

choices

A list of choices that this command can take.

Type

typing.List[ApplicationCommandOptionChoice]

options

A list of options that go into the application command.

Type

typing.List[ApplicationCommandOption]

__init__(name: str, type: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOptionType, description: str, default: Optional[str] = None, required: bool = True)
Parameters
  • name (str) – The name of this option.

  • type (ApplicationCommandOptionType) – The type of this command option.

  • description (str) – The description given to this argument.

  • default (typing.Any) – The default value given to the command option.

  • required (bool) – Whether or not this option is required for the command to run.

add_choice(choice: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOptionChoice) None

Add a choice to this instance.

add_option(option: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOption) None

Add an option to this instance.

ApplicationCommandOptionChoice

class voxelbotutils.ApplicationCommandOptionChoice(name: str, value: Any)

The possible choices that an application command can take.

name

The name of this option.

Type

str

value

The value given to this option.

Type

str

__init__(name: str, value: Any)
Parameters
  • name (str) – The name of this option.

  • value (typing.Any) – The value given to this option.

ApplicationCommandOptionType

class voxelbotutils.ApplicationCommandOptionType(value)

The different types of option that an application command argument can have.

SUBCOMMAND = 1

If the option is a subcommand.

SUBCOMMAND_GROUP = 2

If the option is a subcommand group.

STRING = 3

If the option is a string.

INTEGER = 4

If the option is an integer.

BOOLEAN = 5

If the option is a boolean.

USER = 6

If the option is a user.

CHANNEL = 7

If the option is a channel.

ROLE = 8

If the option is a role.

Components

Components also have their own page for a basic integration guide.

InteractionMessageable

class voxelbotutils.InteractionMessageable(*args, **kwargs)

A messageable that allows you to send back responses to interaction payloads more easily.

Note

The interaciton messageable’s send method also implements ephemeral as a valid kwarg, but for ease of documentation, the send method remains undocumented, as aside from this it is unchanged from the rest of the messageable objects.

component

The component that triggered this interaction. It may be none if the interaction that triggered this wasn’t a component, such as when slash commands are used.

Type

typing.Optional[BaseComponent]

async defer(*, ephemeral: bool = False, defer_type: int = 5)

Send an acknowledge payload to Discord for the interaction. The send() method does this automatically if you haven’t called it yourself, but if you’re doing a time-intensive operation (anything that takes longer than 5 seconds to send a response), you may want to send the ack yourself so that Discord doesn’t discard your interaction.

Parameters

ephemeral (bool, optional) – Whether or not the ack is visible only to the user calling the command.

async respond(*args, **kwargs)

Send a type 4 response to Discord for the interaction. The send() method does this for you automatically if you use the wait=False kwarg.

ComponentInteractionPayload

class voxelbotutils.cogs.utils.interactions.components.ComponentInteractionPayload(*args, **kwargs)

An interaction messageable that comes from a component interaction.

async defer_update()

Sends a deferred update payload to Discord for this interaction.

async update_message(*args, **kwargs)

Sends an update to the original message as an interaction response.

async defer(*, ephemeral: bool = False, defer_type: int = 5)

Send an acknowledge payload to Discord for the interaction. The send() method does this automatically if you haven’t called it yourself, but if you’re doing a time-intensive operation (anything that takes longer than 5 seconds to send a response), you may want to send the ack yourself so that Discord doesn’t discard your interaction.

Parameters

ephemeral (bool, optional) – Whether or not the ack is visible only to the user calling the command.

async respond(*args, **kwargs)

Send a type 4 response to Discord for the interaction. The send() method does this for you automatically if you use the wait=False kwarg.

BaseComponent

class voxelbotutils.BaseComponent

The base message component for Discord UI interactions.

Note

You will not need to make instances of this class - make instances of the child classes of this instead.

DisableableComponent

class voxelbotutils.DisableableComponent

Bases: voxelbotutils.cogs.utils.interactions.components.models.BaseComponent

A message component that has a disabled flag.

Note

You will not need to make instances of this class - make instances of the child classes of this instead.

disable() None

Set the disabled flag on the current component.

enable() None

Unset the disabled flag on the current component.

ComponentHolder

class voxelbotutils.ComponentHolder(*components: List[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent])

A message component that holds other message components.

Note

You will not need to make instances of this class - make instances of the child classes of this instead.

__init__(*components: List[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent])
Parameters

*components – A list of the components that this component holder holds.

add_component(component: voxelbotutils.cogs.utils.interactions.components.models.BaseComponent)

Adds a component to this holder.

Parameters

component (BaseComponent) – The component that you want to add.

remove_component(component: voxelbotutils.cogs.utils.interactions.components.models.BaseComponent)

Removes a component from this holder.

Parameters

component (BaseComponent) – The component that you want to remove.

disable_components() None

Disables all of the components inside this component holder that inherit from DisableableComponent.

enable_components() None

Enables all of the components inside this component holder that inherit from DisableableComponent.

get_component(custom_id: str) Optional[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent]

Get a component from the internal components list using its custom_id attribute.

Parameters

custom_id (str) – The ID of the component that you want to find.

Returns

The component that was found, if any.

Return type

typing.Optional[BaseComponent]

MessageComponents

class voxelbotutils.MessageComponents(*components: List[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent])

Bases: voxelbotutils.cogs.utils.interactions.components.models.ComponentHolder

A set of components that can be added to a message.

classmethod boolean_buttons(yes_id: Optional[str] = None, no_id: Optional[str] = None)

Return a set of message components with yes/no buttons, ready for use. If provided, the given IDs will be used for the buttons. If not, the button custom IDs will be set to the strings “YES” and “NO”.

Parameters
  • yes_id (str, optional) – The custom ID of the yes button.

  • no_id (str, optional) – The custom ID of the no button.

classmethod add_buttons_with_rows(*buttons: voxelbotutils.cogs.utils.interactions.components.buttons.Button)

Adds a list of buttons, breaking into a new ActionRow automatically when it contains 5 buttons. This does not check that you’ve added fewer than 5 rows.

Parameters

*buttons (Button) – The buttons that you want to have added.

ActionRow

class voxelbotutils.ActionRow(*components: List[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent])

Bases: voxelbotutils.cogs.utils.interactions.components.models.ComponentHolder

The main UI component for adding and ordering components on Discord messages.

ButtonStyle

class voxelbotutils.ButtonStyle(value)

An enum of the available button styles.

PRIMARY

A blurple button.

SECONDARY

A grey button.

SUCCESS

A green button.

DANGER

A red button.

A button that navigates to a URL, and doesn’t dispatch an interaction create payload.

Button

class voxelbotutils.Button(label: Optional[str] = None, custom_id: Optional[str] = None, *, style: voxelbotutils.cogs.utils.interactions.components.buttons.ButtonStyle = ButtonStyle.PRIMARY, emoji: Optional[Union[str, discord.partial_emoji.PartialEmoji]] = None, url: Optional[str] = None, disabled: bool = False)

Bases: voxelbotutils.cogs.utils.interactions.components.models.DisableableComponent

A button as supported by the Discord UI.

__init__(label: Optional[str] = None, custom_id: Optional[str] = None, *, style: voxelbotutils.cogs.utils.interactions.components.buttons.ButtonStyle = ButtonStyle.PRIMARY, emoji: Optional[Union[str, discord.partial_emoji.PartialEmoji]] = None, url: Optional[str] = None, disabled: bool = False)
Parameters
  • label (str) – The label that is added to the button.

  • style (ButtonStyle, optional) – The style that the button should use.

  • custom_id (str, optional) – The custom ID that should be assigned to the button. If you don’t provide one, then a UUID1 is generated automatically. Buttons with the LINK style do not support the custom_id attribute, so it will be ignored.

  • emoji (typing.Union[str, discord.PartialEmoji], optional) – The emoji that should be added to the button.

  • url (str, optional) – The URL that the button points to. This is only supported when the LINK style is used.

  • disabled (bool, optional) – Whether or not the button is clickable.

Raises

ValueError – If a URL is passed and the style isn’t set to ButtonStyle.LINK or vice-vera, this will be raised.

disable() None

Set the disabled flag on the current component.

enable() None

Unset the disabled flag on the current component.

SelectOption

class voxelbotutils.SelectOption(label: str, value: str, *, description: Optional[str] = None, emoji: Optional[Union[str, discord.partial_emoji.PartialEmoji]] = None, default: Optional[bool] = None)

Bases: voxelbotutils.cogs.utils.interactions.components.models.BaseComponent

An option menu that can go into a voxelbotutils.SelectMenu object.

__init__(label: str, value: str, *, description: Optional[str] = None, emoji: Optional[Union[str, discord.partial_emoji.PartialEmoji]] = None, default: Optional[bool] = None)
Parameters
  • label (str) – The label that gets shown on the option.

  • value (str) – The value that this option will give back to the bot.

  • description (str, optional) – A description for the option.

  • emoji (typing.Union[str, discord.PartialEmoji], optional) – An emoji to be displayed with the option.

  • default (bool, optional) – Whether or not the option is selected by default.

SelectMenu

class voxelbotutils.SelectMenu(custom_id: str, options: List[voxelbotutils.cogs.utils.interactions.components.select_menu.SelectOption], placeholder: Optional[str] = None, min_values: Optional[int] = None, max_values: Optional[int] = None, disabled: bool = False)

Bases: voxelbotutils.cogs.utils.interactions.components.models.DisableableComponent

Discord’s dropdown component.

__init__(custom_id: str, options: List[voxelbotutils.cogs.utils.interactions.components.select_menu.SelectOption], placeholder: Optional[str] = None, min_values: Optional[int] = None, max_values: Optional[int] = None, disabled: bool = False)
Parameters
  • custom_id (str) – The custom ID for this component.

  • options (typing.List[SelectOption]) – The options that should be displayed in this component.

  • placeholder (str, optional) – The placeholder text for when nothing is selected.

  • min_values (int, optional) – The minimum amount of selectable values.

  • max_values (int, optional) – The maximum amount of selectable values.

  • disabled (bool, optional) – Whether or not the select menu is clickable.

disable() None

Set the disabled flag on the current component.

enable() None

Unset the disabled flag on the current component.

Checks

checks.is_config_set

voxelbotutils.checks.is_config_set(*config_keys)

Checks that your config has been set given the keys for the item. Items are run as __getitem__`s for the following item. So for a config where you want to check that `config[“api_keys”][“example”] has been set, you would write your check as is_config_set(“api_keys”, “example”).

Raises

ConfigNotSet – If the config item hasn’t been set for the bot.

checks.meta_command

voxelbotutils.checks.meta_command()

Stops users from being able to run this command. Should be caught and then reinvoked, or should have Context.invoke_meta set to True.

Examples

@voxelbotutils.command()
@voxelbotutils.checks.meta_command()
async def notrunnable(self, ctx, *args):
    '''This command can't be run by normal users, and will fail silently...'''

    await ctx.send('uwu time gamers')

@voxelbotutils.command()
async def runnable(self, ctx):
    '''But you can still run the command like this.'''

    ctx.invoke_meta = True
    await ctx.invoke(ctx.bot.get_command('notrunnable'))
Raises

InvokedMetaCommand – If the command was run without the meta tag being set.

checks.bot_is_ready

voxelbotutils.checks.bot_is_ready()

The check for whether or not the bot has processed all of its startup methods (as defined by the Bot.startup_method task being completed), as well as having populated the cache (as defined by Discord.py having set discord.ext.commands.Bot.is_ready to true).

Raises

BotNotReady – If the bot isn’t yet marked as ready.

checks.is_bot_support

voxelbotutils.checks.is_bot_support()

Checks whether or not the calling user has the bot support role, as defined in the bot’s configuration file (config.bot_support_role_id). As it checks a role ID, this will only work it the command in quesiton is called in a guild where the calling user has the given role.

Raises

NotBotSupport – If the given user isn’t a member of the bot’s support team.

checks.is_voter

voxelbotutils.checks.is_voter(timeout: float = 3.0)

A check to make sure the author of a given command is a voter on your bot’s Top.gg page. This only works if a Top.gg token is provided in your config (BotConfig.bot_listing_api_keys.topgg_token) and is valid. If one isn’t provided, the command will always raise voxelbotutils.errors.IsNotVoter.

Parameters

timeout (float, optional) – The amount of time to wait before considering their API to be down.

Raises
  • IsNotVoter – If the user is has not voted for the bot on Top.gg, or the bot doesn’t have a Top.gg token defined.

  • commands.CheckFailure – Top.gg’s API is unable to process our API request within the given time.

checks.is_upgrade_chat_subscriber

voxelbotutils.checks.is_upgrade_chat_subscriber(*any_item_names)

A check to see whether a given user is an UpgradeChat subscriber for any of the given item names, adding an upgrade_chat_items attribute to the context object with the given purchases. For example, if you wanted a command to only be runnable if someone is subscribed to an item called command_access via UpgradeChat, your check would be is_upgrade_chat_subscriber(“command_access”).

Raises
  • IsNotUpgradeChatSubscriber – If the user isn’t subscribing to the given item.

  • commands.CheckFailure – If the Upgrade.Chat API is unavailable.

checks.is_upgrade_chat_purchaser

voxelbotutils.checks.is_upgrade_chat_purchaser(*any_item_names)

A check to see whether a given user is an UpgradeChat purchaser for any of the given item names, adding an upgrade_chat_items attribute to the context object with the given purchases. For example, if you wanted a command to only be runnable if someone purchased the an item called command_access via UpgradeChat, your check would be is_upgrade_chat_purchaser(“command_access”).

Raises
  • IsNotUpgradeChatPurchaser – If the user hasn’t purchased the given item.

  • commands.CheckFailure – If the Upgrade.Chat API is unavailable.

checks.is_slash_command

voxelbotutils.checks.is_slash_command()

Checks that the command has been invoked from a slash command.

Raises

IsNotSlashCommand – If the command was not run as a slash command.

checks.is_not_slash_command

voxelbotutils.checks.is_not_slash_command()

Checks that the command has not been invoked from a slash command.

Raises

IsSlashCommand – If the command was run as a slash command.

checks.bot_in_guild

voxelbotutils.checks.bot_in_guild()

Checks that the bot is in the guild where this command is being called.

Raises

BotNotInGuild – If the bot isn’t in the guild where the command is being called.

Cooldowns

cooldown.cooldown

voxelbotutils.cooldown.cooldown(rate: int, per: int, type: discord.ext.commands.cooldowns.BucketType = <BucketType.default: 0>, *, cls: Optional[discord.ext.commands.cooldowns.Cooldown] = None) Callable
Parameters
  • rate (int) – How many times this command can be run.

  • per (int) – The time before which the cooldown for this command is reset.

  • type (commands.BucketType, optional) – The bucket that the cooldown should be applied for.

  • cls (commands.Cooldown, optional) – The cooldown class instance.

Returns

The decorator that should be applied to the command.

Return type

typing.Callable

cooldown.no_raise_cooldown

voxelbotutils.cooldown.no_raise_cooldown(*args, **kwargs)

cooldown.Cooldown

class voxelbotutils.cooldown.Cooldown(*, error: Optional[discord.ext.commands.errors.CommandOnCooldown] = None, mapping: Optional[voxelbotutils.cogs.utils.checks.cooldown.cooldown.CooldownMapping] = None)

A class handling the cooldown for an individual user. This is provided as a subclass of discord.ext.commands.Cooldown and provides a predicate() function that you can use to change aspects of a given command’s cooldown

default_cooldown_error

alias of discord.ext.commands.errors.CommandOnCooldown

default_mapping_class

alias of voxelbotutils.cogs.utils.checks.cooldown.cooldown.CooldownMapping

__init__(*, error: Optional[discord.ext.commands.errors.CommandOnCooldown] = None, mapping: Optional[voxelbotutils.cogs.utils.checks.cooldown.cooldown.CooldownMapping] = None)
Parameters
  • error (None, optional) – The error instance to be raised if the user is on cooldown.

  • mapping (CooldownMapping, optional) – The cooldown mapping to be used.

predicate(ctx) bool

A function that runs before each command call, so you’re able to update anything before the command runs. Most likely you’ll be using this to update the self.per attr so that cooldowns can be tailored to the individual. Everything this method returns is discarded. This method CAN be a coroutine.

get_tokens(current: Optional[float] = None) int

Gets the number of command calls that can still be made before hitting the rate limit

Parameters

current (float, optional) – The current time, or now (via time.time()). Is _not_ used to update self._last, since the command may not have actually been called.

Returns

The number of times this command has been used given the time limit.

Return type

int

update_rate_limit(current: Optional[float] = None) Optional[int]

Updates the rate limit for the command, as it has now been called.

Parameters

current (float, optional) – The current time, or now (via time.time()).

get_remaining_cooldown(current: Optional[float] = None) Optional[float]

Gets the remaining rate limit for the command.

reset() None

Resets the cooldown for the given command.

copy() discord.ext.commands.cooldowns.Cooldown

Returns a copy of the cooldown.

cooldown.GroupedCooldownMapping

class voxelbotutils.cooldown.GroupedCooldownMapping(key: str)

A grouped cooldown mapping class so that you can easily apply a single cooldown to multiple commands.

Examples

@voxelbotutils.command()
@voxelbotutils.cooldown.cooldown(
    1, 60, commands.BucketType.user,
    mapping=voxelbotutils.cooldown.GroupedCooldownMapping("group"))
async def commandone(self, ctx):
    '''These two commands will be subject to the same cooldown.'''

@voxelbotutils.command()
@voxelbotutils.cooldown.cooldown(
    1, 60, commands.BucketType.user,
    mapping=voxelbotutils.cooldown.GroupedCooldownMapping("group"))
async def commandtwo(self, ctx):
    '''These two commands will be subject to the same cooldown.'''
__init__(key: str)
Parameters

key (str) – The cooldown key that the commands will be grouped under.

cooldown.RoleBasedCooldown

class voxelbotutils.cooldown.RoleBasedCooldown(tiers: dict, **kwargs)

A cooldown that lets you set the cooldown for a command based on the user’s roles.

Example

@voxelbotutils.command()
@voxelbotutils.cooldown.cooldown(
    1, 60, commands.BucketType.user, cls=RoleBasedCooldown({742262426086670347: 5}))
async def example(self, ctx):
    '''This command will have a rate limit of 5 seconds if the user has a role with the ID 742262426086670347.'''
__init__(tiers: dict, **kwargs)
Parameters
  • tiers (dict) – The dictionary of {role_id: seconds} that should be used for this cooldown.

  • **kwargs – The default kwargs to be passed to the original cooldown class.

predicate(ctx: discord.ext.commands.context.Context)

Update the cooldown based on the given guild member.

Converters

converters.UserID

class voxelbotutils.converters.UserID

A conveter that takes the given value and tries to grab the ID from it. When used, this would provide the ID of the user. This isn’t guarenteed to be a real user, but rather an ID that looks like a user’s.

converters.ChannelID

class voxelbotutils.converters.ChannelID

A conveter that takes the given value and tries to grab the ID from it. When used, this would provide the ID of the channel. This isn’t guarenteed to be a real user, but rather an ID that looks like a user’s.

converters.BooleanConverter

class voxelbotutils.converters.BooleanConverter

Converts the given input into a boolean yes/no, defaulting to “no” if something couldn’t be properly converted rather than raising an error.

converters.ColourConverter

class voxelbotutils.converters.ColourConverter(*, allow_custom_colour_names: bool = True, allow_default_colours: bool = True)

The normal Discord discord.ext.commands.ColourConverter class but it contains a lot more colour names, as taken from Wikipedia, the CSS colour set, and a couple of extra ones that I thought were cute.

converters.FilteredUser

class voxelbotutils.converters.FilteredUser(*, allow_author: bool = False, allow_bots: bool = False)

A simple discord.ext.commands.UserConverter that doesn’t allow bots or the author to be passed into the function.

converters.FilteredMember

class voxelbotutils.converters.FilteredMember(*, allow_author: bool = False, allow_bots: bool = False)

A simple discord.ext.commands.MemberConverter that doesn’t allow bots or the author to be passed into the function.

Errors

errors.ConfigNotSet

exception voxelbotutils.errors.ConfigNotSet(message=None, *args)

This is a subclass of discord.ext.commands.DisabledCommand raised exclusively by the is_config_set check. For normal users, this should just say that the command is disabled.

errors.InvokedMetaCommand

exception voxelbotutils.errors.InvokedMetaCommand(message=None, *args)

Raised on any command decorated with voxelbotutils.checks.meta_command(). This stops users from running commands that you’ve made for internal use only, such as settings subcommands or commands that should only be invoked via discord.ext.commands.Bot.invoke().

errors.BotNotReady

exception voxelbotutils.errors.BotNotReady(message=None, *args)

The generic error for the bot failing the voxelbotutils.checks.bot_is_ready() check.

errors.IsNotVoter

exception voxelbotutils.errors.IsNotVoter(message=None, *args)

The error thrown when a particular user is not a voter on Top.gg, or when there’s no valid token set in the bot’s config (BotConfig.bot_listing_api_keys.topgg_token).

errors.NotBotSupport

exception voxelbotutils.errors.NotBotSupport

The generic error for the bot failing the voxelbotutils.checks.is_bot_support() check - is a subclass of discord.ext.commands.MissingRole.

errors.IsSlashCommand

exception voxelbotutils.errors.IsSlashCommand(message=None, *args)

Raised when a given command failes the voxelbotutils.checks.is_not_slash_command() check.

errors.IsNotSlashCommand

exception voxelbotutils.errors.IsNotSlashCommand(message=None, *args)

Raised when a given command failes the voxelbotutils.checks.is_slash_command() check.

errors.BotNotInGuild

exception voxelbotutils.errors.BotNotInGuild(message=None, *args)

Raised when a given command failes the voxelbotutils.checks.bot_in_guild() check.

errors.MissingRequiredArgumentString

exception voxelbotutils.errors.MissingRequiredArgumentString(param: str)

This is a version of discord.ext.commands.MissingRequiredArgument that just takes a string as a parameter so you can manually raise it inside commands.

param

The parameter that was missing from the command.

Type

str

errors.InvalidTimeDuration

exception voxelbotutils.errors.InvalidTimeDuration(value: str)

A conversion error for an invalid input passed to voxelbotutils.TimeValue.

Parameters

value (str) – The given value that was invalid.

value

The value that was given that failed to parse.

Type

str

errors.IsNotUpgradeChatPurchaser

exception voxelbotutils.errors.IsNotUpgradeChatPurchaser(item_names: str)

The error raised when the user is missing an UpradeChat purchase.

errors.IsNotUpgradeChatSubscriber

exception voxelbotutils.errors.IsNotUpgradeChatSubscriber

The error raised when the user is missing an UpradeChat subscription.

Websites

web.OauthGuild

class voxelbotutils.web.OauthGuild(bot, guild_data, user)

A guild object from an oauth integration.

id

The ID of the guild.

Type

int

name

The name of the guild.

Type

str

icon

The guild’s icon hash.

Type

str

icon_url

The guild’s icon.

Type

discord.Asset

owner_id

The ID of the owner for the guild. This will either be the ID of the authenticated user or 0.

Type

int

features

A list of features that the guild has.sa

Type

typing.List[str]

async fetch_guild(bot=None) Optional[discord.guild.Guild]

Fetch the original discord.Guild object from the API using the authentication from the bot given.

Parameters

bot – The bot object that you want to use to fetch the guild.

Returns

The guild instance.

Return type

typing.Optional[discord.Guild]

web.OauthUser

class voxelbotutils.web.OauthUser(user_data)

A user object from an oauth integration.

id

The ID of the user.

Type

int

username

The user’s username.

Type

str

avatar

The user’s avatar hash.

Type

str

avatar_url

The user’s avatar.

Type

discord.Asset

discriminator

The user’s discrimiator.

Type

str

public_flags

The user’s public flags.

Type

discord.PublicUserFlags

locale

The locale of the user.

Type

str

mfa_enabled

Whether or not the user has MFA enabled.

Type

bool

web.OauthMember

class voxelbotutils.web.OauthMember(bot, guild_data, user_data)

A user object from an oauth integration.

id

The ID of the user.

Type

int

username

The user’s username.

Type

str

avatar

The user’s avatar hash.

Type

str

avatar_url

The user’s avatar.

Type

discord.Asset

discriminator

The user’s discrimiator.

Type

str

public_flags

The user’s public flags.

Type

discord.PublicUserFlags

locale

The locale of the user.

Type

str

mfa_enabled

Whether or not the user has MFA enabled.

Type

bool

guild

The guild object that this member is a part of.

Type

OauthGuild

guild_permissions

The permissions that this member has on the guild.

Type

discord.Permissions

web.add_discord_arguments

voxelbotutils.web.add_discord_arguments(*, redirect_if_logged_out: Optional[str] = None, redirect_if_logged_in: Optional[str] = None)

This function is a wrapper around all routes. It takes the output and adds the user info and request to the returning dictionary It must be applied before the template decorator.

Parameters
  • redirect_if_logged_out (str, optional) – A location to direct the user to should they be logged out.

  • redirect_if_logged_in (str, optional) – A location to direct the user to if they are logged in already.

web.get_avatar_url

voxelbotutils.web.get_avatar_url(user_info: Optional[dict] = None)

Gets the avatar URL for a user when provided with their user info. If no arguments are provided then the default Discord avatar is given.

web.requires_login

voxelbotutils.web.requires_login()

Using this wrapper on a route means that the user needs to be logged in to see the page. If they’re not logged in then they’ll be redirected to the login URL as set in your website config.

web.is_logged_in

async voxelbotutils.web.is_logged_in(request: aiohttp.web_request.Request)

Returns whether or not the user for the given request is logged in.

web.get_discord_login_url

voxelbotutils.web.get_discord_login_url(request: aiohttp.web_request.Request, redirect_uri: Optional[str] = None) str

Returns a login URL for your website based on the oauth information given in your website config.

Parameters
  • request (Request) – The request from which this command call is coming from.

  • redirect_uri (str, optional) – Where the user should be redirected to after pressing authorize.

  • oauth_scopes (list, optional) – The scopes that the login URL will ask for. Does not necessarily mean we’ll get them.

Returns

The login URL that we want to use.

Return type

str

web.process_discord_login

async voxelbotutils.web.process_discord_login(request: aiohttp.web_request.Request) None

Process a Discord login and store the information in the provided session based off of a callback from your Discord redirect URI.

Parameters
  • request (Request) – The request from which this command call is coming from.

  • oauth_scopes (list) – The list of oauth scopes that we asked for.

web.get_user_info_from_session

async voxelbotutils.web.get_user_info_from_session(request: aiohttp.web_request.Request, *, refresh: bool = False)

Get the user’s info.

web.get_access_token_from_session

async voxelbotutils.web.get_access_token_from_session(request: aiohttp.web_request.Request, *, refresh_if_expired: bool = True, refresh: bool = False) str

Get the access token for a given user.

web.get_user_guilds_from_session

async voxelbotutils.web.get_user_guilds_from_session(request: aiohttp.web_request.Request, bot_key: str = 'bot') List[voxelbotutils.web.utils.oauth_models.OauthMember]

Returns a list of guilds that the user is in based on the request’s logged in user.

web.add_user_to_guild_from_session

async voxelbotutils.web.add_user_to_guild_from_session(request: aiohttp.web_request.Request, bot_index: str, guild_id: int) bool

Adds the user to the given guild (if the correct scopes were previously provided). Returns a boolean of whether or not that user was added (or was already in the guild) successfully.