Skip to content

Lifecycle and Closing

A view lives from send() until it closes: through exit(), a timeout, or the deletion of its message. This page covers each of those, what the panel shows once its view has closed, the child views that close with it, and what happens when a callback raises.

From Send to Close

Every view goes through the same four stages:

  1. Built. __init__ runs and the view subscribes to the store. Nothing is in Discord yet.
  2. Sent. send() loads the view, checks it, and posts the panel. See Building and Sending.
  3. Live. Clicks run callbacks. Each click, and each edit that reaches Discord, restarts the timeout.
  4. Closed. The view takes no more clicks, leaves the store, and frees its place in its instance limit. The panel stays on screen without working controls, or is deleted.

This view closes when someone clicks Exit, or 5 minutes after the last click:

import discord

from cascadeui import StatefulButton, StatefulLayoutView, card


class CounterView(StatefulLayoutView):
    timeout = 300  # (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", callback=self.increment),
                self.make_exit_button(),  # (2)!
            )
        )

    async def increment(self, interaction: discord.Interaction):
        self.count += 1
        self.build_ui()
        await self.refresh()
  1. Seconds without a click before the view closes on its own.
  2. make_exit_button() comes with every view: an Exit button that closes the view and leaves the panel on screen with its buttons disabled.

A click on +1 edits the message to Count 1 and starts the 300-second timeout again. When it runs out, on_timeout() edits the panel once more with both buttons disabled and closes the view

A closed view cannot be sent again: send() raises RuntimeError. It raises too for a view already being sent, and for one that has handed its panel on with push() or pop(). Build a new instance instead.

Timeout

A view closes on its own 180 seconds after its last click. Set timeout in the class body, or pass timeout= to the constructor, which wins over the class:

class SettingsView(StatefulLayoutView):
    timeout = 600  # 10 minutes


view = SettingsView(interaction=interaction, timeout=None)  # never times out

The count runs from the last click or the last edit that reached Discord, so a panel your code keeps redrawing stays up. That includes a card with nothing to click: it closes timeout seconds after its last edit, and one that should stay up between edits sets timeout=None. A click on a DynamicPersistentButton the view drew, such as a role button, counts as a click on the view.

Assigning view.timeout on a live view restarts the count from that moment: a shorter value closes it sooner, and None or 0 stops it. set_class_attribute("timeout", ...) does the same. The value is a number of seconds, at least 0, or None. Anything else raises where it is set, in a class body when the class is defined: TypeError for a string or a bool, ValueError for NaN or a negative number.

A persistent view never times out. Its timeout is None, and any number other than 0, which it reads as None when the view is built, raises ValueError. A screen pushed onto a persistent panel goes back to the panel when it times out, rather than leaving the panel frozen, unless it defines its own on_timeout().

A public panel can be edited for as long as its view lives: after the send, the view reads its message back through the channel, so its edits do not depend on the command's 15-minute interaction token. If that read never lands (Discord refuses it for missing access, or every retry fails), edits made outside a click stop when the token runs out: see A Request That Never Reaches Discord. An ephemeral panel cannot be read back that way, and Ephemeral Views says what the library does about it.

When the Timeout Ends

on_timeout() closes the view: it closes the views attached to it, leaves the store, frees its place in its instance limit, and edits the panel with every control disabled. It freezes the panel even under exit_policy = "delete", since nobody closed it and the person may still be reading it. A view with nothing to click closes without an edit.

Override it to change the last screen. Draw the screen, then call super():

class MatchView(StatefulLayoutView):
    async def on_timeout(self):
        self.abandoned = True
        self.build_ui()  # (1)!
        await super().on_timeout()  # (2)!
  1. This view's build_ui() draws "Match abandoned" when abandoned is set.
  2. Closes the view and sends the final screen with its controls disabled, in one edit.

To delete the panel when the view times out, close it with exit():

class MatchView(StatefulLayoutView):
    async def on_timeout(self):
        await self.exit(delete_message=True)

An override must close the view

An on_timeout() override calls super().on_timeout() or exit(). One that calls neither leaves the view in the store, still holding its place in its instance limit, until the bot restarts.

When a dispatch draws the last screen, dispatch before super(): super().on_timeout() and exit() both take the view out of the store, so a dispatch made after them reaches other views but not this one. A refresh() after super() still reaches the panel, with its controls disabled. Draw the screen through the view rather than with message.edit(), which goes past the library: a render still in flight can land over it.

