Skip to content

Building and Sending

A view draws its panel in build_ui(), loads anything it has to wait for in on_load(), and goes to Discord with send(). This page covers those three steps, redrawing with refresh(), and the settings that apply to every message a view sends.

Two Kinds of View

Discord has two message layouts, and CascadeUI has a view class for each:

  • StatefulLayoutView builds the whole message from components. Text, images, and controls sit together in cards, each with its own accent color. Use it for new views.
  • StatefulView is the classic layout: embeds and text on top, rows of buttons and selects underneath.

Both get every CascadeUI feature, from state and navigation to instance limits. They differ in how the message is made:

StatefulLayoutView StatefulView
The message's content The view's components Embeds and text, passed to send() and refresh()
Buttons and selects Inside an ActionRow, anywhere in the layout Up to 5 rows under the content
Components per message 40, counting every nested one 25 (5 rows of 5)
Accent color One per card One per embed
After exit() Stays on screen with its controls disabled Keeps its embeds, and the controls are removed

The examples on this page use StatefulLayoutView, with a tab for StatefulView where the code differs. Prebuilt views for menus, forms, wizards, tabs, pages, and leaderboards are on the Patterns pages.

Drawing the Panel

build_ui() draws the panel from the view's data. Call it again whenever the data changes. A StatefulLayoutView that nothing has drawn yet is drawn from its build_ui() when it is sent, so the call in __init__ below is optional: it draws the view sooner, which a test may want. A StatefulView's build_ui() returns the message's content instead, and the send reads it:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card


class CounterView(StatefulLayoutView):
    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", callback=self.increment))
        )

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

from cascadeui import StatefulButton, StatefulView


class CounterView(StatefulView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.count = 0
        self.add_item(StatefulButton(label="+1", callback=self.increment))  # (1)!

    def build_ui(self):
        return {"embed": discord.Embed(description=f"Count: **{self.count}**")}  # (2)!

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        await self.refresh(**self.build_ui())
  1. The controls are added once and stay. Only the embed changes.
  2. The message's content: send() posts it, and a redraw passes it to refresh().

What build_ui() does depends on the class:

  • StatefulLayoutView: it removes the components with clear_items() and adds them again. Buttons and selects go inside a discord.ui.ActionRow, since Discord refuses one placed directly on the view. Builders such as button_row() and action_section() place buttons for you. Layout Rules and Limits lists what goes where.
  • StatefulView: it returns a dict of embed=, embeds=, or content=. send() posts it, and what you pass to send() takes the place of the field it names. A state redraw passes it to refresh(), and a push() or pop() onto the view edits with it unless the view names a nav_rebuild.

build_ui() is a plain method, so __init__ can call it. Data you have to await is loaded in on_load().

Loading Data

When the panel shows data you have to await, such as rows from a database, load it in on_load(). The library awaits it before the view is sent, so the first panel already shows the data:

class ProfileView(StatefulLayoutView):
    def __init__(self, *, db, **kwargs):
        super().__init__(**kwargs)
        self.db = db  # (1)!
        self.profile = None

    async def on_load(self):
        self.profile = await self.db.fetch_profile(self.user_id)
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"## {self.profile.name}", f"Level {self.profile.level}"))
        self.add_item(
            discord.ui.ActionRow(StatefulButton(label="Refresh", callback=self.reload_profile))
        )

    async def reload_profile(self, interaction: discord.Interaction):
        await self.reload()  # (2)!
  1. A keyword of your own. See the warning below for the names the library reserves.
  2. reload() comes with every view: it runs on_load() again and redraws the panel with what it loaded.

