Wrappers, Emoji, and V1 Composites¶
Three smaller tools. A wrapper adds a behavior to a button you already have: a question before it acts, a cooldown, or a loading state while it works. Every emoji argument in the library takes the same forms discord.py's buttons take. And the V1 composites are prebuilt button groups for V1 views.
This button asks before it empties the inventory, and empties it at most once every 30 seconds:
import discord
from discord.ui import ActionRow
from cascadeui import StatefulButton, StatefulLayoutView, card, with_confirmation, with_cooldown
class Inventory(StatefulLayoutView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.items = ["Sword", "Shield", "Potion"]
self.build_ui()
def build_ui(self):
self.clear_items()
clear = StatefulButton(label="Clear", style=discord.ButtonStyle.danger, callback=self.clear)
with_cooldown(clear, seconds=30) # (1)!
with_confirmation(clear, message="Throw away every item?")
self.add_item(card("## Inventory", ", ".join(self.items) or "Empty.", ActionRow(clear)))
async def clear(self, interaction):
self.items.clear()
self.build_ui()
await self.refresh()
await self.respond(interaction, "Inventory cleared.", ephemeral=True)
- Added first, the cooldown sits inside the question. A click inside the 30 seconds is told how long to wait and gets no question, and the 30 seconds start at Yes, so a No leaves the button free.
Adding a Behavior to a Button¶
A wrapper takes a button, puts its own step in front of the button's callback, and returns the button. Wrap a button where you build it. A view that rebuilds its buttons on every redraw wraps each new one, and a wrapper applied twice to the same button acts once.
A click the button itself refuses (its owner_only, for one) gets only the refusal: no question, no
cooldown, no loading state.
Asking First¶
with_confirmation(button, ...) answers a click with a private prompt, an embed titled title with
message under it, and Yes and No buttons. Yes changes the prompt to confirmed_message and runs the
button's callback with the Yes click. No changes it to cancelled_message and calls on_cancel, when
given, with the No click. The prompt takes one answer, and its buttons are disabled once timeout seconds
(60 by default) pass unanswered.
The prompt stays open while the panel goes on, so Yes takes its turn like a click on the panel: one sent while
another click is still running waits for it. Yes on a panel that has closed in the meantime runs nothing, and the
prompt shows the panel's session_ended_message. One that moved to
another screen (a push) has not ended its session, so the prompt only loses its buttons. No changes the prompt at
once, and its on_cancel waits its turn the same way; on a closed panel it still runs, since the cleanup it does may
be owed.
The callback receives the Yes click, which has already been answered by the change to the prompt, so a
self.respond() in it replies as a follow-up, and a self.refresh() edits the panel.
confirm_label, cancel_label, confirm_style, cancel_style, and color change the prompt's look. A link
or premium style is refused, since those buttons send the bot no click.
A Cooldown¶
with_cooldown(button, seconds=5, message=None, scope="user", key=None) lets a person use the button once
per seconds. A click inside the cooldown is answered privately with message, whose {remaining} is the
time left rounded up to a tenth of a second, so it never reads shorter than the real wait: 2.41 seconds
left reads 2.5. Without message the answer is "This action is on cooldown. Try again in {remaining}
seconds."
scope says who shares a cooldown:
"user", the default: each person has their own"guild": everyone in a server shares one"user_guild": each person has one in each server"global": everyone shares one
The cooldown is kept on the view, so a button rebuilt by the next redraw keeps it. A new copy of the view,
including one pop() rebuilds, starts without one. It is named after the button's custom_id when you
gave one, else after your callback (other wrappers on the button do not change it), and buttons with the
same name share it: give buttons a loop builds around one callback their own custom_id= or key=. When buttons with different callbacks share a
name, the first click the cooldown turns away logs a warning naming the fix.
refresh_cooldown_ms looks like a cooldown and is not one: it paces a view's redraws and lets the edit a
click asks for through. See
Pacing a Panel vs. Guarding a Button.
Showing That It Is Working¶
with_loading_state(button, loading_label="Loading...", loading_emoji=None) disables the button and shows
loading_label while the callback runs, then puts both back, whether the callback returns or raises. Use it
on a button whose work takes seconds.
On a CascadeUI view the loading state and the restore are two edits of the message, and the click's answer
is left to the callback, so respond() and open_modal() work as they do without the wrapper. An edit the
callback makes while it runs still shows the loading label, and the restore follows it.
Stacking Wrappers¶
The wrapper added last runs first. For a question and a cooldown the order decides one thing, when the cooldown starts:
| Added first | The cooldown starts | A No |
|---|---|---|
with_cooldown(), as in the opener |
At a Yes | Leaves the button free |
with_confirmation() |
At the click | Spends the cooldown |
Either way a click inside the cooldown is told how long to wait and gets no question. A question checks
a cooldown added before it at the click and again at Yes: a Yes on a second prompt left open, once the
first prompt's Yes started the cooldown, changes that prompt to the wait notice instead of
confirmed_message. A with_loading_state() added after a cooldown shows no loading state for a click
the cooldown turns away.
Emoji¶
Every emoji= or *_emoji= argument and every *_emoji class attribute takes what discord.py's buttons
take (the EmojiInput type): a string, a discord.Emoji, or a discord.PartialEmoji. So does each option's
emoji:
Choice(emoji=) in choice_row() (the {label: value} form has no place for one), RowButton(emoji=) in
button_row() and tab_nav(), the "emoji" key of a select option or a menu category, and a roles
panel's format_button_emoji(). A leaderboard's podium_emojis and a role category's icon are text.
| Form | Written as |
|---|---|
| A standard emoji | "🔥", or "\N{FIRE}" in Python |
| A custom emoji | "<:fire:1234567890123456789>" |
| An animated custom emoji | "<a:dance:1234567890123456789>" |
- In an
emoji=argument discord.py also reads":fire:1234567890123456789"and"fire:1234567890123456789"as the same custom emoji. In text (a card, an embed, a leaderboard'spodium_emojis, a role category'sicon) Discord draws a custom emoji written with or without its angle brackets. - discord.py reads the id only when it has 13 to 20 digits (a real one has 17 to 19). With a shorter one,
the whole string is sent as the emoji's name, and no emoji has a name like
<:fire:12345>. - Discord refuses a button or a select option (HTTP 400, "Invalid emoji") whose emoji is empty, a plain
word such as
"fire", or a custom emoji with an id discord.py cannot read. The library refuses those three where they are written: the button, option, builder call, or class attribute raisesValueErrornaming the component. A raw discord.py button or option is refused before the send. - A
discord.Emojifrombot.get_emoji()works as it is, andstr(emoji)gives the bracketed form for text. - A button shows a standard emoji or a custom emoji the bot can use. A symbol that some fonts draw is not
always an emoji:
"↻"is a symbol,"🔄"an emoji. A symbol that is not an emoji, and a custom emoji whose id names no emoji, are left for Discord to refuse.
Emoji the Bot Owns¶
A bot can use custom emoji from the servers it is in, and its application's own emoji everywhere. An emoji uploaded to the application keeps working in every server and does not depend on the bot staying in another one. Upload it once with discord.py, and keep its id:
@bot.event
async def on_ready():
with open("fire.png", "rb") as image:
emoji = await bot.create_application_emoji(name="fire", image=image.read())
print(emoji, emoji.id)
Then use the printed form in any emoji slot. bot.fetch_application_emojis() lists the application's emoji,
and bot.fetch_application_emoji(emoji_id) fetches one.
V1 Composites¶
Three button groups and a progress bar for V1 views (StatefulView), each with a V2 counterpart:
| V1 | What it is | On a V2 view |
|---|---|---|
ConfirmationButtons(on_confirm, on_cancel) |
A Yes and a No button | confirm_section() |
PaginationControls(page_count, on_page_change=...) |
Previous, a page label, Next | PaginatedRegion |
ToggleGroup(options, on_select=...) |
One highlighted option of several | choice_row() |
ProgressBar(total=100, width=20) |
Text, not a component: bar.render(40) |
progress_bar() |
add_to_view(view, row=None) adds a group's buttons to the view, all on row when one is given:
from cascadeui import ConfirmationButtons, StatefulView
class Delete(StatefulView):
def __init__(self, **kwargs):
super().__init__(**kwargs)
ConfirmationButtons(on_confirm=self.delete, on_cancel=self.keep).add_to_view(self, row=1)
async def delete(self, interaction):
await self.respond(interaction, "Deleted.")
await self.exit()
async def keep(self, interaction):
await self.exit()
ConfirmationButtonstakes one answer: once one button's callback runs, a click on either sent before it finishes is dropped.PaginationControlscallson_page_change(interaction, page), page counting from 0, and the callback draws the page. When it raises, the controls go back to the page they left.ToggleGrouphighlights the option clicked, redraws the view, and then callson_select(interaction, value).ProgressBar.render(current)returns the bar and a percentage, such as████░░░░░░ 40%, for an embed field or a description, rounded asprogress_bar()rounds it.
On a V2 view a send refuses their buttons, since a V2 button must sit in an action row. Use the counterparts there.
Less common cases
A wrapper on a plain discord.py view. The loading state answers the click itself, so the callback
finds the interaction answered: reply through interaction.followup.send(). A reply through
interaction.response raises a RuntimeError naming that fix.
V1 composites on a panel that survives a restart. ConfirmationButtons and PaginationControls
take custom_id= as the base of their buttons' ids ({custom_id}_confirm, {custom_id}_prev, and so
on), and ToggleGroup builds its ids from key= and each option. Rebuilt after a restart,
PaginationControls starts from its current_page while the message shows the page it was on. Keep
the page where __init__ can read it, or redraw in on_restore().
Building your own group. CompositeComponent is the base the three button groups share: add_component() collects
components and add_to_view() adds them. register_component(name, cls) and get_component(name)
keep classes under a name.
Refused when built. Each of these raises at the call that passed it:
with_cooldown: ascopeoutside the four, asecondsthat is negative or not a number, or amessagethat is not text or that{remaining}cannot fill (another placeholder, or a format such as{remaining:.0f}).with_confirmation: a negativetimeoutor one that is neither a number norNone, a style that is not adiscord.ButtonStyleor is a link or premium style, or anon_cancelthat cannot take(interaction).ConfirmationButtonsandPaginationControls: acustom_idthat is not text or leaves the suffixed ids past 100 characters, a callback that cannot take(interaction)or(interaction, page), or apage_countorcurrent_pagethat is not a whole number.ToggleGroup:optionsthat is empty or not a list of text, adefaultnot among them, an id ({key}_{option}) past 100 characters, or anon_selectthat cannot take(interaction, value).ProgressBar: atotalthat is not a number, awidththat is not a whole number above 0, or afill_charorempty_charthat is not text.
Related¶
- Buttons and Selects:
owner_onlyon a button, and the callbacks wrappers sit in front of. - Choice and Toggle Controls: the V2 controls for picking and toggling.
- Pacing a Panel vs. Guarding a Button.
- Wrappers and composites in the API reference: every parameter.