Panels That Survive Restarts¶
A persistent panel keeps working after the bot restarts. Its message stays in the channel, and when the bot starts again the library builds the panel anew on that message, so the next click is answered as before. It suits what is posted once and used for a long time: a support desk, a role picker, a status board.
A Panel That Comes Back¶
A persistent panel subclasses PersistentLayoutView (PersistentView for a V1 panel), gives each control a
custom_id, and is sent with a persistence_key that names it. Persistence must be set up with bot=.
import discord
from cascadeui import PersistentLayoutView, StatefulButton, card
class TicketDesk(PersistentLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.add_item(
card(
"## Support",
"Click the button to open a ticket.",
discord.ui.ActionRow(
StatefulButton(
label="Open Ticket", custom_id="desk:open", callback=self.open_ticket # (1)!
),
),
)
)
async def open_ticket(self, interaction):
await self.respond(interaction, "Ticket opened.", ephemeral=True)
@bot.hybrid_command()
async def post_desk(ctx):
await TicketDesk(context=ctx, persistence_key=f"desk:{ctx.guild.id}").send() # (2)!
- After a restart, Discord's click finds the button by its
custom_id, so every control needs one. - The key names the panel, one message per key. Sending again under it replaces the panel (Posting Again Under Its Key).
The send writes the panel's row at once: its class, its message and channel, its owner, guild, and session, and the
arguments its constructor got, which must be JSON (Dependencies Through on_bind).
What a Restart Does¶
With bot=, setup_middleware() puts each saved panel back before the bot connects:
- Finds the panel's class by the name its row recorded (Keeping the Class Findable).
- Brings the saved arguments up to the class's
kwargs_schema_versionthrough your kwargs migrators. - Fetches the channel and the message.
- Builds the panel from the saved arguments, gives it the row's owner, guild, and session, and ties it to the
message. A V2 panel nothing has drawn yet is drawn from its
build_ui(), so its buttons answer clicks. - Runs
on_bind(bot), and has discord.py send the message's clicks to the panel, which answers them from here on.
The panel shows what its message showed before the restart until something redraws it. Once the bot is ready,
on_restore(bot) runs on each restored panel, so a redraw there can read the bot's caches.
Its buttons work without one: on_restore changes what the message shows, and no override is needed to draw the
panel.
The default does nothing, and the leaderboard and roles panels redraw. An on_restore that raises is logged at ERROR
and the panel stays up and clickable. To take a panel down there, call exit(). The same restore runs after a
reattach() and when the unreachable sweep finds a panel's message
again, so on_restore can run while the bot is up.
What the Restore Reports¶
Each pass sorts the saved panels into five lists, logs their counts at INFO, and keeps them in
store.persistence_manager.last_reattach_summary:
| List | When | The row |
|---|---|---|
restored |
The panel is back on its message | Kept |
skipped |
No class is registered under the row's name (logged at DEBUG at the start, since a cog may import it later, and at WARNING on a later pass), or no kwargs migrator reaches the class's version (logged at WARNING) | Kept, tried again at the next start |
failed |
The constructor or a kwargs migrator raised (logged at ERROR), or a row for a deleted message could not be deleted | Kept, tried again at the next start |
removed |
Discord answered 404 for the channel or the message | Deleted, and REGISTRY_PRUNED dispatched with reason="gone" and source="reattach" |
unreachable |
The fetch failed another way: 403, a rate limit, a server error, a timeout, or a channel that holds no messages | Kept: the panel may still be there, so do not clean up records from this list |
total_reattach_summary puts every pass in the process together, since a reattach() replaces
last_reattach_summary. reattach_removed_messages maps each removed key to its message and channel, for code
that cleans up after a deleted panel.
Closing a Panel for Good¶
exit() on the panel deletes its row, so it is not restored. When no live panel holds the key (its message was
deleted while the bot was off, or a cleanup task decides), delete the row by key:
from cascadeui import get_store
await get_store().persistence_manager.prune_registry(persistence_keys=["desk:22"])
prune_registry deletes the row whatever holds it. Pruning a key a live panel holds leaves that panel on screen
and logs a WARNING, and the panel is not restored after the next restart. get_active_view(persistence_key=...)
says whether one is live. When both are needed, prune after the exit(), which can hand the row back to an older
panel (Posting Again Under Its Key).
Pruning covers the sweep for rows whose message stays out of reach.
A panel that opens a screen with push() keeps its row through that screen. Closing the screen (its Exit, a
replace(), or the library's own cleanup) closes the panel and deletes the row, and Back returns to the panel. A
screen left idle returns to the panel instead of timing out, unless the screen defines its own on_timeout().
Keeping the Class Findable¶
A row names its class as module.QualName from when the panel was sent. Moving or renaming the class leaves the
old rows unmatched: they are skipped at the next start, and those panels stay up with buttons nothing answers.
Pin the name the rows hold before shipping the move:
class TicketDesk(PersistentLayoutView): # moved from mybot.views to mybot.panels
session_class_key = "mybot.views.TicketDesk" # the name the rows hold
New rows record the pin too, and kwargs migrators are registered under it. Two persistent classes cannot share a
pin (ValueError when the second is defined), and a subclass does not inherit it. A skipped row is not lost: it
comes back at the next start, or at a reattach(), once a class is registered under its name. A reattach() that
still finds no class logs a WARNING naming it.
Who Owns a Panel¶
| Sent with | Owner (user_id) |
Suits |
|---|---|---|
context=ctx or interaction= |
The person who ran the command | A panel that belongs to someone |
context=channel |
None | A board for the whole channel |
Either, plus user_id= |
The id given | A public board that records who posted it |
A persistent panel's owner_only is False, so anyone who can see it can click it. Set owner_only = True for a
panel only its owner may use. A restart restores the owner, the guild, and the session id the panel had.
Dependencies Through on_bind¶
The panel is rebuilt from its saved arguments, so a database pool or a client cannot be one of them: a send with
one logs an ERROR naming it and writes no row, and the panel is not restored. A bot= argument is left out of the
row, so a restore builds the panel without it. Set them in on_bind(bot), which runs at the send before the first
render and at a restore before on_restore:
class TicketDesk(PersistentLayoutView):
async def on_bind(self, bot):
await super().on_bind(bot) # (1)!
self.db = bot.db
async def open_ticket(self, interaction):
number = await self.db.open_ticket(interaction.user.id)
await self.respond(interaction, f"Ticket #{number} opened.", ephemeral=True)
- A pattern sets its own dependencies there. When the library runs the hook,
self.botis already set.
At a send, bot is the interaction's client, the command's bot, or the client the channel belongs to. The hook can
run more than once, so keep it to assigning: at a send it runs before the panel has a message, and at a restore
before on_restore. Code that reads what it sets before send() calls await view.on_bind(bot) first.
Keys inside an argument come back as strings: scores={42: 3} is saved as {"42": 3}, with an ERROR naming the
key.
Posting Again Under Its Key¶
Sending a panel under a key another panel holds replaces that panel: the old one closes by its exit_policy
(frozen by default), and the row moves to the new message. A message left from before a restart is closed the same
way. To post the new panel first and take the old one down only once the new one checks out, set
retire_previous_on_send = False:
from cascadeui import PersistentLayoutView, get_store
class TicketDesk(PersistentLayoutView):
retire_previous_on_send = False
async def repost(key, context):
old = get_store().get_active_view(persistence_key=key) # read before the send
new = TicketDesk(context=context, persistence_key=key)
await new.send()
if not await looks_right(new):
await new.exit(delete_message=True) # the row goes back to the old panel
return
if old is not None:
await old.exit(delete_message=True)
The new panel holds the row from its send. If it exits while the old one is up, the row goes back to the old one,
so a restart restores what is on screen. set_class_attribute("retire_previous_on_send", False) sets the flag for
one panel.
Panels Loaded Later¶
With the cogs loaded before setup_middleware() (Setup), every panel class is known at the start.
A class imported later (a cog loaded or reloaded while the bot runs) is skipped at the start. Call reattach()
once its cog has loaded:
It restores only what is not back yet: a restored panel is not fetched again, and a key a live panel holds is left alone. It returns that pass's five lists and routes the clicks of the cog's dynamic buttons.
Requirements¶
| Rule | Otherwise |
|---|---|
A persistence_key that is a non-empty str, passed to the constructor or set in the class body (the constructor's wins) |
ValueError when missing or empty, TypeError when not a str |
Every control has a custom_id |
send() raises ValueError, whether the control was added in __init__ or in on_load() |
| No timeout | A timeout number in the constructor, the class body, or an assignment raises ValueError. 0 is accepted, and passed to the constructor it reads back as None |
| Not ephemeral | send(ephemeral=True) raises ValueError: an ephemeral message cannot be found again after a restart |
A key set in the class body is the same for every panel of the class, so it suits a panel posted once per bot. A
panel posted in each server takes its key at construction, such as f"desk:{guild_id}": posting a second panel
under the same key closes the first.