Skip to content

run

Code execution cog for running code snippets in various programming languages.

This module provides functionality to execute code using external services like Godbolt and Wandbox, with support for multiple programming languages and proper error handling through custom exceptions.

Classes:

  • CodeDispatch

    Abstract base class for code execution services.

  • GodboltService

    Code execution service using Godbolt compiler explorer.

  • WandboxService

    Code execution service using Wandbox online compiler.

  • Run

    Cog for executing code in various programming languages.

Functions:

  • setup

    Set up the Run cog.

Classes

CodeDispatch

Python
CodeDispatch(compiler_map: dict[str, str])

Bases: ABC

Abstract base class for code execution services.

Initialize the code dispatch service.

Parameters:

  • compiler_map (dict[str, str]) –

    Mapping of language names to compiler identifiers.

Methods:

  • run

    Execute code using the appropriate compiler.

Functions

run async
Python
run(language: str, code: str, options: str | None = None) -> str | None

Execute code using the appropriate compiler.

Parameters:

  • language (str) –

    The programming language identifier.

  • code (str) –

    The source code to execute.

  • options (str | None, default: None ) –

    Additional compiler options. Defaults to None.

Returns:

  • str | None

    The execution output or None if execution failed.

_execute abstractmethod async
Python
_execute(compiler: str, code: str, options: str | None) -> str | None

Execute code with the specified compiler.

Parameters:

  • compiler (str) –

    The compiler identifier.

  • code (str) –

    The source code to execute.

  • options (str | None) –

    Additional compiler options.

Returns:

  • str | None

    The execution output or None if execution failed.

GodboltService

Python
GodboltService(compiler_map: dict[str, str])

Bases: CodeDispatch

Code execution service using Godbolt compiler explorer.

Initialize the code dispatch service.

Parameters:

  • compiler_map (dict[str, str]) –

    Mapping of language names to compiler identifiers.

Methods:

  • run

    Execute code using the appropriate compiler.

Functions

run async
Python
run(language: str, code: str, options: str | None = None) -> str | None

Execute code using the appropriate compiler.

Parameters:

  • language (str) –

    The programming language identifier.

  • code (str) –

    The source code to execute.

  • options (str | None, default: None ) –

    Additional compiler options. Defaults to None.

Returns:

  • str | None

    The execution output or None if execution failed.

_execute async
Python
_execute(compiler: str, code: str, options: str | None) -> str | None

Execute code using Godbolt service.

Parameters:

  • compiler (str) –

    The Godbolt compiler identifier.

  • code (str) –

    The source code to compile and execute.

  • options (str | None) –

    Additional compiler options. C++ options are automatically enhanced.

Returns:

  • str | None

    The execution output with header lines removed, or None if execution failed.

WandboxService

Python
WandboxService(compiler_map: dict[str, str])

Bases: CodeDispatch

Code execution service using Wandbox online compiler.

Initialize the code dispatch service.

Parameters:

  • compiler_map (dict[str, str]) –

    Mapping of language names to compiler identifiers.

Methods:

  • run

    Execute code using the appropriate compiler.

Functions

run async
Python
run(language: str, code: str, options: str | None = None) -> str | None

Execute code using the appropriate compiler.

Parameters:

  • language (str) –

    The programming language identifier.

  • code (str) –

    The source code to execute.

  • options (str | None, default: None ) –

    Additional compiler options. Defaults to None.

Returns:

  • str | None

    The execution output or None if execution failed.

_execute async
Python
_execute(compiler: str, code: str, options: str | None) -> str | None

Execute code using Wandbox service.

Parameters:

  • compiler (str) –

    The Wandbox compiler identifier.

  • code (str) –

    The source code to compile and execute.

  • options (str | None) –

    Additional compiler options.

Returns:

  • str | None

    Combined compiler errors and program output, or None if execution failed.

Notes

Nim compiler errors are filtered out due to excessive verbosity.

Run

Python
Run(bot: Tux)

Bases: BaseCog

Cog for executing code in various programming languages.

Supports multiple programming languages through Godbolt and Wandbox services. Provides code execution with proper error handling and user-friendly output.

Initialize the Run cog.

Parameters:

  • bot (Tux) –

    The bot instance to attach this cog to.

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.

  • run

    Execute code in various programming languages.

  • languages

    Display all supported programming languages to use with the run command.

Attributes:

Attributes

db property

Get the database coordinator for accessing database controllers.

Returns:

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

_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.

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.

__repr__
Python
__repr__() -> str

Return a string representation of the cog instance.

Returns:

  • str

    String representation in format <CogName bot=BotUser>.

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.

_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.

_parse_code_block
Python
_parse_code_block(text: str) -> tuple[str, str]

Parse a code block to extract language and code.

Parameters:

  • text (str) –

    The code block text.

Returns:

  • tuple[str, str]

    A tuple containing (language, code).

_determine_service
Python
_determine_service(language: str) -> str | None

Determine which service to use for a given language.

Parameters:

  • language (str) –

    The programming language identifier.

Returns:

  • str | None

    The service name ("wandbox" or "godbolt") or None if language is not supported.

_create_result_embed async
Python
_create_result_embed(
    ctx: Context[Tux], output: str, language: str, service: str
) -> Embed

Create a result embed for code execution output.

Parameters:

  • ctx (Context[Tux]) –

    The command context.

  • output (str) –

    The execution output.

  • language (str) –

    The programming language.

  • service (str) –

    The service used for execution.

Returns:

  • Embed

    The created embed.

_create_close_button_view
Python
_create_close_button_view() -> View

Create a view with a close button.

Returns:

  • View

    The view with close button.

_extract_code_from_message async
Python
_extract_code_from_message(ctx: Context[Tux], code: str | None) -> str | None

Extract code from the command or referenced message.

Parameters:

  • ctx (Context[Tux]) –

    The command context.

  • code (str | None) –

    Code provided directly in the command.

Returns:

  • str | None

    The extracted code or None if not found.

Notes

If no code is provided directly, attempts to extract code from a replied-to message containing triple backticks.

run async
Python
run(ctx: Context[Tux], *, code: str | None = None) -> None

Execute code in various programming languages.

Code should be enclosed in triple backticks with language specification. You can also reply to a message containing code to execute it.

Parameters:

  • ctx (Context[Tux]) –

    The command context.

  • code (str | None, default: None ) –

    The code to execute, or None to use referenced message. Defaults to None.

Raises:

languages async
Python
languages(ctx: Context[Tux]) -> None

Display all supported programming languages to use with the run command.

Parameters:

Functions

_remove_ansi

Python
_remove_ansi(text: str) -> str

Remove ANSI escape sequences from text.

Parameters:

  • text (str) –

    Text containing ANSI escape sequences.

Returns:

  • str

    Text with ANSI sequences removed.

_remove_backticks

Python
_remove_backticks(text: str) -> str

Remove backticks from text.

Parameters:

  • text (str) –

    Text containing backticks.

Returns:

  • str

    Text with backticks removed.

setup async

Python
setup(bot: Tux) -> None

Set up the Run cog.

Parameters:

  • bot (Tux) –

    The bot instance to add the cog to.