Buttons and Selects¶
Buttons and selects are the controls people click and pick from. CascadeUI's versions take their callback as a keyword, check it when the control is built, and follow the view's rules for who may click, double clicks, and keeping the panel in step with what the view holds.
This panel lets someone pick a size and then order:
import discord
from cascadeui import StatefulButton, StatefulLayoutView, StatefulSelect, card
class PizzaView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.size = "Medium"
self.size_select = StatefulSelect(
placeholder="Size",
options=[discord.SelectOption(label=s) for s in ("Small", "Medium", "Large")],
callback=self.pick_size,
)
self.size_select.set_selected(self.size)
self.add_item(card("Pick a size, then order."))
self.add_item(discord.ui.ActionRow(self.size_select)) # (1)!
self.add_item(discord.ui.ActionRow(StatefulButton(label="Order", callback=self.order)))
async def pick_size(self, interaction, values): # (2)!
self.size = values[0]
self.size_select.set_selected(self.size) # (3)!
await self.refresh()
async def order(self, interaction):
await self.respond(interaction, f"Ordered a {self.size} pizza.")
- In a
StatefulLayoutView, buttons and selects go in anActionRow. - A select's callback may take the picked values as a second parameter.
- Marks the pick as the select's choice, so the panel keeps showing it after the redraw.
Buttons¶
StatefulButton takes the same keywords as discord.ui.Button (label, style, emoji, disabled,
row), plus callback. The callback receives the interaction, and may be async def or a plain def.
A button carries no value, so a callback that needs a second argument is refused when the button is built,
with a TypeError that prints the signature it saw. The usual cause is a method passed from the class
instead of the instance (MyView.save where self.save was meant).
In a StatefulLayoutView, wrap buttons in an ActionRow, up to five to a row. In a StatefulView, add
them directly, and row= picks the row. Layout Rules and Limits has the full rules.
Four subclasses set the style for you:
from cascadeui import DangerButton, PrimaryButton, SecondaryButton, SuccessButton
PrimaryButton("Save", callback=self.save)
DangerButton("Delete", callback=self.delete)
Two settings on any button are covered with the views they belong to:
owner_only=Truekeeps one control for the view's owner on a panel open to everyone. See One Control for the Owner Alone.allow_double_click=Trueruns every click, for a button such as a counter. By default a person's second click on a button whose first click is still running is dropped. See Double Clicks.
Link Buttons¶
LinkButton opens a web page. Discord opens it in the person's browser and sends the bot nothing, so it
takes a URL and no callback:
An empty URL raises ValueError. A StatefulButton given style=discord.ButtonStyle.link raises
ValueError too, since a link style needs a URL and sends no click.
Toggle Buttons¶
ToggleButton flips between on and off with each click. Off, it shows its label in grey. On, it shows
toggled_label (the label with a check mark, unless you give one) in green. The click is answered with the
panel, so the new look shows without a refresh():
from cascadeui import ToggleButton
class AlertsView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.notify = True
self.add_item(card("Alerts"))
self.add_item(
discord.ui.ActionRow(
ToggleButton("Notifications", toggled=self.notify, callback=self.set_notify)
)
)
async def set_notify(self, interaction, toggled): # (1)!
self.notify = toggled
toggledis the state after the click. A callback with onlyinteractionworks too, and reads the button'svalue. A reply throughself.respond()goes out after the panel.
toggle_button() draws a green or red on/off button from a
state the view passes in, and toggle_section() puts one beside a
line of text.
Selects¶
StatefulSelect takes the same keywords as discord.ui.Select (options, placeholder, min_values,
max_values, disabled), plus callback. The callback receives the interaction, and the picked values as
a list of strings when it declares a second parameter. Discord's client holds a person to min_values,
so a pick below it never reaches the bot.
Dropdown takes plain dicts for the options. An option without a value uses its label:
from cascadeui import Dropdown
Dropdown(
[
{"label": "Red", "emoji": "\N{LARGE RED CIRCLE}"},
{"label": "Blue", "value": "blue", "description": "The calm one"},
],
placeholder="Team",
callback=self.pick_team,
)
Discord refuses some selects outright, so these raise when the select is built rather than when the message is sent:
- more than 25 options (
ValueError) - two options with the same value (
ValueError) - a dict in a
StatefulSelect's options (TypeError: useDropdown)
A string select whose options marked default outnumber its max_values is refused before the send.
Fewer than min_values is fine. A label made only of spaces, tabs, or line breaks counts as empty,
on an option as on a button, where it leaves a button with no emoji nothing to show. An emoji that is
empty, a plain word, or a custom emoji with an unreadable id raises ValueError when the control is
built: see Emoji.
A select built with no options shows one disabled placeholder option instead, so a list filtered down to nothing still renders.
Showing the Current Choice¶
set_selected() marks which options show as chosen, and get_selected() reads them back:
select.set_selected("blue") # one option
select.set_selected(["red", "blue"]) # several, when max_values allows it
select.set_selected(None) # none
select.get_selected() # always a list, such as ["blue"]
A value that matches no option is ignored, so a saved choice whose option was later removed does not break the redraw.
Keeping a Pick on Screen¶
Discord keeps showing what someone picked until the message is edited. When a pick's callback leaves the click unanswered, CascadeUI answers it with the panel as the view holds it, so the select shows the view's choice rather than the person's.
To keep a pick on screen, draw it: mark the option with set_selected() and call refresh(), as
pick_size does in the first example. A callback that only stores the pick is answered with the select as
it was before the pick: the old choice, or the placeholder.
Refusing a pick therefore takes no code: a callback that returns without drawing the pick puts the select back.
A refusal sent through self.respond() gets the same answer, and its words follow as a separate message.
Role, Channel, User, and Mentionable Selects¶
RoleSelect, ChannelSelect, UserSelect, and MentionableSelect let someone pick from the server's
roles, channels, or members. Their callbacks receive the picked objects rather than strings.
default_values= marks entries as chosen when the panel is sent. It takes ids, the objects themselves, or
discord.SelectDefaultValue. set_default_values() takes the same and replaces the list later (None
clears it):
from cascadeui import MentionableSelect, RoleSelect
RoleSelect(default_values=[moderator_role_id], callback=self.pick_roles)
MentionableSelect(default_values=[guild.owner, moderator_role], callback=self.pick_target) # (1)!
- A mentionable select takes members and roles, so a bare id could be either and raises
TypeError. Pass the object, or adiscord.SelectDefaultValuenaming the type.
Callbacks and Control Values¶
Every control follows one rule: the callback receives the interaction, plus the control's value when the control has one and the callback declares a second parameter.
| Control | Second argument |
|---|---|
StatefulSelect, Dropdown, the role, channel, user, and mentionable selects |
the picked values, if declared |
ToggleButton, toggle_section() |
the state after the click, if declared |
toggle_button(), cycle_button(), choice_row() |
the state or value, always: the callback must take it |
StatefulButton, action_section(), button_row(), confirm_section(), tab_nav() |
none |
A second parameter with a default counts as declared. *args does not, so a *args callback is called
with the interaction alone. A callback that cannot be called the way its control calls it raises
TypeError on the line that builds the control, naming the signature, instead of failing on the first
click.
Passing Context to Callbacks¶
A callback receives only the interaction and the value. For anything else, such as which cell of a board was
clicked, close over it or use functools.partial:
from functools import partial
class BoardView(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.board = [" "] * 3
self.add_item(
discord.ui.ActionRow(
*(StatefulButton(label=str(i + 1), callback=partial(self.mark, i)) for i in range(3))
)
)
async def mark(self, cell, interaction): # (1)!
self.board[cell] = "X"
await self.respond(interaction, f"Marked cell {cell + 1}.")
partialpassescellfirst, so the interaction comes last.
Each button gets its own custom_id, worked out from its callback and the values it carries, so the three
buttons above stay apart. Generated Ids covers how they are made, and when
to set your own.
Less common cases
What a click records. After the callback, each click or pick records a COMPONENT_INTERACTION
action in the store, carrying the control's id and value. A dropped click records nothing. See
Built-in Actions.
Channel selects return partial channels. A ChannelSelect callback receives discord.py's
AppCommandChannel and AppCommandThread, which have no permissions_for(). Their .permissions is
the person's permissions in that channel, not the bot's. Call .resolve(), or await .fetch() when
the cache may miss, before checking what the bot may do there.
Picks the library does not answer with the panel. A pick the view's own owner_only or
allowed_users refuses gets the refusal's words alone, as in discord.py, so the person keeps seeing
their pick until the panel next renders. A reply sent with interaction.response.send_message() takes
the answer itself, with the same result. With serialize_interactions = False a pick is acknowledged
without the panel, and under auto_defer = False a pick on your own select is yours to answer.
Picks answered with the panel before the words. Besides a respond() refusal, the panel goes first
when the control's own owner_only refuses the pick, when a modal the pick opened refuses its input,
and when the callback sends another panel, which then posts as a separate message. The words may come
from the callback, a task it awaits, or the modal's callback.
A reply while the callback is still working. The answer then sends the panel as the pick found it, and runs nothing to build it. A callback part way through changing the panel has its words sent alone, and its own redraw shows the change. A redraw made while that answer is on its way waits for it, so the older panel never lands over the newer one. Past 30 seconds the redraw goes on, with a warning naming the view.
Cost. The answer is the one request the pick needed anyway. A refusal's words then cost one more request.
Related¶
- Responding to Clicks: replies, modals, and the 3-second rule.
- Who Can Click:
owner_only,allowed_users, and refusals. - Choice and Toggle Controls: rows of options, toggles, and tabs built for you.
- Layout Rules and Limits: rows, ids, and Discord's limits.