Closing a View

exit() closes the view. It closes the views attached to it, cancels its tasks, leaves the store, frees its place in its instance limit, removes a persistent panel's registration, and then freezes or deletes the panel. The class's exit_policy decides which:

class SettingsView(StatefulLayoutView):
    exit_policy = "delete"  # (1)!
  1. "disable", the default, freezes the panel. "delete" deletes the message.

An argument wins over the policy for one call: exit(delete_message=True) deletes the message and exit(delete_message=False) freezes the panel, whatever the class says. This is the three-tier precedence model: class attribute, then method override, then explicit argument.

The exit controls the library builds follow the policy too. make_exit_button() returns an Exit button for you to place, add_exit_button() adds one to the view, and make_nav_row() builds Back and Exit together (see Navigation). Each takes delete_message= to override the policy for that button. The first two also take label=, emoji=, and style=:

self.add_exit_button(label="Close", emoji=None, style=discord.ButtonStyle.danger)

On a persistent panel, give the button a custom_id, so it still works after a restart: self.add_exit_button(custom_id="settings:exit").

Close a view with exit(), not stop(). discord.py's stop() ends the view's clicks and its timeout, but leaves it in the store and holding its place in its instance limit. A card with nothing to click closes with exit(delete_message=False) and no edit, since there is nothing to disable.

What a Closed Panel Looks Like

exit(), freezing exit(), deleting Timeout
StatefulLayoutView Stays, with its controls disabled Deleted Stays, with its controls disabled
StatefulView Keeps its embeds and text, and the controls are removed Deleted Keeps its embeds and text, and the controls are disabled

The page's CounterView, closed by exit() or by its timeout, stays on screen showing Count: 1 with +1 and Exit disabled. A StatefulView twin keeps its embed after exit(), with the buttons removed, and after its timeout, with the buttons disabled. exit(delete_message=True) deletes the message, for either class

A StatefulLayoutView cannot drop its controls the way a StatefulView does: its components are the message, and Discord refuses a message with none. So it freezes instead. Link buttons stay enabled, since they open their URL with no view behind them.

To close on a final screen, draw it before exit(). The freeze sends what the view shows, in one edit:

async def finish(self, interaction: discord.Interaction):
    self.finished = True
    self.build_ui()  # draws the result
    await self.exit()  # sends it with the controls disabled

freeze_components() disables every control without closing the view, for a panel that should wait with its controls off. Call refresh() after it to show the change.

More on closing

Closing twice. A second exit() does only what the first left undone: after a freeze, exit(delete_message=True) deletes the message. One called while another close is running waits for it, for up to 30 seconds.

State changes dispatched before the close. exit(), a timeout, exit_children(), and replace() wait for the views they close to render a state change dispatched before them, for up to 30 seconds. A close made from inside that render, or one the render is waiting on, goes on without it, and so does a view whose message is already gone (deleted, or never sent), since nothing would show it. A change dispatched inside a batch() is announced when the batch closes, so close after the batch, not inside it.

Closing during a send. An exit() on a view still being sent is carried out by the send, which then returns None. See When Nothing Is Sent.

Closing from inside a navigation. exit() called from the new view's on_load(), or a rebuild= or nav_rebuild hook, during a push() or pop(), raises RuntimeError. Close the view once the navigation has returned.

A stack whose screens disagree. push() and pop() edit one message, so screens with different exit_policy values close the same panel differently depending on how deep the person went. The library logs a warning the first time a navigation crosses two policies. Declare the policy on a shared base class when every screen should agree. A confirm screen that deletes while its hub freezes is a valid shape and works as written.

A restored panel. A persistent panel restored after a restart that has not redrawn yet freezes what Discord shows, not its own tree.

A tree Discord would refuse. When the tree is empty at close, or holds a shape Discord refuses, the library sends nothing and the panel keeps its last render. A warning names the view when something was on screen.

Child Views

A view can own other views that close with it, such as the private panels of the players in a game. Pass parent= to the child's constructor, and send() attaches the child once its panel is posted:

class GameView(StatefulLayoutView):
    async def show_hand(self, interaction: discord.Interaction):
        hand = HandView(interaction=interaction, parent=self)
        await hand.send(ephemeral=True)

