Build predictable, state-driven interfaces with discord.py . A Redux-inspired UI framework that introduces centralized state, access control, lifecycle control, and predictable data flow to Discord applications. Documentation · Quick Start · Example Cogs Built with CascadeUI BerryPacks A Celeste card-collecting game for Discord from Celeste Modding Central. Trailer · Discord Why…
Build predictable, state-driven interfaces with discord.py.
A Redux-inspired UI framework that introduces centralized state, access control, lifecycle control, and predictable data flow to Discord applications.
Each view keeps its own attributes, and other messages are edited by hand
One store, and every view that listens redraws, in any server
Restarts
Each persistent view class is added back in setup_hook, its state rebuilt by hand
Persistent interfaces come back on their own messages
Who can click
Anyone, unless the view writes interaction_check
Only the person who opened it, unless allowed_users lets others in (a persistent interface answers anyone)
Copies
Nothing stops a second copy
instance_limit replaces the old one or refuses the new one
The 3-second deadline
A slow callback calls defer() first, or the click fails
Clicks are acknowledged automatically
Double clicks
Each click runs the callback
A quick second click is dropped
Ephemeral replies
Buttons stop answering after 15 minutes
A Continue button carries the interface on
Screens
The bot swaps views and tracks the way back
push() opens a screen, and Back returns
Undo
Not available
enable_undo = True
Common interfaces
Built from scratch
Menus, forms, wizards, tabs, pages, and leaderboards
Quick Start
pip install pycascadeui
Python 3.10+ and discord.py 2.7+. For a database backend, install "pycascadeui[sqlite]" or "pycascadeui[postgres]".
A counter that redraws on every click. Only the person who opened it can click, opening a second one in the same server closes their first, and it freezes after three minutes without a click.
import discord
from cascadeui import StatefulButton, StatefulLayoutView, card
class CounterView(StatefulLayoutView):
instance_limit = 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, # every click counts, even a quick second one
)
)
)
async def increment(self, interaction: discord.Interaction):
self.count += 1
self.build_ui()
await self.refresh()
@bot.tree.command(description="Open a counter") # bot is your commands.Bot
async def counter(interaction: discord.Interaction):
await CounterView(interaction=interaction).send()
The same counter with discord.py on its own
import discord
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:
if interaction.user.id != self.owner_id: # refuses everyone but the owner
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) # has to reach Discord within 3 seconds
async def on_timeout(self): # without this, the button stays enabled and a click on it fails
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") # bot is your commands.Bot
async def counter(interaction: discord.Interaction):
key = (interaction.user.id, interaction.guild_id)
old = open_counters.pop(key, None) # one counter per person in each server
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
Your First Panel builds it step by step, with the whole bot file.
Highlights
Centralized State
Keep state for each person, each server, or everyone. Every interface that shows it redraws on its own, wherever it was posted.
class CounterView(StatefulLayoutView):
state_scope = "user" # one count for each person, in every server
subscribed_actions = {"SCOPED_UPDATE"}
def build_ui(self):
count = self.scoped_state.get("count", 0)
... # the card and the +1 button, as in the Quick Start
async def increment(self, interaction):
await self.dispatch_scoped(lambda current: {"count": current.get("count", 0) + 1})
Scalability
An interface that leaves an action out of subscribed_actions costs the event loop a microsecond or a few, and one whose state_selector() returns what it did last time costs a few more, so thousands of interfaces share one store and only the ones a change reaches redraw. A bot split into processes by shard restores only the interfaces on its own shards, and on PostgreSQL every saved write reaches the other processes, which read it into their own stores.
import os
from discord.ext import commands
from cascadeui import (
PersistenceMiddleware,
PostgresBackend,
StatefulLayoutView,
read_slot,
setup_middleware,
)
class ScoreBadge(StatefulLayoutView):
subscribed_actions = {"SCORE_CHANGED"} # every other action passes this interface by
def state_selector(self, state):
return read_slot(state, "scores", self.user_id) # redraws only when this person's score changes
class MyBot(commands.AutoShardedBot):
async def setup_hook(self):
backend = PostgresBackend(os.environ["DATABASE_URL"]) # one database for every process
await setup_middleware(PersistenceMiddleware(backend=backend, bot=self))
Persistent Interfaces
discord.py answers clicks after a restart only for views the bot registers again itself, with their state rebuilt by hand. CascadeUI records each persistent interface it posts and restores it on its own message, built with the arguments it was posted with. Turning persistence on is one line in setup_hook.
import discord
from discord.ext import commands
from cascadeui import (
PersistenceMiddleware,
PersistentLayoutView,
SQLiteBackend,
StatefulButton,
card,
setup_middleware,
)
class MyBot(commands.Bot):
async def setup_hook(self):
await setup_middleware(PersistenceMiddleware(backend=SQLiteBackend("cascadeui.db"), bot=self))
class TicketDesk(PersistentLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
button = StatefulButton(label="Open Ticket", custom_id="desk:open", callback=self.open_ticket)
self.add_item(card("## Support", "Click the button to open a ticket.", discord.ui.ActionRow(button)))
async def open_ticket(self, interaction):
await self.respond(interaction, "Ticket opened.", ephemeral=True)
await TicketDesk(context=ctx, persistence_key=f"desk:{ctx.guild.id}").send() # in a command
Access Control
By default an interface answers only the person who opened it (a persistent one answers anyone), and allowed_users lets others in. Anyone else gets a private reply, and the callback never runs. instance_limit caps how many copies can be open at once.
class MatchView(StatefulLayoutView):
instance_limit = 1 # one open match for each person in each server
unauthorized_message = "This match is between two other players."
def __init__(self, *, opponent, **kwargs):
super().__init__(**kwargs)
self.allowed_users = {self.user_id, opponent}
forfeit = StatefulButton(label="Forfeit", callback=self.forfeit)
self.add_item(card(f"<@{self.user_id}> challenged {opponent.mention}."))
self.add_item(discord.ui.ActionRow(forfeit))
async def forfeit(self, interaction):
await self.respond(interaction, f"{interaction.user.mention} forfeits.", ephemeral=False)
await self.exit()
Navigation
push() opens a screen on the same message, and Back rebuilds the one before.
class HubView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
settings = StatefulButton(label="Settings", callback=self.open_settings)
self.add_item(card("## Hub"))
self.add_item(discord.ui.ActionRow(settings))
async def open_settings(self, interaction):
await self.push(SettingsView, interaction)
class SettingsView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_item(card("## Settings"))
self.add_item(self.make_nav_row()) # Back and Exit
Long-Lived Ephemeral Interfaces
Discord lets a bot edit an ephemeral reply for 15 minutes after the last click that updated it. An ephemeral interface with no timeout offers a Continue button before then, and one click brings the same interface back, on the same message, with 15 more minutes.
class SettingsView(StatefulLayoutView):
timeout = None # a Continue button carries it past 15 minutes
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_item(card("## Settings", "Only you can see this panel."))
await SettingsView(interaction=interaction).send(ephemeral=True)
Undo and Redo
With undo on, every change a view’s actions make becomes a step. A step holds only the keys it changed, so an undo leaves everything else as it stands.
class NotificationsPanel(StatefulLayoutView):
enable_undo = True # with UndoMiddleware installed in setup_hook
def build_ui(self):
... # the toggles, and Undo and Redo buttons that call the two methods below
async def undo_last(self, interaction):
await self.undo()
async def redo_last(self, interaction):
await self.redo()
Components V2 and Embeds
StatefulLayoutView builds the whole message from components, with text and controls together in cards. StatefulView sends embeds with rows of buttons under them. Both read the same store, so one poll written both ways stays in step.
Developer Tools
An inspector and an owner-only /cascadeui command group show open views, sessions, the action history, and render timings without leaving Discord.
await bot.add_cog(DevToolsCog(bot))
Patterns
Prebuilt views for the interfaces most bots need. Subclass one and fill in the parts that change. Composites and grids are components you add to any view.
Menu Each category opens on the same message, and Back returns to the menu.
Tabs Several tabs on one message, each drawn when it is opened.
Form Buttons, toggles, and modal fields, radio groups and checkboxes included, with validators on any field.
Wizard Steps with an optional check before each Next, and a progress bar.
Paginated Any list a page at a time, or pages fetched from a database.
Paginated Region Page buttons for one card, while the rest of the interface stays as it is.
Leaderboard Ranked pages built from a list of scores, with avatars when given the bot.
Collapsible A section that opens and closes inside the card.
Button Grid A board of buttons, each built from its row and column.
Emoji Grid An emoji board that rewrites its own text when a cell changes.
Every change to the store is an action. Middleware sees it first, a reducer turns it into the new state, and each view that listens redraws its own message from that state.
Coming From Redux or React?
CascadeUI brings Redux’s design to Discord. Most of its core pieces have a close analogue in Redux or React:
CascadeUI
Closest Redux / React Analogue
StateStore
Redux store
@cascade_reducer
Redux reducer
@computed
Reselect / useMemo
build_ui()
React component render()
on_state_changed
componentDidUpdate + auto re-render
push() / pop() / replace()
React Router navigation
Middleware chain
applyMiddleware
PersistenceMiddleware
redux-persist (opt-in per slot)
The analogues stop where Discord does not resemble a browser. Middleware can await, saved state outlives the process as Discord messages do, and the interaction model has no React or Redux equivalent: a 3-second deadline to acknowledge a click, webhook tokens that expire after 15 minutes, and per-channel rate limits. How CascadeUI Thinks covers those on their own terms.
What’s Included
Area
What It Covers
Guide
State
One store, actions and reducers, @computed values, scoped state (per person, per server, or global), batching, middleware, undo and redo
The repository has 19 example cogs, each a complete feature a bot can load, from settings menus and dashboards to multiplayer games with hidden information.
v2_tictactoe.py Two players take turns on one board, and everyone else's clicks are refused.
v2_player.py A card its own timer redraws, with Back, Pause, Skip, and a queue.
Example Cogs lists every cog and the bot that loads them.
git clone https://github.com/HollowTheSilver/CascadeUI.git
cd CascadeUI
pip install -e ".[dev,sqlite,postgres]"
pytest tests/ -n auto --dist loadgroup
black cascadeui/
isort cascadeui/
Developer’s Note
I built CascadeUI on more than ten years of Python and roughly fifteen years of development experience. This project uses Anthropic agents across the entire codebase, and I don’t attempt to hide that. The design and every decision that ships are exclusively my own. The agents are amplifiers, not substitutes.
– Hollow
MIT License
CascadeUI is not affiliated with or endorsed by Discord Inc. Discord and the Discord logo are trademarks of Discord Inc.
评论