core ¶
Core module for Tux bot.
This module provides the core infrastructure including: - Base cog class for extensions - Database service for data persistence
Modules:
-
app–Tux application entrypoint and lifecycle management.
-
base_cog–Enhanced base cog with database access and automatic usage generation.
-
bot–Tux Discord bot core implementation.
-
checks–Dynamic Permission System - Fully Database-Driven.
-
cog_loader–Dynamic cog loading system with priority-based ordering and telemetry.
-
context–Command and Interaction Context Utilities.
-
converters–Discord.py command converters for Tux bot.
-
decorators–Dynamic Permission Decorators.
-
flags–Flag converters for Discord bot commands.
-
logging–Centralized Loguru Configuration for Tux Discord Bot.
-
permission_system–Dynamic permission system for guild-specific permission hierarchies.
-
prefix_manager–Prefix management with in-memory caching for optimal performance.
-
setup–Setup services for bot initialization.
-
task_monitor–Task monitoring and cleanup utilities for the Tux bot.
-
types–Type definitions for Tux core components.
Classes:
-
BaseCog–Enhanced base cog class providing database access and automatic usage generation.
-
DatabaseService–Async database service for PostgreSQL.
Classes¶
BaseCog ¶
BaseCog(bot: Tux)
Bases: Cog
Enhanced base cog class providing database access and automatic usage generation.
This class serves as the foundation for all bot cogs, offering convenient access to database controllers, configuration values, and automatic command usage string generation based on function signatures.
Attributes:
-
bot(Tux) –The bot instance this cog is attached to.
-
_unload_task(Task[None] | None) –Background task for graceful cog unloading when config is missing.
Notes
All cogs should inherit from this class to gain access to: - Database operations via self.db - Configuration access via self.get_config() - Automatic command usage generation - Graceful unloading on missing configuration
Initialize the base cog with bot instance and command usage setup.
Parameters:
-
bot(Tux) –The bot instance this cog will be attached to.
Notes
Automatically generates usage strings for all commands in this cog that don't have explicit usage strings defined.
-
afk ClassesAfk -
avatar ClassesAvatar -
bookmarks ClassesBookmarks -
clearafk ClassesClearAFK -
deepfry ClassesDeepfry -
dev ClassesDev -
encode_decode ClassesEncodeDecode -
eval ClassesEval -
event ClassesEventHandler -
fact ClassesFact -
flagremover ClassesFlagRemover -
gif_limiter ClassesGifLimiter -
git ClassesGit -
harmfulcommands ClassesHarmfulCommands -
influxdblogger ClassesInfluxLogger -
info ClassesInfo -
level ClassesLevel -
levels ClassesLevelsService -
levels ClassesLevels -
mail ClassesMail -
member_count ClassesMemberCount -
mock ClassesMock -
moderation ClassesModerationCogBase -
ping ClassesPing -
purge ClassesPurge -
random ClassesRandom -
remindme ClassesRemindMe -
report ClassesReport -
rolecount ClassesRoleCount -
run ClassesRun -
self_timeout ClassesSelfTimeout -
slowmode ClassesSlowmode -
snippets ClassesSnippetsBaseCog -
starboard ClassesStarboard -
status_roles ClassesStatusRoles -
supportnotifier ClassesSupportNotifier -
temp_vc ClassesTempVc -
timezones ClassesTimezones -
tldr ClassesTldr -
tty_roles ClassesTtyRoles -
wiki ClassesWiki -
wolfram ClassesWolfram -
xkcd ClassesXkcd
Methods:
-
get_config–Get a configuration value from CONFIG with support for nested keys.
-
__repr__–Return a string representation of the cog instance.
-
unload_if_missing_config–Check if required configuration is missing and log warning.
Attributes¶
db property ¶
db: DatabaseCoordinator
Get the database coordinator for accessing database controllers.
Returns:
-
DatabaseCoordinator–Coordinator providing access to all database controllers.
Examples:
>>> 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¶
_setup_command_usage ¶
_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 ¶
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.
get_config ¶
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:
>>> 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.
__repr__ ¶
__repr__() -> str
Return a string representation of the cog instance.
Returns:
-
str–String representation in format
<CogName bot=BotUser>.
unload_if_missing_config ¶
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:
>>> 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.
_unload_self async ¶
_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.
DatabaseService ¶
DatabaseService(echo: bool = False)
Async database service for PostgreSQL.
Provides connection management, session handling, query execution with retry logic, and health checks for the PostgreSQL database.
Attributes:
-
_engine(AsyncEngine | None) –SQLAlchemy async engine for database connections.
-
_session_factory(async_sessionmaker[AsyncSession] | None) –Factory for creating database sessions.
-
_echo(bool) –Whether to log SQL queries (useful for debugging).
Initialize the database service.
Parameters:
-
echo(bool, default:False) –Whether to enable SQL query logging (default is False).
-
afk ClassesAfkController Attributesdb_service -
base ClassesBaseController Attributesdb_service -
base_controller ClassesBaseController Attributesdb_service -
case ClassesCaseController Attributesdb_service -
controllers Classes-
AfkController Attributesdb_service -
BaseController Attributesdb_service -
CaseController Attributesdb_service -
GuildConfigController Attributesdb_service -
GuildController Attributesdb_service -
LevelsController Attributesdb_service -
PermissionAssignmentController Attributesdb_service -
PermissionCommandController Attributesdb_service -
PermissionRankController Attributesdb_service -
ReminderController Attributesdb_service -
SnippetController Attributesdb_service -
StarboardController Attributesdb_service -
StarboardMessageController Attributesdb_service
-
-
guild ClassesGuildController Attributesdb_service -
guild_config ClassesGuildConfigController Attributesdb_service -
levels ClassesLevelsController Attributesdb_service -
permissions Classes -
reminder ClassesReminderController Attributesdb_service -
snippet ClassesSnippetController Attributesdb_service -
starboard Classes -
utils Functionsget_db_service_from
-
afk ClassesAfkController -
base ClassesBaseController -
base_controller ClassesBaseController -
bulk ClassesBulkOperationsController -
case ClassesCaseController -
controllers Classes -
crud ClassesCrudController -
database_setup ClassesDatabaseSetupService -
guild ClassesGuildController -
guild_config ClassesGuildConfigController -
levels ClassesLevelsController -
pagination ClassesPaginationController -
performance ClassesPerformanceController -
permission_setup ClassesPermissionSetupService -
permissions Classes -
query ClassesQueryController -
reminder ClassesReminderController -
snippet ClassesSnippetController -
starboard Classes -
transaction ClassesTransactionController -
upsert ClassesUpsertController
Methods:
-
connect–Connect to the PostgreSQL database.
-
disconnect–Disconnect from the database and dispose of the connection pool.
-
is_connected–Check if database is currently connected.
-
test_connection–Test database connectivity with a simple query.
-
session–Get a database session context manager.
-
execute_transaction–Execute a callback inside a database transaction.
-
execute_query–Execute database operation with automatic retry logic.
-
health_check–Perform database health check.
-
validate_schema–Validate that the database schema matches the current model definitions.
Attributes¶
engine property ¶
engine: AsyncEngine | None
Get the database engine.
Returns:
-
AsyncEngine | None–The SQLAlchemy async engine, or None if not connected.
Notes
Primarily used for testing and advanced operations.
Functions¶
connect async ¶
disconnect async ¶
disconnect() -> None
Disconnect from the database and dispose of the connection pool.
test_connection async ¶
test_connection() -> None
Test database connectivity with a simple query.
Raises:
-
Exception–If the database connection fails or the test query fails.
session async ¶
session() -> AsyncGenerator[AsyncSession]
Get a database session context manager.
Automatically handles connection, commit, and rollback.
Yields:
-
AsyncSession–An active database session.
Examples:
>>> async with db.session() as session:
... result = await session.execute(select(User))
... users = result.scalars().all()
execute_transaction async ¶
execute_query async ¶
execute_query(operation: Callable[[AsyncSession], Awaitable[T]], span_desc: str) -> T
Execute database operation with automatic retry logic.
Parameters:
-
operation(Callable[[AsyncSession], Awaitable[T]]) –Async function that performs database operations.
-
span_desc(str) –Description for Sentry performance monitoring.
Returns:
-
T–Result of the operation.
Notes
Retries the operation automatically on transient failures.
_execute_with_retry async ¶
_execute_with_retry(
operation: Callable[[AsyncSession], Awaitable[T]],
span_desc: str,
max_retries: int = 3,
backoff_factor: float = 0.5,
) -> T
Execute database operation with exponential backoff retry logic.
Parameters:
-
operation(Callable[[AsyncSession], Awaitable[T]]) –Database operation to execute.
-
span_desc(str) –Description for monitoring/logging.
-
max_retries(int, default:3) –Maximum number of retry attempts (default is 3).
-
backoff_factor(float, default:0.5) –Multiplier for exponential backoff (default is 0.5).
Returns:
-
T–Result of the operation.
Raises:
-
TimeoutError–If the operation times out after all retries.
-
DisconnectionError–If database disconnection occurs after all retries.
-
OperationalError–If database operational error occurs after all retries.
-
RuntimeError–If the retry loop completes unexpectedly without return or exception.
health_check async ¶
Perform database health check.
Returns:
-
dict[str, Any]–Health check result with status and optional error message. Status can be: "healthy", "unhealthy", or "disconnected".
Examples:
>>> result = await db.health_check()
>>> print(result)
{'status': 'healthy', 'mode': 'async'}
validate_schema async ¶
Validate that the database schema matches the current model definitions.
Uses SQLAlchemy's metadata reflection to compare the actual database schema with the defined model metadata. Much more efficient and accurate than manual queries.
Returns:
-
dict[str, Any]–Schema validation result with status and optional error message. Status can be: "valid", "invalid", or "error".
Examples:
>>> result = await db.validate_schema()
>>> print(result)
{'status': 'valid', 'mode': 'async'}