Skip to content

Coming from discord.py

CascadeUI is built on discord.py. A StatefulLayoutView is a discord.ui.LayoutView and a StatefulView is a discord.ui.View, so the components, styles, interactions, and commands you know work as they always have. What changes is the code every panel repeats around them: checking who clicked, keeping one panel per person, freezing a panel that times out, answering each click in time. This page shows that code beside what replaces it.

The Counter, Both Ways

The counter from Your First Panel: one counter per person in each server, only its owner can click it, and it freezes after three minutes without a click.

import discord
from discord.ext import commands

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())
open_counters = {}  # (user id, server id) -> the counter open there


class CounterView(discord.ui.LayoutView):
    def __init__(self, owner_id: int, key: tuple):
        super().__init__(timeout=180)
        self.owner_id = owner_id
        self.key = key
        self.message = None
        self.count = 0
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(discord.ui.Container(discord.ui.TextDisplay(f"Count: **{self.count}**")))
        button = discord.ui.Button(label="+1", style=discord.ButtonStyle.primary)
        button.callback = self.increment
        self.add_item(discord.ui.ActionRow(button))

    async def interaction_check(self, interaction: discord.Interaction) -> bool:  # (1)!
        if interaction.user.id != self.owner_id:
            await interaction.response.send_message("You cannot interact with this.", ephemeral=True)
            return False
        return True

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        self.build_ui()
        await interaction.response.edit_message(view=self)  # (2)!

    async def on_timeout(self):  # (3)!
        if open_counters.get(self.key) is self:
            del open_counters[self.key]
        for item in self.walk_children():
            if isinstance(item, discord.ui.Button):
                item.disabled = True
        await self.message.edit(view=self)


@bot.tree.command(description="Open a counter")
async def counter(interaction: discord.Interaction):
    key = (interaction.user.id, interaction.guild_id)
    old = open_counters.pop(key, None)  # (4)!
    if old is not None:
        old.stop()
        await old.message.delete()
    view = CounterView(interaction.user.id, key)
    await interaction.response.send_message(view=view)
    view.message = await interaction.original_response()
    open_counters[key] = view
  1. Refuses everyone but the owner, in a reply only they see.
  2. Answers the click by editing the message. The answer has to reach Discord within 3 seconds of the click.
  3. Disables the button when the timeout ends. Without it, discord.py leaves the button enabled, and a click on it fails.
  4. Keeps one counter per person in each server: the old one stops, and its message is deleted.
import discord
from discord.ext import commands

from cascadeui import StatefulButton, StatefulLayoutView, card

bot = commands.Bot(command_prefix="!", intents=discord.Intents.default())


class CounterView(StatefulLayoutView):
    instance_limit = 1  # (1)!

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.count = 0
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"Count: **{self.count}**"))
        self.add_item(
            discord.ui.ActionRow(
                StatefulButton(
                    label="+1",
                    style=discord.ButtonStyle.primary,
                    callback=self.increment,
                    allow_double_click=True,  # (2)!
                )
            )
        )

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        self.build_ui()
        await self.refresh()  # (3)!


@bot.tree.command(description="Open a counter")
async def counter(interaction: discord.Interaction):
    await CounterView(interaction=interaction).send()
  1. One counter per person in each server. A second /counter closes the first and deletes its message.
  2. Counts both clicks of a double click, as the discord.py version does. Without it, the second is dropped.
  3. refresh() comes with every view: it edits the message as the click's answer, in one request.

The owner check and the freeze at the timeout take no code: they are the defaults.

Diagram: one click on the counter, in each library. In discord.py the code you write checks who clicked and replies to a refusal, changes the count and rebuilds the panel, and answers with edit_message() within 3 seconds. A callback slower than that fails the click, and two clicks run at the same time. In CascadeUI the library acknowledges a click still running after 2.5 seconds, checks who clicked and replies to a refusal, and runs clicks one at a time, and the code you write changes the count and calls build_ui() and refresh(), and the library sends the edit as the click's answer, in one request.

What Replaces What

In discord.py In CascadeUI See
interaction_check() comparing the clicker with the owner, and the refusal owner_only = True, the default, or allowed_users for a list of people Who Can Click
A dict of open panels, closing the old one yourself instance_limit = 1 How Many Can Exist
on_timeout() disabling every button and editing the message Nothing: the default on_timeout() does it When the Timeout Ends
interaction.response.edit_message(view=self) refresh(), which edits the message as the click's answer The Usual Callback
interaction.response.defer() before slow work Nothing: a click still running after 2.5 seconds is acknowledged for it The Usual Callback
interaction.original_response(), kept for later edits send() keeps the message. A public panel's is read back through the channel, so its edits outlast the interaction's 15 minutes once that read lands Two Ways to Edit a Message
stop(), then editing or deleting the message exit(), which freezes or deletes it by exit_policy Closing a View
A lock, so two clicks do not edit the message at once serialize_interactions = True, the default Changing the Defaults
Nothing: a double click runs the callback twice Dropped by default, and allow_double_click=True counts every click Double Clicks
bot.add_view() at every start, with the message ids saved yourself PersistentLayoutView with a persistence_key, and persistence set up. Each component still needs its custom_id Panels That Survive Restarts
Module-level dicts shared by several panels Scoped state in the store Adding Shared State

What Stays the Same

  • Components. discord.ui.Button, Select, ActionRow, Container, TextDisplay, Section, and the rest go in a view as they do in discord.py, under the same layout rules. A plain discord.ui.Button with its callback set works too, and gets the same checks. StatefulButton adds the callback= argument and records each click in the store.
  • The interaction. interaction.user, interaction.guild, and interaction.response are discord.py's. A callback can still answer with interaction.response.send_message(), and respond() does the same and falls back to a followup when the click has already been acknowledged.
  • The view. add_item(), clear_items(), walk_children(), wait(), and is_finished() work as in discord.py. timeout counts from the last click or edit, not the last click alone (Timeout).
  • Bots and commands. The bot, its intents, its commands, and its cogs are unchanged. Build the view with the command's interaction (or context) and call send() in place of interaction.response.send_message(view=...).

Coming From a Paginator Gist

Many discord.py bots page their lists with Soheab's paginator gists, the Components V2 one and the classic one. PaginatedLayoutView does the same job:

In the gists In CascadeUI
ButtonPaginator(pages, ...) and start() PaginatedLayoutView.from_data(items, per_page=..., formatter=..., interaction=...) and send()
author_id= owner_only = True, the default
per_page= per_page= on from_data()
format_page() formatter= on from_data(), a plain or an async function
convert_str_to_text_display=True Nothing: a page of text is drawn as a card in the theme's color
add_buttons_to_container=True nav_inside_container = True
The Stop button auto_exit_button = True
delete_message_after=True exit_policy = "delete"
disable_items_after=True exit_policy = "disable", the default
At the timeout, the classic gist leaves its buttons on screen The panel freezes, and When the Timeout Ends shows how to delete it instead

From five pages, the row also has first-page, last-page, and go-to buttons, and from_cursor() pages through data fetched a page at a time. The gists shaped CascadeUI's paginator and remain a good way to learn the discord.py pieces underneath.

Next

  • Your First Panel builds the counter step by step, if you have not yet.
  • Views covers each row of the table above.
  • Patterns shows finished panels: menus, forms, wizards, tabs, paged lists.