on_load() runs at these points:

  • Before the first send. The panel goes out once the data is in.
  • On a view pushed or popped to. The screen loads before the message changes to show it, so a Back button shows fresh data. See Navigation.
  • reload() runs on_load() and then refresh(). Use it for a Refresh button, or after a click changed the data the view shows. The library calls it too, with no arguments (a persistent leaderboard's restore does), so give a Refresh button's callback another name: a reload that takes the click raises TypeError there.
  • load() runs on_load() without redrawing, for a view whose data another view reads.

A state change, a page turn, or a tab switch redraws from what was last loaded, without calling on_load().

on_load() runs one at a time on each view, whichever of these started it, so two loads never mix their results and the last to run shows the freshest data. A state change that arrives during a load redraws once the load finishes. The library's own loading outside on_load() takes the same turns: a leaderboard's rebuild, a tab or wizard step, and a from_cursor() page. An on_state_changed() override that fetches data itself does not, so fetch in on_load().

A time line of the ProfileView above, with a database call that takes 1 second. send() runs on_load() first and posts the panel at 1.0 s showing Level 4. Kael clicks Refresh at 1.5 s, and the panel is edited at 2.5 s to Level 5. A timer's reload() at 1.7 s waits for that load, then loads, and the panel is edited at 3.5 s to Level 6

Fetch first and draw after, with no await between clear_items() and the last add_item(). A refresh() your own code makes from another task, such as a timer, sends the components as they are at that moment, and could send a panel half drawn. A build_ui() that reads only what on_load() loaded never leaves one.

Keep your data off the reserved keywords

Seven constructor keywords already mean something to the library: context, interaction, state_store, session_id, user_id, guild_id, and parent. A value passed under one of them is read, not stored: a database ID passed as user_id becomes the view's owner, and no one can click it. Pass your own data under names of your own, as db= above.

More on loading

Load only the view's own data. Calling the view's own reload() or load() from inside its on_load() raises RuntimeError, since a load is already running. So does an on_load() that awaits another view's reload() while that view's on_load() awaits this one: reload the other view after this load returns. Routed through asyncio.gather() or a task the on_load() created, the same cycle cannot be detected, and logs a warning naming the view after 30 seconds.

Reloading from on_state_changed(). Await self.reload() directly. Awaiting a separate task that reloads the same view, such as await asyncio.gather(self.reload()), waits on a reload that is waiting for the redraw. Nothing raises, and a warning naming the view is logged after 30 seconds.

Slow loads. An on_load() that takes longer than auto_defer_delay (2.5 seconds by default) logs a warning naming the view, once per class. The send waits for it, and so does a click that pushes to the view. A slash command shows "Bot is thinking..." from that point until the panel takes its place (see After the Answer).

Reloads inside a cooldown. On a view with refresh_cooldown_ms set, or one waiting out a rate limit, a reload() made inside the window runs at its end, on_load() included, even from a click. A Refresh button therefore cannot query the data source faster than the window allows. A click's refresh() still goes out at once.

Sending a View

Build the view with the command's interaction or ctx, so it knows who opened it and where to reply, then call send():

@bot.tree.command(description="Show your profile")
async def profile(interaction: discord.Interaction):
    await ProfileView(interaction=interaction, db=bot.db).send()
from discord.ext import commands


@bot.hybrid_command(description="Show your profile")
async def profile(ctx: commands.Context):
    await ProfileView(context=ctx, db=bot.db).send()

send() posts the panel, records who opened it, and registers the view with the store, its session, and its instance limit, all in one call. It takes:

  • ephemeral=True to show the panel only to the person who ran the command. Discord limits how long the bot can change it, and a prefix command posts it publicly (see Ephemeral Views).
  • file= or files= to upload files with the message. See Files and Media.
  • allowed_mentions= for this message's mention rules.
  • On a StatefulView, content=, embed=, and embeds=. The dict its build_ui() returns fills what you leave out: text you pass shows above the view's embed, and an embed you pass takes its place. embeds=[] sends your text alone. A send given none of them uses its nav_rebuild's dict when build_ui() gives no content. The dict's allowed_mentions go with its text unless you pass your own.

When Nothing Is Sent

send() returns the message it posted, or None when the send left no live view on a new message. That happens in four cases:

  1. on_pre_send() returned False. Nothing is posted or registered, and the command's interaction is still unanswered, so the hook can reply with respond() to say why.
  2. The instance limit refused the view. With instance_policy = "reject", a person already at instance_limit gets the view's on_instance_limit() reply instead. See How Many Can Exist.
  3. A participant was already taken. With auto_register_participants = True, someone in allowed_users was already in another instance of the view.
  4. The view closed while it was being sent. An exit() from its own on_load(), from another task, or from a newer instance replacing it closed it, or stop() stopped it. Before the view finished loading, nothing is posted. After that, the message is posted and then closed the way the close asked: frozen or deleted.

In every case the library cleans up after itself: no entry in the store, no instance slot taken, and no live message. A view already live on a message, sent again and refused, stays live on its old message. So check the result before doing anything that assumes the panel is up:

view = ProfileView(interaction=interaction, db=bot.db)
if await view.send() is None:
    return  # the person was already told why
view.start_countdown()

To keep that check inside the class, override send() and pass its keywords on:

async def send(self, **kwargs):
    message = await super().send(**kwargs)
    if message is not None:
        self.start_countdown()
    return message
More on sending

Sending a view again. A view that is already live on a message moves when you send it again: once the new message is posted, the old one closes as exit() would close it, frozen or deleted by exit_policy, and stops answering clicks. A send that fails leaves the view where it was.

Views that cannot be sent. send() raises RuntimeError on a view that has closed, including one whose earlier send failed or was refused, and on one already being sent. Build a new view instead.

on_pre_send() runs first, before on_load() and before anything is posted, so a refusal costs nothing. It receives the command's interaction, or None for a prefix command.

Redrawing

After the view changes, call build_ui() and then refresh(), which edits the message to match. It works at any time, from a click's callback or from code of your own, such as a timer.

Start a timer in on_load() with create_task(), which ties the task to the view: exit(), a timeout, and a push or pop away cancel it. on_load() runs again on reload() and an ephemeral Continue, so keep the task it returns and start another only when that one is done. v2_player.py moves a progress bar this way, and since refresh() sends nothing when nothing changed, its timer costs no requests while the player is paused.

refresh() sends the components as they are. It does not rebuild them, so call build_ui() first. A StatefulLayoutView passes no arguments. A StatefulView passes its content again: await self.refresh(**self.build_ui()).

It accepts content=, embed=, embeds=, attachments=, and allowed_mentions=. refresh() chooses between three ways to edit a message at run time, and other keywords, such as suppress= or delete_after=, work with only some of them, so it raises TypeError for them rather than working only some of the time. For a one-off edit that needs one, edit view.message directly.

refresh() returns a RenderOutcome saying what happened, such as RENDERED or SKIPPED (nothing had changed, so nothing was sent). Most code can ignore it.

When the message has been deleted, the view closes, as it does when Discord reports the deletion (see When the Message Is Deleted). A request that never reaches Discord, such as one lost to a network failure, is not raised: the edit is dropped, refresh_degraded is set, and the next change sends the panel again. See A Request That Never Reaches Discord.

Redrawing When State Changes

When a view shows data from the state store, the library redraws it for you. List the actions the view reacts to in subscribed_actions. On each one, the default on_state_changed() calls build_ui() and then refresh(), passing on the dict a StatefulView's build_ui() returns:

class ScoreView(StatefulLayoutView):
    subscribed_actions = {"SCORE_CHANGED"}

    def build_ui(self):
        self.clear_items()
        score = self.state_store.state["application"].get("score", 0)
        self.add_item(card(f"Score: **{score}**"))

Code dispatches SCORE_CHANGED with no click. The view lists it in subscribed_actions, so build_ui() runs and one edit changes the panel from Score 0 to Score 7. Code then dispatches THEME_CHANGED, which the view does not list: nothing runs and no edit is sent

subscribed_actions is empty by default, so a view redraws for no action until you list one, except an undo or redo of its own. Every action it lists redraws it, so list only the actions that change what it shows. Subscribers and Slots covers the rest of the subscription.

Override on_state_changed() to do more than redraw:

class MatchView(StatefulLayoutView):
    subscribed_actions = {"MATCH_UPDATED"}

    async def on_state_changed(self, state):
        if state["application"]["match"]["finished"]:
            await self.exit()
            return
        await super().on_state_changed(state)

Mention Rules

Discord reads the mentions in a message again on every edit, so a panel that names users can notify them each time it redraws: a leaderboard rebuilt on every score change, a lobby redrawn on every join. Set allowed_mentions once on the class:

class ScoreboardView(StatefulLayoutView):
    allowed_mentions = discord.AllowedMentions.none()

It applies to the send and to every edit the view makes after it: each refresh(), each push or pop, and the edit that disables the panel when it closes. The default, None, uses the bot's own rules (commands.Bot(allowed_mentions=...)) on every one of those edits.

To notify for one message, such as announcing a winner, pass allowed_mentions= to send() or refresh(). LeaderboardLayoutView sets AllowedMentions.none(), since a ranking that notified its top ten on every update is rarely wanted.

One-Off Cards

For a card that needs no class of its own, such as a stats readout or a confirmation, pass it to DisplayLayoutView:

from cascadeui import DisplayLayoutView, card, key_value

stats = card("## Session Stats", key_value({"Games": 5, "Wins": 3}))
await DisplayLayoutView(interaction=interaction, container=stats).send(ephemeral=True)

Buttons inside the card work as they do on any view, with one default changed from StatefulLayoutView: owner_only is False, so anyone can click them. A card with nothing to click needs no cleanup: when it times out, the library closes the view without editing the message, since there is nothing to disable.