API Reference¶
Utils¶
Bot¶
- class voxelbotutils.MinimalBot(command_prefix, help_command=<default-help-command>, description=None, **options)¶
A minimal version of the VoxelBotUtils bot that inherits from
discord.ext.commands.AutoShardedBot
but gives new VBU features.- 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
- class voxelbotutils.Bot(config_file: str = 'config/config.toml', logger: Optional[logging.Logger] = None, activity: discord.activity.BaseActivity = <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
- session¶
A session instance that you can use to make web requests.
- database¶
The database connector, as connected using the data from your
config file
.- Type
- redis¶
The redis connector, as connected using the data from your
config file
.- Type
- stats¶
The stats connector, as connected using the data from your
config file
. May not be authenticated, but will fail silently if not.- Type
- startup_method¶
The task that’s run when the bot is starting up.
- Type
- 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
- upgrade_chat¶
An UpgradeChat connector instance using the oauth information provided in your
config file
.
- owner_ids¶
A list of the owners from the
config file
.- Type
- embeddify¶
Whether or not messages should be embedded by default, as set in the
config file
.- Type
- __init__(config_file: str = 'config/config.toml', logger: Optional[logging.Logger] = None, activity: discord.activity.BaseActivity = <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
config_file (str, optional) – The path to the
config file
for the bot.logger (logging.Logger, optional) – The logger object that the bot should use.
activity (discord.Activity, optional) – The default activity of the bot.
status (discord.Status, optional) – The default status of the bot.
case_insensitive (bool, optional) – Whether or not commands are case insensitive.
intents (discord.Intents, optional) – The default intents for the bot. Unless subclassed, the intents to use will be read from your
config file
.allowed_mentions (discord.AllowedMentions, optional) – The default allowed mentions for the bot.
*args – The default args that are sent to the
discord.ext.commands.Bot
object.**kwargs – The default args that are sent to the
discord.ext.commands.Bot
object.
- async startup()¶
Clears the custom caches for the bot (
guild_settings
anduser_settings
), re-reads the database tables for each of those items, and calls thevoxelbotutils.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]
- get_invite_link(*, client_id: Optional[int] = None, scope: Optional[str] = None, response_type: Optional[str] = None, redirect_uri: Optional[str] = None, guild_id: Optional[int] = None, permissions: Optional[discord.permissions.Permissions] = None, **kwargs) str ¶
Generate an invite link for the bot.
- Parameters
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
- 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.
- get_event_webhook(event_name: str) Optional[discord.webhook.async_.Webhook] ¶
Get a
discord.Webhook
object based on the keys in thebot'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[Tuple[Union[discord.user.User, discord.member.Member]]] = None, *, delete: Optional[Tuple[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
- 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.
- get_context_message(messageable, content: str, *, embed: discord.embeds.Embed = ..., embeddify: Optional[bool] = None) 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.
Cog¶
- class voxelbotutils.Cog(*args: Any, **kwargs: Any)¶
A slightly modified cog class to allow for the
cache_setup
method and for the class’logger
instance.- 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
- 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"
- Type
- 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
orvoxelbotutils.Bot.user_settings
tables. This setup should clear your caches before setting them, as thevoxelbotutils.Bot.startup()
method may be called multiple times.
Command¶
- class voxelbotutils.Command(*args: Any, **kwargs: Any)¶
A custom command class subclassing
discord.ext.commands.Command
so that we can add some more attirbutes to it. Unlike normal Discord.py, thecooldown_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.
- argument_descriptions¶
A list of descriptions for the command arguments to be used in slash commands.
- Type
- argparse¶
A list of args and kwargs to be expanded into argparse.
For instance, if you had a ban command and wanted to specify a ban time with a
-days
flag, you could set that up like so:@voxelbotutils.command(argparse=( ("-days", "-d", {"type": int, "default": 0, "nargs": "?"}), )) async def ban(self, ctx, user: discord.Member, *, namespace: argparse.Namespace): ban_time: int = namespace.days # Conversion is handled automatically ...
- Type
typing.Tuple[str, …, typing.Dict[str, typing.Any]]
- context_command_type¶
The type of context command that your given command should be added as.
- Type
voxelbotutils.ApplicationCommandType
- class voxelbotutils.Group(*args: Any, **kwargs: Any)¶
- group(*args, **kwargs)¶
Add the usual
voxelbotutils.Group
to the mix.
Context¶
- class voxelbotutils.Context(*args, **kwargs)¶
A modified version of the default
discord.ext.commands.Context
.- 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
- get_mentionable_channel(channel_id: int, fallback: str = 'null') voxelbotutils.cogs.utils.custom_context.AbstractMentionable ¶
Get the mention string for a given channel ID.
- Parameters
- Returns
The mentionable channel.
- Return type
typing.Union[discord.TextChannel, voxelbotutils.AbstractMentionable]
- get_mentionable_role(role_id: int, fallback: str = 'null') voxelbotutils.cogs.utils.custom_context.AbstractMentionable ¶
Get the mention string for a given role ID.
- Parameters
- Returns
The mentionable role.
- Return type
typing.Union[discord.Role, voxelbotutils.AbstractMentionable]
AbstractMentionable¶
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 theconn
attribute), and can be easily accessed via theBot.database
attribute.Examples
# The database can be used via context async with DatabaseConnection() 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 DatabaseConnection.get_connection() await db("DELETE FROM user_settings") await db.disconnect() # And transactions are also available async with DatabaseConnection() 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
- 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
RedisConnection¶
- class voxelbotutils.RedisConnection(connection: Optional[aioredis.connection.RedisConnection] = None)¶
A wrapper for an
aioredis.Redis
object, provided in your bot object atBot.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 RedisConnection() 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.
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
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
Sets the footer of the embed.
- set_image(url: str) voxelbotutils.cogs.utils.context_embed.Embed ¶
Sets the image of the embed.
- set_thumbnail(url: str) voxelbotutils.cogs.utils.context_embed.Embed ¶
Sets the thumbnail of the 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
- add_field(name: str, value: str, inline: bool = True) voxelbotutils.cogs.utils.context_embed.Embed ¶
Adds a field to the embed without using kwargs.
- 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.
- 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
- Returns
The embed instance.
- Return type
- 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
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)¶
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)¶
- 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 (discord.ext.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]
- static default_list_formatter(m: voxelbotutils.cogs.utils.paginator.Paginator, d: List[Union[str, discord.embeds.Embed]])¶
The default list formatter for embeds. Takes the paginator instance and the list of data to be displayed, and returns a dictionary of kwargs for a Message.edit.
- static default_ranked_list_formatter(m: voxelbotutils.cogs.utils.paginator.Paginator, d: List[str])¶
The default list formatter for embeds. Takes the paginator instance and the list of strings to be displayed, and returns a dictionary of kwargs for a Message.edit.
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).
- delta¶
A timedelta for the entire timevalue object.
- Type
- __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.
- 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 (discord.ext.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
- Raises
voxelbotutils.errors.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
- Raises
voxelbotutils.errors.InvalidTimeDuration – If the time could not be successfully converted.
component_check¶
- voxelbotutils.component_check(user: Union[discord.user.User, discord.member.Member], message: discord.message.Message, no_interact_message: Optional[str] = ...) Callable[[discord.interactions.Interaction], bool] ¶
A check for a wait_for that allows only a user to interact with the given button, outputting the no interaction message.
New in version 0.6.6.
- Parameters
user (Union[discord.User, discord.Member]) – The user who’s allowed to interact with the message.
message (discord.Message) – The message that the user is allowed to interact with.
no_interact_message (Optional[str]) –
The content that’s output when a non-valid user interacts with the button.
Changed in version 0.7.0.
You can now disable a response being sent by passing
None
to this parameter. If you do, a deferred update will still be sent.
- Returns
A callable check for interaction events where only the supplied user is allowed to interact.
- Return type
Callable[[discord.Interaction], bool]
format¶
- voxelbotutils.format(*args, **kwargs)¶
A modified version of the normal
str.format
method to have some slightly more useful utilities in it.Examples
# Saying how many of a given item you have can be a pain. # Using the plural formatter, you can easily format a string to have # plural nouns. vbu.format("{0:plural,single,plural}", 1) # "single" vbu.format("{0:plural,single,plural}", 2) # "plural" vbu.format("{0} {0:plural,item,items}", 1) # "1 item" vbu.format("{0} {0:plural,item,items}", 2) # "2 items" # You have a command `inventory` - runnable as `inventory @user` defaulting the user # to yourself. # Pronouns for this can be a pain to update in strings. In this example, we set the # pronouns by comparing the specified user to `ctx.author` vbu.format("{0:pronoun,You,{1.mention}} {0:pronoun,have,has} stuff.", ctx.author == user, user.mention) # The join formatter can "human" join a list strings. items = ["a", "b", "c", "d"] vbu.format("{0:humanjoin}", items) # "a, b, c, and d"
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 setdiscord.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 raisevoxelbotutils.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.
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(*args, **kwargs)¶
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: Optional[str] = None, *args: Any)¶
This is a subclass of
discord.ext.commands.DisabledCommand
raised exclusively by theis_config_set
check. For normal users, this should just say that the command is disabled.
errors.InvokedMetaCommand¶
- exception voxelbotutils.errors.InvokedMetaCommand(message: Optional[str] = None, *args: Any)¶
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 viadiscord.ext.commands.Bot.invoke()
.
errors.BotNotReady¶
- exception voxelbotutils.errors.BotNotReady(message: Optional[str] = None, *args: Any)¶
The generic error for the bot failing the
voxelbotutils.checks.bot_is_ready()
check.
errors.IsNotVoter¶
- exception voxelbotutils.errors.IsNotVoter(message: Optional[str] = None, *args: Any)¶
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 ofdiscord.ext.commands.MissingRole
.
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.
errors.InvalidTimeDuration¶
errors.IsNotUpgradeChatPurchaser¶
Websites¶
web.OauthGuild¶
- class voxelbotutils.web.OauthGuild(bot, guild_data, user)¶
A guild object from an oauth integration.
- icon_url¶
The guild’s icon.
- Type
- owner_id¶
The ID of the owner for the guild. This will either be the ID of the authenticated user or 0.
- Type
- features¶
A list of features that the guild has.sa
- Type
- 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¶
web.OauthMember¶
- class voxelbotutils.web.OauthMember(bot, guild_data, user_data)¶
A user object from an oauth integration.
- avatar_url¶
The user’s avatar.
- Type
- public_flags¶
The user’s public flags.
- guild¶
The guild object that this member is a part of.
- Type
- guild_permissions¶
The permissions that this member has on the guild.
- Type
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.
web.get_avatar_url¶
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
.See also
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.
See also
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
- Returns
The login URL that we want to use.
- Return type
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¶
web.get_access_token_from_session¶
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.