Skip to content

tux.cogs.utility.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:

Name Description
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.

Classes

CodeDispatch(compiler_map: dict[str, str])

Bases: ABC

Abstract base class for code execution services.

Initialize the code dispatch service.

Parameters:

Name Type Description Default
compiler_map dict[str, str]

Mapping of language names to compiler identifiers.

required

Methods:

Name Description
run

Execute code using the appropriate compiler.

Source code in tux/cogs/utility/run.py
Python
def __init__(self, compiler_map: dict[str, str]) -> None:
    """
    Initialize the code dispatch service.

    Parameters
    ----------
    compiler_map : dict[str, str]
        Mapping of language names to compiler identifiers.
    """
    self.compiler_map = compiler_map

Functions

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

Execute code using the appropriate compiler.

Parameters:

Name Type Description Default
language str

The programming language identifier.

required
code str

The source code to execute.

required
options str | None

Additional compiler options. Defaults to None.

None

Returns:

Type Description
str | None

The execution output or None if execution failed.

Source code in tux/cogs/utility/run.py
Python
async def run(self, 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, optional
        Additional compiler options. Defaults to None.

    Returns
    -------
    str | None
        The execution output or None if execution failed.
    """
    compiler = self.compiler_map.get(language)
    if compiler is None:
        return None
    return await self._execute(compiler, code, options)
_execute(compiler: str, code: str, options: str | None) -> str | None abstractmethod async

Execute code with the specified compiler.

Parameters:

Name Type Description Default
compiler str

The compiler identifier.

required
code str

The source code to execute.

required
options str | None

Additional compiler options.

required

Returns:

Type Description
str | None

The execution output or None if execution failed.

Source code in tux/cogs/utility/run.py
Python
@abstractmethod
async def _execute(self, 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(compiler_map: dict[str, str])

Bases: CodeDispatch

Code execution service using Godbolt compiler explorer.

Initialize the code dispatch service.

Parameters:

Name Type Description Default
compiler_map dict[str, str]

Mapping of language names to compiler identifiers.

required

Methods:

Name Description
run

Execute code using the appropriate compiler.

Source code in tux/cogs/utility/run.py
Python
def __init__(self, compiler_map: dict[str, str]) -> None:
    """
    Initialize the code dispatch service.

    Parameters
    ----------
    compiler_map : dict[str, str]
        Mapping of language names to compiler identifiers.
    """
    self.compiler_map = compiler_map

Functions

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

Execute code using the appropriate compiler.

Parameters:

Name Type Description Default
language str

The programming language identifier.

required
code str

The source code to execute.

required
options str | None

Additional compiler options. Defaults to None.

None

Returns:

Type Description
str | None

The execution output or None if execution failed.

Source code in tux/cogs/utility/run.py
Python
async def run(self, 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, optional
        Additional compiler options. Defaults to None.

    Returns
    -------
    str | None
        The execution output or None if execution failed.
    """
    compiler = self.compiler_map.get(language)
    if compiler is None:
        return None
    return await self._execute(compiler, code, options)
_execute(compiler: str, code: str, options: str | None) -> str | None async

Execute code using Godbolt service.

Parameters:

Name Type Description Default
compiler str

The Godbolt compiler identifier.

required
code str

The source code to compile and execute.

required
options str | None

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

required

Returns:

Type Description
str | None

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

Source code in tux/cogs/utility/run.py
Python
async def _execute(self, 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.
    """
    output = godbolt.getoutput(code, compiler, options)
    if not output:
        return None

    # Remove header lines (first 5 lines)
    lines = output.split("\n")
    return "\n".join(lines[5:])

WandboxService(compiler_map: dict[str, str])

Bases: CodeDispatch

Code execution service using Wandbox online compiler.

Initialize the code dispatch service.

Parameters:

Name Type Description Default
compiler_map dict[str, str]

Mapping of language names to compiler identifiers.

required

Methods:

Name Description
run

Execute code using the appropriate compiler.

Source code in tux/cogs/utility/run.py
Python
def __init__(self, compiler_map: dict[str, str]) -> None:
    """
    Initialize the code dispatch service.

    Parameters
    ----------
    compiler_map : dict[str, str]
        Mapping of language names to compiler identifiers.
    """
    self.compiler_map = compiler_map

Functions

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

Execute code using the appropriate compiler.

Parameters:

Name Type Description Default
language str

The programming language identifier.

required
code str

The source code to execute.

required
options str | None

Additional compiler options. Defaults to None.

None

Returns:

Type Description
str | None

The execution output or None if execution failed.

Source code in tux/cogs/utility/run.py
Python
async def run(self, 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, optional
        Additional compiler options. Defaults to None.

    Returns
    -------
    str | None
        The execution output or None if execution failed.
    """
    compiler = self.compiler_map.get(language)
    if compiler is None:
        return None
    return await self._execute(compiler, code, options)
_execute(compiler: str, code: str, options: str | None) -> str | None async

Execute code using Wandbox service.

Parameters:

Name Type Description Default
compiler str

The Wandbox compiler identifier.

required
code str

The source code to compile and execute.

required
options str | None

Additional compiler options.

required

Returns:

Type Description
str | None

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

Notes

Nim compiler errors are filtered out due to excessive verbosity.

Source code in tux/cogs/utility/run.py
Python
async def _execute(self, 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.
    """
    result = wandbox.getoutput(code, compiler, options)
    if not result:
        return None

    output_parts: list[str] = []

    # Handle compiler errors (skip for Nim due to verbose debug messages)
    if (compiler_error := result.get("compiler_error")) and compiler != self.compiler_map.get("nim"):
        output_parts.append(str(compiler_error))

    # Handle program output
    if program_output := result.get("program_output"):
        output_parts.append(str(program_output))

    return " ".join(output_parts).strip() if output_parts else None

Run(bot: Tux)

Bases: Cog

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.

Methods:

Name Description
run

Execute code in various programming languages.

languages

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

Source code in tux/cogs/utility/run.py
Python
def __init__(self, bot: Tux) -> None:
    self.bot = bot
    self.run.usage = generate_usage(self.run)
    self.languages.usage = generate_usage(self.languages)
    self.services = {
        "godbolt": GodboltService(GODBOLT_COMPILERS),
        "wandbox": WandboxService(WANDBOX_COMPILERS),
    }

Functions

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

Parse a code block to extract language and code.

Parameters:

Name Type Description Default
text str

The code block text.

required

Returns:

Type Description
tuple[str, str]

A tuple containing (language, code).

Source code in tux/cogs/utility/run.py
Python
def _parse_code_block(self, 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).
    """
    cleaned_text = _remove_backticks(text)
    lines = cleaned_text.split("\n")
    language = lines[0] if lines else ""
    code = "\n".join(lines[1:]) if len(lines) > 1 else ""
    return language, code
_determine_service(language: str) -> str | None

Determine which service to use for a given language.

Parameters:

Name Type Description Default
language str

The programming language identifier.

required

Returns:

Type Description
str | None

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

Source code in tux/cogs/utility/run.py
Python
def _determine_service(self, 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.
    """
    # sourcery skip: assign-if-exp, reintroduce-else
    if language in WANDBOX_COMPILERS:
        return "wandbox"
    if language in GODBOLT_COMPILERS:
        return "godbolt"
    return None
_create_result_embed(ctx: commands.Context[Tux], output: str, language: str, service: str) -> discord.Embed async

Create a result embed for code execution output.

Parameters:

Name Type Description Default
ctx Context[Tux]

The command context.

required
output str

The execution output.

required
language str

The programming language.

required
service str

The service used for execution.

required

Returns:

Type Description
Embed

The created embed.

Source code in tux/cogs/utility/run.py
Python
async def _create_result_embed(
    self,
    ctx: commands.Context[Tux],
    output: str,
    language: str,
    service: str,
) -> discord.Embed:
    """
    Create a result embed for code execution output.

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The command context.
    output : str
        The execution output.
    language : str
        The programming language.
    service : str
        The service used for execution.

    Returns
    -------
    discord.Embed
        The created embed.
    """
    service_link = SERVICE_LINKS.get(service, service)
    description = f"-# Service provided by {service_link}\n```{language}\n{output}\n```"

    return EmbedCreator.create_embed(
        bot=self.bot,
        embed_type=EmbedCreator.INFO,
        user_name=ctx.author.name,
        user_display_avatar=ctx.author.display_avatar.url,
        title="",
        description=description,
    )
_create_close_button_view() -> discord.ui.View

Create a view with a close button.

Returns:

Type Description
View

The view with close button.

Source code in tux/cogs/utility/run.py
Python
def _create_close_button_view(self) -> discord.ui.View:
    """
    Create a view with a close button.

    Returns
    -------
    discord.ui.View
        The view with close button.
    """

    async def close_callback(interaction: discord.Interaction) -> None:
        if interaction.message:
            await interaction.message.delete()

    button = discord.ui.Button[discord.ui.View](style=discord.ButtonStyle.red, label="✖ Close")
    button.callback = close_callback

    view = discord.ui.View()
    view.add_item(button)
    return view
_extract_code_from_message(ctx: commands.Context[Tux], code: str | None) -> str | None async

Extract code from the command or referenced message.

Parameters:

Name Type Description Default
ctx Context[Tux]

The command context.

required
code str | None

Code provided directly in the command.

required

Returns:

Type Description
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.

Source code in tux/cogs/utility/run.py
Python
async def _extract_code_from_message(self, ctx: commands.Context[Tux], code: str | None) -> str | None:
    """
    Extract code from the command or referenced message.

    Parameters
    ----------
    ctx : commands.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.
    """
    if code:
        return code

    # Check for replied message
    if ctx.message.reference and ctx.message.reference.message_id:
        with suppress(discord.NotFound):
            referenced_message = await ctx.fetch_message(ctx.message.reference.message_id)
            if "```" in referenced_message.content:
                return referenced_message.content.split("```", 1)[1]

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

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:

Name Type Description Default
ctx Context[Tux]

The command context.

required
code str | None

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

None

Raises:

Type Description
MissingCodeError

When no code is provided and no replied message contains code.

InvalidCodeFormatError

When the code format is invalid or missing language specification.

UnsupportedLanguageError

When the specified language is not supported.

CompilationError

When code compilation or execution fails.

Source code in tux/cogs/utility/run.py
Python
@commands.command(name="run", aliases=["compile", "exec"])
async def run(self, ctx: commands.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 : commands.Context[Tux]
        The command context.
    code : str | None, optional
        The code to execute, or None to use referenced message. Defaults to None.

    Raises
    ------
    MissingCodeError
        When no code is provided and no replied message contains code.
    InvalidCodeFormatError
        When the code format is invalid or missing language specification.
    UnsupportedLanguageError
        When the specified language is not supported.
    CompilationError
        When code compilation or execution fails.
    """

    # Extract code from command or referenced message
    extracted_code = await self._extract_code_from_message(ctx, code)

    if not extracted_code:
        raise MissingCodeError

    # Parse the code block
    language, source_code = self._parse_code_block(extracted_code)

    if not language or not source_code.strip():
        raise InvalidCodeFormatError

    # Determine service to use
    service = self._determine_service(language)
    if not service:
        raise UnsupportedLanguageError(language, SUPPORTED_LANGUAGES)

    # Add loading reaction
    await ctx.message.add_reaction(LOADING_REACTION)

    try:
        # Execute the code
        output = await self.services[service].run(language, source_code)

        if output is None:
            raise CompilationError

        # Create and send result embed
        cleaned_output = _remove_ansi(output)
        result_embed = await self._create_result_embed(ctx, cleaned_output, language, service)
        view = self._create_close_button_view()

        await ctx.send(embed=result_embed, view=view)

    finally:
        # Remove loading reaction
        with suppress(discord.HTTPException):
            await ctx.message.clear_reaction(LOADING_REACTION)
languages(ctx: commands.Context[Tux]) -> None async

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

Parameters:

Name Type Description Default
ctx Context[Tux]

The command context.

required
Source code in tux/cogs/utility/run.py
Python
@commands.command(name="languages", aliases=["langs", "lang"])
async def languages(self, ctx: commands.Context[Tux]) -> None:
    """
    Display all supported programming languages to use with the `run` command.

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The command context.
    """

    languages_text = ", ".join(SUPPORTED_LANGUAGES)

    help_text = (
        "The following languages are currently supported by the `run` command:\n"
        f"```{languages_text}\n```\n\n"
        "Please use triple backticks and provide syntax highlighting like below:\n"
        '```\n`\u200b``python\nprint("Hello, World!")\n`\u200b``\n```\n'
    )

    embed = EmbedCreator.create_embed(
        bot=self.bot,
        embed_type=EmbedCreator.INFO,
        user_name=ctx.author.name,
        user_display_avatar=ctx.author.display_avatar.url,
        title="Supported Languages",
        description=help_text,
    )

    await ctx.send(embed=embed)

Functions

_remove_ansi(text: str) -> str

Remove ANSI escape sequences from text.

Parameters:

Name Type Description Default
text str

Text containing ANSI escape sequences.

required

Returns:

Type Description
str

Text with ANSI sequences removed.

Source code in tux/cogs/utility/run.py
Python
def _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.
    """
    return ANSI_PATTERN.sub("", text)

_remove_backticks(text: str) -> str

Remove backticks from text.

Parameters:

Name Type Description Default
text str

Text containing backticks.

required

Returns:

Type Description
str

Text with backticks removed.

Source code in tux/cogs/utility/run.py
Python
def _remove_backticks(text: str) -> str:
    """
    Remove backticks from text.

    Parameters
    ----------
    text : str
        Text containing backticks.

    Returns
    -------
    str
        Text with backticks removed.
    """
    return BACKTICKS_PATTERN.sub("", text)