Skip to content

tux.cogs.utility.run

Classes:

Name Description
Run

Classes

Run(bot: Tux)

Bases: Cog

Methods:

Name Description
send_embedded_reply

A generalized version of an embed.

run

Run code in various languages. Code should be enclosed in triple backticks.

run_error

A generalized error handler for the run command.

languages

Lists all the supported languages.

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

Functions

__remove_ansi(ansi: str) -> str staticmethod

Converts ANSI encoded text into non-ANSI.

Parameters:

Name Type Description Default
ansi str

The ANSI encoded text.

required

Returns:

Type Description
str

The non-ANSI encoded text.

Source code in tux/cogs/utility/run.py
Python
@staticmethod
def __remove_ansi(ansi: str) -> str:
    """
    Converts ANSI encoded text into non-ANSI.

    Parameters
    ----------
    ansi : str
        The ANSI encoded text.

    Returns
    -------
    str
        The non-ANSI encoded text.
    """

    return ansi_re.sub("", ansi)
__remove_backticks(st: str) -> str staticmethod

Removes backticks from the provided string.

Parameters:

Name Type Description Default
st str

The string containing backticks.

required

Returns:

Type Description
str

The string without backticks.

Source code in tux/cogs/utility/run.py
Python
@staticmethod
def __remove_backticks(st: str) -> str:
    """
    Removes backticks from the provided string.

    Parameters
    ----------
    st : str
        The string containing backticks.

    Returns
    -------
    str
        The string without backticks.
    """

    return ticks_re.sub("", st)
send_embedded_reply(ctx: commands.Context[Tux], output: str, lang: str, is_wandbox: bool) -> None async

A generalized version of an embed.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context in which the command is invoked.

required
output str

The output.

required
lang str

The language of the code.

required
is_wandbox bool

True if Wandbox is used as the backend.

required
Source code in tux/cogs/utility/run.py
Python
async def send_embedded_reply(self, ctx: commands.Context[Tux], output: str, lang: str, is_wandbox: bool) -> None:
    """
    A generalized version of an embed.

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The context in which the command is invoked.
    output : str
        The output.
    lang : str
        The language of the code.
    is_wandbox: bool
        True if Wandbox is used as the backend.
    """

    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="",
        description=f"{f'Service provided by {"[Wandbox](https://wandbox.org)" if is_wandbox else "[Godbolt](https://godbolt.org/)"}'}\n```{lang}\n{output}\n```",
    )

    button = discord.ui.Button(style=discord.ButtonStyle.red, label="✖ Close")  # type: ignore
    view = discord.ui.View()
    view.add_item(button)  # type: ignore

    async def button_callback(interaction: discord.Interaction):
        if interaction.message is not None:
            await interaction.message.delete()

    button.callback = button_callback

    await ctx.send(embed=embed, view=view)
run(ctx: commands.Context[Tux], *, code: str | None) async

Run code in various languages. Code should be enclosed in triple backticks.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context in which the command is invoked.

required
code str | None

The code to be evaluated. Provide None if the code is supposed to be grabbed from the message replied to.

required
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,
):
    """
    Run code in various languages. Code should be enclosed in triple backticks.

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The context in which the command is invoked.
    code : str | None
        The code to be evaluated. Provide None if the code is supposed to be grabbed from the message replied to.
    """
    await ctx.message.add_reaction("<a:BreakdancePengu:1378346831250985061>")

    # checks if the author replied to a message or not.
    if ctx.message.reference is not None:
        msg = await ctx.fetch_message(ctx.message.reference.message_id)  # type: ignore
    else:
        msg = None

    # if the code wasnt provided, and there was no reply, Error out.
    if code is None and msg is None:
        raise commands.MissingRequiredArgument(
            commands.Parameter(name="code", kind=commands.Parameter.KEYWORD_ONLY),
        )

    # if there was no code, but there was a reply.
    if not code and msg:
        code = msg.content.split("```", 1)[1] if "```" in msg.content else None

    # if the reply was badly formatted
    if code is None:
        embed = EmbedCreator.create_embed(
            bot=self.bot,
            embed_type=EmbedCreator.ERROR,
            user_name=ctx.author.name,
            user_display_avatar=ctx.author.display_avatar.url,
            title="Fatal Exception occurred!",
            description="Bad formatting.",
        )
        await ctx.message.clear_reaction("<a:BreakdancePengu:1378346831250985061>")
        await ctx.send(embed=embed)
        return

    (language, code) = self.__parse_code(code)
    is_wandbox = "wandbox" if language in compiler_map_wandbox else "godbolt"

    if language not in compiler_map_godbolt and language not in compiler_map_wandbox:
        embed = EmbedCreator.create_embed(
            bot=self.bot,
            embed_type=EmbedCreator.ERROR,
            user_name=ctx.author.name,
            user_display_avatar=ctx.author.display_avatar.url,
            title="Fatal exception occurred.",
            description=f"No compiler could be found for target '{language}'.",
        )
        await ctx.message.clear_reaction("<a:BreakdancePengu:1378346831250985061>")
        await ctx.send(embed=embed)
        return

    filtered_output = await self.services[is_wandbox].run(language, code, None)

    if not filtered_output:
        embed = EmbedCreator.create_embed(
            bot=self.bot,
            embed_type=EmbedCreator.ERROR,
            user_name=ctx.author.name,
            user_display_avatar=ctx.author.display_avatar.url,
            title="Fatal exception occurred!",
            description="failed to get output from the compiler.",
        )
        await ctx.message.clear_reaction("<a:BreakdancePengu:1378346831250985061>")
        await ctx.send(embed=embed, delete_after=30)
        return

    await ctx.message.clear_reaction("<a:BreakdancePengu:1378346831250985061>")
    await self.send_embedded_reply(
        ctx,
        self.__remove_ansi(filtered_output),
        language,
        is_wandbox == "wandbox",
    )
run_error(ctx: commands.Context[Tux], error: Exception) async

A generalized error handler for the run command.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context in which the command is invoked.

required
error Exception

The error that occurred.

required
Source code in tux/cogs/utility/run.py
Python
@run.error
async def run_error(
    self,
    ctx: commands.Context[Tux],
    error: Exception,
):
    """
    A generalized error handler for the run command.

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The context in which the command is invoked.
    error : Exception
        The error that occurred.
    """

    desc = ""
    if isinstance(error, commands.CommandInvokeError):
        desc = error.original

    if isinstance(error, commands.MissingRequiredArgument):
        desc = f"Missing required argument: `{error.param.name}`"

    embed = EmbedCreator.create_embed(
        bot=self.bot,
        embed_type=EmbedCreator.ERROR,
        user_name=ctx.author.name,
        user_display_avatar=ctx.author.display_avatar.url,
        title="Fatal exception occurred!",
        description=str(desc),
    )

    await ctx.message.clear_reaction("<a:BreakdancePengu:1378346831250985061>")
    await ctx.send(embed=embed, delete_after=30)
languages(ctx: commands.Context[Tux]) -> None async

Lists all the supported languages.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context in which the command is invoked.

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

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The context in which the command is invoked.
    """

    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="```C, C++, C#, F#, OCaml, Haskell, Julia, Python, Javascript, Typescript, Ruby, SQL, Java, Nim, Lisp, Pascal, Perl, Pony, PHP, R, Swift, Groovy, D, Bash, Rust, Kotlin```",
    )

    await ctx.send(embed=embed)

Functions