Skip to content

levels

Leveling and XP tracking service for Discord guilds.

This module provides comprehensive XP and leveling functionality, including automatic XP gain from messages, role assignments based on levels, and various utility functions for level calculations and progress tracking.

Classes:

  • LevelsService

    Service for managing user levels and XP in Discord guilds.

Functions:

  • setup

    Set up the LevelsService cog.

Classes

LevelsService

Python
LevelsService(bot: Tux)

Bases: BaseCog

Service for managing user levels and XP in Discord guilds.

Initialize the levels service.

Parameters:

  • bot (Tux) –

    The bot instance to attach this service to.

Methods:

Attributes:

Attributes

db property

Get the database coordinator for accessing database controllers.

Returns:

  • DatabaseCoordinator

    Coordinator providing access to all database controllers.

Examples:

Python Console Session
>>> await self.db.guild_config.get_guild_config(guild_id)
>>> await self.db.cases.create_case(...)
Notes

This property provides convenient access to database operations without needing to access self.bot.db directly.

Functions

xp_listener async
Python
xp_listener(message: Message) -> None

Listen for messages to process XP gain.

Parameters:

  • message (Message) –

    The message object.

process_xp_gain async
Python
process_xp_gain(member: Member, guild: Guild) -> None

Process XP gain for a member.

Parameters:

  • member (Member) –

    The member gaining XP.

  • guild (Guild) –

    The guild where the member is gaining XP.

_setup_command_usage
Python
_setup_command_usage() -> None

Generate usage strings for all commands in this cog that lack explicit usage.

The generated usage follows the pattern: <qualified_name> <param tokens>

Where: - Required parameters are denoted as <name: Type> - Optional parameters are denoted as [name: Type] - The prefix is intentionally omitted (provided by ctx.prefix)

Examples:

ban <member: Member> [reason: str] config set <key: str> <value: str>

Notes

Respects explicit usage strings if already set on a command. Errors during generation are logged but don't prevent cog loading.

_generate_usage
Python
_generate_usage(command: Command[Any, ..., Any]) -> str

Generate a usage string with support for flags and positional parameters.

This method inspects the command's callback signature to detect: - FlagConverter parameters (e.g., --flag value) - Positional parameters (e.g., <required> or [optional])

Parameters:

  • command (Command) –

    The command to generate usage for.

Returns:

  • str

    Generated usage string, or qualified command name as fallback.

Notes

Delegates to shared usage generator for consistency across all cogs. Falls back gracefully to command name if generation fails.

is_on_cooldown
Python
is_on_cooldown(last_message_time: datetime) -> bool

Check if the member is on cooldown.

Parameters:

  • last_message_time (datetime) –

    The time of the last message.

Returns:

  • bool

    True if the member is on cooldown, False otherwise.

handle_level_up async
Python
handle_level_up(member: Member, guild: Guild, new_level: int) -> None

Handle the level up process for a member.

Parameters:

  • member (Member) –

    The member leveling up.

  • guild (Guild) –

    The guild where the member is leveling up.

  • new_level (int) –

    The new level of the member.

update_roles async
Python
update_roles(member: Member, guild: Guild, new_level: int) -> None

Update the roles of a member based on their new level.

Parameters:

  • member (Member) –

    The member whose roles are being updated.

  • guild (Guild) –

    The guild where the member's roles are being updated.

  • new_level (int) –

    The new level of the member.

try_assign_role async staticmethod
Python
try_assign_role(member: Member, role: Role) -> None

Try to assign a role to a member.

Parameters:

  • member (Member) –

    The member to assign the role to.

  • role (Role) –

    The role to assign.

get_config
Python
get_config(key: str, default: Any = None) -> Any

Get a configuration value from CONFIG with support for nested keys.

Parameters:

  • key (str) –

    The configuration key to retrieve. Supports dot notation for nested values (e.g., "BOT_INFO.BOT_NAME").

  • default (Any, default: None ) –

    Default value to return if key is not found, by default None.

Returns:

  • Any

    The configuration value or default if not found.

Examples:

Python Console Session
>>> self.get_config("BOT_INFO.BOT_NAME")
'Tux'
>>> self.get_config("MISSING_KEY", "fallback")
'fallback'
Notes

Errors during retrieval are logged but don't raise exceptions. Returns the default value on any error.

calculate_xp_for_level
Python
calculate_xp_for_level(level: int) -> float

Calculate the XP required for a given level.

Parameters:

  • level (int) –

    The level to calculate XP for.

Returns:

  • float

    The XP required for the level.

calculate_xp_increment
Python
calculate_xp_increment(member: Member) -> float

Calculate the XP increment for a member.

Parameters:

  • member (Member) –

    The member gaining XP.

Returns:

  • float

    The XP increment.

calculate_level
Python
calculate_level(xp: float) -> int

Calculate a level based on XP.

Parameters:

  • xp (float) –

    The XP amount.

Returns:

  • int

    The calculated level.

__repr__
Python
__repr__() -> str

Return a string representation of the cog instance.

Returns:

  • str

    String representation in format <CogName bot=BotUser>.

valid_xplevel_input
Python
valid_xplevel_input(user_input: int) -> Embed | None

Check if the input is valid.

Parameters:

  • user_input (int) –

    The input to check.

Returns:

  • Embed | None

    A string if the input is valid, or a discord. Embed if there is an error.

unload_if_missing_config
Python
unload_if_missing_config(condition: bool, config_name: str) -> bool

Check if required configuration is missing and log warning.

This allows cogs to detect missing configuration at load time and return early from init to prevent partial initialization.

Parameters:

  • condition (bool) –

    True if config is missing (should unload), False otherwise.

  • config_name (str) –

    Name of the missing configuration for logging purposes.

Returns:

  • bool

    True if config is missing (caller should return early), False if config is present.

Examples:

Python Console Session
>>> def __init__(self, bot: Tux):
...     super().__init__(bot)
...     if self.unload_if_missing_config(not CONFIG.GITHUB_TOKEN, "GITHUB_TOKEN"):
...         return  # Exit early, cog will be partially loaded but won't register commands
...     self.github_client = GitHubClient()
Notes

When this returns True, the cog's init should return early to avoid initializing services that depend on the missing config. The cog will be loaded but commands won't be registered properly, preventing runtime errors.

For complete cog unloading, the bot owner should remove the cog from the modules directory or use the reload system to unload it programmatically.

generate_progress_bar staticmethod
Python
generate_progress_bar(
    current_value: int, target_value: int, bar_length: int = 10
) -> str

Generate an XP progress bar based on the current level and XP.

Parameters:

  • current_value (int) –

    The current XP value.

  • target_value (int) –

    The target XP value.

  • bar_length (int, default: 10 ) –

    The length of the progress bar. Defaults to 10.

Returns:

  • str

    The formatted progress bar.

_unload_self async
Python
_unload_self(extension_name: str) -> None

Perform the actual cog unload operation.

Parameters:

  • extension_name (str) –

    Full extension name to unload.

Notes

This is called as a background task by unload_if_missing_config(). Errors during unload are logged but don't raise exceptions.

get_level_progress
Python
get_level_progress(xp: float, level: int) -> tuple[int, int]

Get the progress towards the next level.

Parameters:

  • xp (float) –

    The current XP.

  • level (int) –

    The current level.

Returns:

  • tuple[int, int]

    A tuple containing the XP progress within the current level and the XP required for the next level.

Functions

setup async

Python
setup(bot: Tux) -> None

Set up the LevelsService cog.

Parameters:

  • bot (Tux) –

    The bot instance to add the cog to.