When the parent closes, by exit() or a timeout, each child still open closes with its message deleted. A child that already closed keeps what its own close left.

A game panel with two hands attached. When GameView exits, Kael's open hand is deleted and Mira's hand, closed at the Fold, stays as it was. When GameView dispatches GAME_FINISHED and then calls exit_children(delete_message=False), Kael's hand shows the result and freezes on it, and the game panel stays open

  • attach_child(child) attaches a view after its send, or one built without parent=. Attaching a view to itself, or to one of its own descendants, raises ValueError. Attaching a child to a second parent moves it.
  • parent reads the view a child is attached to, or None once the parent has closed. Read it rather than keeping a second reference to the parent.
  • exit_children() closes the children while the parent stays open, such as at the end of a round. It deletes their messages by default, delete_message=False freezes them, and None follows each child's exit_policy. A view attached while it runs is left for the next call, or for the parent's own close.

A state change dispatched before a close reaches each child first, so a final screen goes out as a dispatch followed by the close:

await self.dispatch("GAME_FINISHED", {"winner": winner})
await self.exit_children(delete_message=False)  # (1)!
  1. Each child renders the result, then freezes with it on screen.

A view that hands its panel on with push() or pop() hands on its children too: the view now on the panel is their parent.

When the Message Is Deleted

When someone deletes a view's message, the library closes the view: it leaves the store, frees its place in its instance limit, and drops a persistent panel's registration. Three signals tell the library about it:

The message went because How the library learns Intents needed
Someone deleted it, or purged it in bulk The gateway's message-delete events guild_messages (or dm_messages in a DM)
Its channel or thread was deleted The channel and thread delete events, since Discord sends no message deletions for these guilds
Either of the above, while the bot missed the event The view's next edit returns "Unknown Message" none

The third row is why a bot that trims its intents still closes the views of deleted panels. Without the message intents, the view of a deleted panel stays until its next edit, its timeout, or a restart. A plain discord.Client, unlike commands.Bot, has no listeners the library can add, so only the third row reaches its views. Nothing needs setting up: the library adds its listeners on the first send(), or when PersistenceMiddleware(bot=...) starts.

Two hooks run on the way:

  • on_message_gone() runs when an edit finds the message gone, before the view closes. Use it to update your own record of the message. The view's message is already None by then, so key the update on an identity you gave the view, such as a persistent panel's persistence_key.
  • on_message_delete() runs for every deletion. By default it closes the view with exit(delete_message=False). An override calls super() or exit(), or the view stays in the store.

Neither takes an argument, and an override that requires one raises TypeError when its class is defined.

from cascadeui import PersistentLayoutView


class SettingsPanel(PersistentLayoutView):
    async def on_message_gone(self):
        await forget_panel(self.persistence_key)  # (1)!

    async def on_message_delete(self):
        logger.info(f"Settings panel {self.id} was deleted")
        await super().on_message_delete()
  1. No exit() needed: the library closes the view right after this returns.

Once a view has closed, a later signal for the same deletion has nothing to do.

When a Callback Raises

When a callback raises, or a check before it does, the view's on_error() runs. By default it logs the error with its traceback and sends the person an ephemeral "Something went wrong" embed. The embed's text is the view's error_message:

class SettingsView(StatefulLayoutView):
    error_message = "Saving failed. Try again in a minute."

Override on_error() to answer differently:

class SettingsView(StatefulLayoutView):
    async def on_error(self, interaction, error, item):
        logger.error(f"Settings failed in {item!r}", exc_info=error)
        await self.respond(interaction, "Saving failed. The bot owner has been told.", ephemeral=True)

on_error() runs before the library acknowledges the click, as in discord.py. respond() answers at any point. interaction.response works until the click's timer acknowledges it, auto_defer_delay (2.5 seconds by default) after the click arrived. An answer through interaction.response after that is replaced by the default message, with a warning in the log.

Whatever the override leaves unanswered is acknowledged after it returns. With auto_defer = False, a click on a control with its own callback is the override's to answer, as in discord.py. See Responding to Clicks.

on_error() runs in the click's turn: with serialize_interactions on, the default, the view's next click waits until it returns. Do slow work, such as a message to the bot owner, in a task. Errors lists what the library raises and logs.