Skip to content

tux.cogs.snippets.list_snippets

Classes:

Name Description
ListSnippets

Functions:

Name Description
setup

Load the ListSnippets cog.

Classes

ListSnippets(bot: Tux)

Bases: SnippetsBaseCog

Methods:

Name Description
list_snippets

List snippets, optionally filtering by a search query.

is_snippetbanned

Check if a user is currently snippet banned in a guild.

check_if_user_has_mod_override

Check if the user invoking the command has moderator permissions (PL >= configured level).

snippet_check

Check if a user is allowed to modify or delete a snippet.

send_snippet_error

Send a standardized snippet error embed.

Source code in tux/cogs/snippets/list_snippets.py
Python
def __init__(self, bot: Tux) -> None:
    super().__init__(bot)
    self.list_snippets.usage = generate_usage(self.list_snippets)

Functions

list_snippets(ctx: commands.Context[Tux], *, search_query: str | None = None) -> None async

List snippets, optionally filtering by a search query.

Displays snippets in a paginated embed, sorted by usage count (descending). The search query filters by snippet name or content (case-insensitive).

Parameters:

Name Type Description Default
ctx Context[Tux]

The context of the command.

required
search_query str | None

The query to filter snippets by name or content.

None
Source code in tux/cogs/snippets/list_snippets.py
Python
@commands.command(
    name="snippets",
    aliases=["ls"],
)
@commands.guild_only()
async def list_snippets(self, ctx: commands.Context[Tux], *, search_query: str | None = None) -> None:
    """List snippets, optionally filtering by a search query.

    Displays snippets in a paginated embed, sorted by usage count (descending).
    The search query filters by snippet name or content (case-insensitive).

    Parameters
    ----------
    ctx : commands.Context[Tux]
        The context of the command.
    search_query : str | None, optional
        The query to filter snippets by name or content.
    """
    assert ctx.guild

    # Fetch all snippets for the guild
    # Sorting by creation date first might be slightly inefficient if we immediately resort by uses.
    # Consider fetching sorted by uses if the DB supports it efficiently, or fetching unsorted.

    all_snippets: list[Snippet] = await self.db.snippet.get_all_snippets_by_guild_id(ctx.guild.id)

    # Sort by usage count (most used first)
    all_snippets.sort(key=lambda s: s.uses, reverse=True)

    # Apply search filter if provided
    filtered_snippets = all_snippets

    if search_query:
        query = search_query.lower()
        filtered_snippets = [
            snippet
            for snippet in all_snippets
            if query in (snippet.snippet_name or "").lower() or query in (snippet.snippet_content or "").lower()
        ]

    if not filtered_snippets:
        await self.send_snippet_error(
            ctx,
            description="No snippets found matching your query." if search_query else "No snippets found.",
        )
        return

    # Set up pagination menu
    menu = ViewMenu(ctx, menu_type=ViewMenu.TypeEmbed, show_page_director=False)

    # Add pages based on filtered snippets
    total_snippets = len(filtered_snippets)

    for i in range(0, total_snippets, CONST.SNIPPET_PAGINATION_LIMIT):
        page_snippets = filtered_snippets[i : i + CONST.SNIPPET_PAGINATION_LIMIT]

        embed = self._create_snippets_list_embed(
            ctx,
            page_snippets,
            total_snippets,
            search_query,
        )

        menu.add_page(embed)

    menu_buttons = [
        ViewButton.go_to_first_page(),
        ViewButton.back(),
        ViewButton.next(),
        ViewButton.go_to_last_page(),
        ViewButton.end_session(),
    ]

    menu.add_buttons(menu_buttons)

    await menu.start()
is_snippetbanned(guild_id: int, user_id: int) -> bool async

Check if a user is currently snippet banned in a guild.

Parameters:

Name Type Description Default
guild_id int

The ID of the guild to check.

required
user_id int

The ID of the user to check.

required

Returns:

Type Description
bool

True if the user is snippet banned, False otherwise.

Source code in tux/cogs/snippets/list_snippets.py
Python
Displays snippets in a paginated embed, sorted by usage count (descending).
The search query filters by snippet name or content (case-insensitive).

