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 anddiscord.Message
’s edit methods have been altered to have thecomponents
andephemeral
arguments.components
refers to an instance ofvoxelbotutils.MessageComponents
, andephemeral
refers to whether or not the sent message should be ephemeral (which only works with interactions responses - slash commands and components).discord.ext.commands.bot_has_permissions
has been superseded byvoxelbotutils.bot_has_permissions
as a drop-in replacement because the first is incompatible with slash commands.discord.ext.commands.bot_has_guild_permissions
has been superseded byvoxelbotutils.bot_has_guild_permissions
as a drop-in replacement because the first is incompatible with slash commands.
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.
- Returns
The bot’s application ID.
- Return type
- 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
- 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 (voxelbotutils.ApplicationCommand) – The command that you want to add.
- Returns
The updated command instance using the returned API data.
- Return type
- 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 (voxelbotutils.ApplicationCommand) – The command you want to add.
- Returns
The updated command instance using the returned API data.
- Return type
- 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[voxelbotutils.ApplicationCommand]) – The list of commands you want to add.
- Returns
- The updated command instances
using the returned API data.
- Return type
- 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[voxelbotutils.ApplicationCommand]) – The list of commands you want to add.
- Returns
- The updated command instances
using the returned API data.
- Return type
- 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
- Returns
- The command instances
that were previously added for the application.
- Return type
- 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
- The command instances
that were previously added for the application.
- Return type
- async delete_global_application_command(command: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommand) None ¶
Remove a global slash command for the bot.
- Parameters
command (voxelbotutils.ApplicationCommand) – The command that you want to remove. A command ID is required for this to work.
- 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. A command ID is required for this to work.
- 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
- 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.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
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(*, base: Optional[str] = None, 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, enabled: Optional[bool] = None) str ¶
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
- 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.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[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
- 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 = <voxelbotutils.cogs.utils.custom_bot._EmptyProxy object>, file: discord.file.File = <voxelbotutils.cogs.utils.custom_bot._EmptyProxy object>, 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.
Cog¶
- class voxelbotutils.Cog(*args, **kwargs)¶
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" class FuckMee6Owo(voxelbotutils.Cog): pass c = FuckMee6Owo(bot) c.qualified_name # "Fuck Mee6 Owo"
- 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, **kwargs)¶
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.
- 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 (discord.ext.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]
- 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 (discord.ext.commands.Context) – The command we want to chek if can be run.
- Returns
Whether or not the command can be run.
- Return type
- 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.
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 implementingContext.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
- 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') 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, 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 (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]
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.
TimeFormatter¶
- class voxelbotutils.TimeFormatter(time: datetime.datetime)¶
A Python datetime formatter.
- __init__(time: datetime.datetime)¶
- Parameters
time (datetime.datetime) – The time that you want to format.
ComponentMessage¶
- class voxelbotutils.ComponentMessage(*, state, channel, data)¶
A subclass of
discord.Message
that has ancomponents
attribute.
- class voxelbotutils.ComponentWebhookMessage(*, state, channel, data)¶
A subclass of
discord.WebhookMessage
that has ancomponents
attribute.
bot_has_permissions¶
- voxelbotutils.bot_has_permissions(*args, **kwargs)¶
- voxelbotutils.bot_has_guild_permissions(*args, **kwargs)¶
defer_response¶
- voxelbotutils.defer_response(ephemeral: bool = False)¶
A “check” that defers the response when called. As checks are run before converters, this will defer the response immediately. Useful if your converters run database calls.
- Parameters
ephemeral (bool, optional) – Whether or not the defer response should be ephemeral.
Slash Commands¶
Slash commands also have their own page for a basic integration guide.
ApplicationCommand¶
- class voxelbotutils.ApplicationCommand(name: str, description: Optional[str] = None, type: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandType = ApplicationCommandType.CHAT_INPUT)¶
An instance of an application command.
- options¶
A list of the options added to this command.
- __init__(name: str, description: Optional[str] = None, type: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandType = ApplicationCommandType.CHAT_INPUT)¶
- add_option(option: voxelbotutils.cogs.utils.interactions.application_commands.ApplicationCommandOption)¶
Add an option to this command instance.
ApplicationCommandType¶
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.
- type¶
The type of this command option.
- default¶
The default value given to the command option.
- Type
typing.Any
- choices¶
A list of choices that this command can take.
- options¶
A list of options that go into the application command.
- __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¶
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.
- MENTIONABLE = 9¶
Any mentionable user or role.
- NUMBER = 10¶
Any double.
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]
- values¶
A list of values that were passed through from the component.
- Type
typing.Optional(typing.List[str])
- 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 thewait=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(**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 thewait=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.
ComponentHolder¶
- class voxelbotutils.ComponentHolder(*components: 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: voxelbotutils.cogs.utils.interactions.components.models.BaseComponent)¶
- Parameters
*components (voxelbotutils.BaseComponent) – 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 (voxelbotutils.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 (voxelbotutils.BaseComponent) – The component that you want to remove.
- disable_components() None ¶
Disables all of the components inside this component holder that inherit from
voxelbotutils.DisableableComponent
.
- enable_components() None ¶
Enables all of the components inside this component holder that inherit from
voxelbotutils.DisableableComponent
.
- get_component(custom_id: str) Optional[voxelbotutils.cogs.utils.interactions.components.models.BaseComponent] ¶
Get a component from the internal
components
list using itscustom_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[voxelbotutils.BaseComponent]
MessageComponents¶
- class voxelbotutils.MessageComponents(*components: 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”.
- 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 (voxelbotutils.Button) – The buttons that you want to have added.
ActionRow¶
- class voxelbotutils.ActionRow(*components: 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¶
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 (voxelbotutils.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.
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.
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.
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
- Returns
The decorator that should be applied to the command.
- Return type
typing.Callable
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 apredicate()
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
- 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.
- 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.'''
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 theis_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 viadiscord.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 ofdiscord.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.
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.