Dynamic Persistent Buttons¶
A dynamic button keeps what it needs in its own custom_id. When someone clicks it, the library builds a new button
from that id and runs its on_click, so the click works after a restart with no saved row and no panel to restore.
It suits a button that differs from its siblings only by an id: a Close button on each ticket, a button for each
role.
A Button That Carries Its Data¶
import discord
from cascadeui import DynamicPersistentButton
class CloseTicket(
DynamicPersistentButton,
template=r"ticket:close:(?P<channel_id>[0-9]+)", # (1)!
):
def __init__(self, *, channel_id: int): # (2)!
super().__init__(
discord.ui.Button(
label="Close Ticket",
style=discord.ButtonStyle.danger,
custom_id=f"ticket:close:{channel_id}",
)
)
self.channel_id = channel_id
async def on_click(self, interaction):
await self.respond(interaction, f"Closing ticket {self.channel_id}.", ephemeral=True)
- The template is a regular expression that must match the whole
custom_id. Each named group in it becomes a keyword argument to__init__. channel_idcomes in as anint: a group nameduser_id,guild_id,channel_id,role_id, ormessage_idis read as a number, and any other group stays astr.
Add it to a view like any other button, inside an ActionRow on a V2 view. A click needs only the class, not the
view: the button answers for as long as its message shows it enabled, and a view that closes or times out shows it
disabled.
What a Click Does¶
- discord.py tries the click's
custom_idagainst the template of every dynamic button class the bot knows. - For each class whose template matches the whole id,
from_custom_idbuilds a new button from the named groups. on_clickruns on that button. If it has not answered afterauto_defer_delay(a class attribute, 2.5 seconds by default), the library acknowledges the click.
Answer through self.respond() and self.open_modal(), which still work once the click is acknowledged. A bare
interaction.response.send_message() raises InteractionResponded then. The button on_click runs on is not the
one you added, and self.view is a copy of the message's components rather than your panel: to reach the panel,
look it up with get_store().get_active_view(persistence_key=...).
A person's second click, while their first is still running and has shown them nothing, is dropped. Set
allow_double_click = True on the class to run every click. A click also restarts the timeout of a live view on
the same message.
After a Restart¶
A class is registered when it is defined, and the bot learns it at one of these points:
| The class is | Its buttons answer once |
|---|---|
Imported before setup_middleware() |
setup_middleware(PersistenceMiddleware(..., bot=bot)) runs, before the bot connects |
| In a cog loaded later | await get_store().persistence_manager.reattach() runs |
| Used with no persistence set up | bot.add_dynamic_items(CloseTicket) runs in setup_hook |
A start without bot= logs a WARNING naming the classes whose buttons will not answer.
Template Rules¶
| Rule | Otherwise |
|---|---|
The template matches the whole custom_id |
The build raises ValueError |
No other class's template matches the id (the roles panel's buttons use roles:) |
The build raises ValueError naming both classes |
Every named group is a keyword __init__ takes, and every keyword it needs is a group |
TypeError when the class is defined, unless it overrides from_custom_id() |
A group named after an id (user_id, role_id, ...) matches digits only |
A click with letters there fails, and discord.py logs the ValueError |
The custom_id is at most 100 characters |
send() raises ValueError |
Every subclass names its own template= |
TypeError when the class is defined |
A button from_custom_id() builds for a click stands for one already posted, so its id is not checked again. A click
that fails shows "didn't respond in time" to the person who clicked.
Building From the Id Yourself¶
The default from_custom_id calls the class with the named groups. Override it when the groups need more than that,
such as a number that is not an id:
class Vote(
DynamicPersistentButton,
template=r"poll:(?P<poll_id>[0-9]+):(?P<choice>[0-9]+)",
):
def __init__(self, *, poll_id: int, choice: int):
super().__init__(discord.ui.Button(label=f"Option {choice}", custom_id=f"poll:{poll_id}:{choice}"))
self.poll_id, self.choice = poll_id, choice
@classmethod
async def from_custom_id(cls, interaction, item, match, /):
return cls(poll_id=int(match["poll_id"]), choice=int(match["choice"]))
item is the button discord.py found on the message, and match is the template's match. from_custom_id runs
before the library starts timing the click, so a slow lookup there counts against Discord's three seconds with
nothing to acknowledge the click. Do slow work in on_click.
Who Can Click¶
A panel's access rules do not reach a dynamic button on it: with owner_only = True on the panel, anyone who can see
the button can click it. To refuse someone, return False from interaction_check, and the button answers with its
unauthorized_message:
unauthorized_message = "Only staff can close tickets."
async def interaction_check(self, interaction):
return interaction.user.guild_permissions.manage_channels
The default message is "You cannot interact with this.", as on views. None acknowledges the click with no reply, a
check that replies itself gets no second one, and a check that raises is logged at ERROR and the click acknowledged.
For a reply that depends on who clicked, override on_unauthorized(interaction), the button's form of the view
hook of that name. Its default sends unauthorized_message:
async def on_unauthorized(self, interaction):
await self.respond(
interaction, f"Only staff can close ticket {self.channel_id}.", ephemeral=True
)
An override that sends nothing, or raises (logged with its traceback), leaves the click acknowledged.
View or Button¶
| The click needs | Use |
|---|---|
Only what fits in its custom_id |
A dynamic button |
| The panel's state, or to redraw the panel | A control on a persistent panel |
| The panel's access rules | A control on a persistent panel |
The two combine: the help desk in v2_persistence.py is a persistent panel whose topic buttons are dynamic, one class answering every topic.