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:
- Built.
__init__runs and the view subscribes to the store. Nothing is in Discord yet. - Sent.
send()loads the view, checks it, and posts the panel. See Building and Sending. - Live. Clicks run callbacks. Each click, and each edit that reaches Discord, restarts the timeout.
- 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()
- Seconds without a click before the view closes on its own.
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 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)!
- This view's
build_ui()draws "Match abandoned" whenabandonedis set. - 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:
"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=:
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 |
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.
attach_child(child)attaches a view after its send, or one built withoutparent=. Attaching a view to itself, or to one of its own descendants, raisesValueError. Attaching a child to a second parent moves it.parentreads the view a child is attached to, orNoneonce 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=Falsefreezes them, andNonefollows each child'sexit_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)!
- 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'smessageis alreadyNoneby then, so key the update on an identity you gave the view, such as a persistent panel'spersistence_key.on_message_delete()runs for every deletion. By default it closes the view withexit(delete_message=False). An override callssuper()orexit(), 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()
- 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:
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.
Related¶
- Building and Sending:
send(), and what happens when nothing is sent. - Responding to Clicks: answering a click in time, and clicks on a closed panel.
- Ephemeral Views: the 15-minute limit and the Continue button.
- Panels That Survive Restarts: the setup for a persistent panel.