Parameters
----------
ctx : commands.Context[Tux]
    The context of the command.
search_query : str | None, optional
    The query to filter snippets by name or content.
"""
assert ctx.guild

# Fetch all snippets for the guild
# Sorting by creation date first might be slightly inefficient if we immediately resort by uses.
# Consider fetching sorted by uses if the DB supports it efficiently, or fetching unsorted.

all_snippets: list[Snippet] = await self.db.snippet.get_all_snippets_by_guild_id(ctx.guild.id)

# Sort by usage count (most used first)
all_snippets.sort(key=lambda s: s.uses, reverse=True)

# Apply search filter if provided
filtered_snippets = all_snippets

if search_query:
    query = search_query.lower()
    filtered_snippets = [
        snippet
        for snippet in all_snippets
        if query in (snippet.snippet_name or "").lower() or query in (snippet.snippet_content or "").lower()
    ]

if not filtered_snippets:
    await self.send_snippet_error(
        ctx,
        description="No snippets found matching your query." if search_query else "No snippets found.",
    )
    return

# Set up pagination menu
menu = ViewMenu(ctx, menu_type=ViewMenu.TypeEmbed, show_page_director=False)

# Add pages based on filtered snippets
total_snippets = len(filtered_snippets)

for i in range(0, total_snippets, CONST.SNIPPET_PAGINATION_LIMIT):
_create_snippets_list_embed(ctx: commands.Context[Tux], snippets: list[Snippet], total_snippets: int, search_query: str | None = None) -> discord.Embed

Create an embed for displaying a paginated list of snippets.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context object.

required
snippets list[Snippet]

The list of snippets for the current page.

required
total_snippets int

The total number of snippets matching the query.

required
search_query str | None

The search query used, if any.

None

Returns:

Type Description
Embed

The generated embed.

Source code in tux/cogs/snippets/list_snippets.py
Python
            embed = self._create_snippets_list_embed(
                ctx,
                page_snippets,
                total_snippets,
                search_query,
            )

            menu.add_page(embed)

        menu_buttons = [
            ViewButton.go_to_first_page(),
            ViewButton.back(),
            ViewButton.next(),
            ViewButton.go_to_last_page(),
            ViewButton.end_session(),
        ]

        menu.add_buttons(menu_buttons)

        await menu.start()


async def setup(bot: Tux) -> None:
    """Load the ListSnippets cog."""
    await bot.add_cog(ListSnippets(bot))
check_if_user_has_mod_override(ctx: commands.Context[Tux]) -> bool async

Check if the user invoking the command has moderator permissions (PL >= configured level).

snippet_check(ctx: commands.Context[Tux], snippet_locked: bool = False, snippet_user_id: int = 0) -> tuple[bool, str] async

Check if a user is allowed to modify or delete a snippet.

Checks for moderator override, snippet bans, role restrictions, snippet lock status, and snippet ownership.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context object.

required
snippet_locked bool

Whether the snippet is locked. Checked only if True. Defaults to False.

False
snippet_user_id int

The ID of the snippet's author. Checked only if non-zero. Defaults to 0.

0

Returns:

Type Description
tuple[bool, str]

A tuple containing a boolean indicating permission status and a reason string.

_get_snippet_or_error(ctx: commands.Context[Tux], name: str) -> Snippet | None async

Fetch a snippet by name and guild, sending an error embed if not found.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context object.

required
name str

The name of the snippet to fetch.

required

Returns:

Type Description
Snippet | None

The fetched Snippet object, or None if not found.

send_snippet_error(ctx: commands.Context[Tux], description: str) -> None async

Send a standardized snippet error embed.

Parameters:

Name Type Description Default
ctx Context[Tux]

The context object.

required
description str

The error message description.

required

Functions

setup(bot: Tux) -> None async

Load the ListSnippets cog.

Source code in tux/cogs/snippets/list_snippets.py
Python
async def setup(bot: Tux) -> None:
    """Load the ListSnippets cog."""
    await bot.add_cog(ListSnippets(bot))