API: Patterns¶
Prebuilt views for the panels most bots need. Patterns teaches them. Each one is a view, so everything on Views applies, and each comes as a V2 class beside a V1 class of the same shape (the leaderboard and the role panel are V2 only).
Every hook and callback on this page may be a plain def or an
async def, except one its entry asks to be synchronous and the hooks a pattern calls while it builds or draws,
listed in Sync or Async, Your Choice. An async def one of those raises
TypeError when its class is defined.
| Pattern | V2 | V1 |
|---|---|---|
| Menu | MenuLayoutView |
MenuView |
| Form | FormLayoutView, with FormField and FormSchema |
FormView |
| Wizard | WizardLayoutView, with WizardStep and WizardSchema |
WizardView |
| Tabs | TabLayoutView |
TabView |
| Paginated | PaginatedLayoutView |
PaginatedView |
| Leaderboard | LeaderboardLayoutView, PersistentLeaderboardLayoutView |
|
| Roles | RolesLayoutView, PersistentRolesLayoutView, with RoleCategory |
What Every Pattern Has¶
A pattern's constructor takes the view keywords (interaction=, context=, user_id=, and the rest on
StatefulLayoutView) beside its own. It draws its own first screen, so await
view.send() is the whole call (Sending One).
A V2 pattern builds in its on_load(), and an override that never calls super().on_load()
still has the pattern's load run after it, so what the override loaded shows from the first message. A menu and a
form also draw when they are built: their load draws again and keeps the new draw only when it shows something
different, otherwise keeping any item the override added. A V1 pattern builds its embed when it is sent, and its
nav_rebuild draws the same embed when navigation returns to it. Most V1 entries below
point at their V2 sibling and list only what differs.
State Changes and Back¶
Each pattern's on_state_changed(state) redraws what it shows, and its
get_nav_state() carries its place across a pop(), which
restore_nav_state() puts back:
| Pattern | A state change the view receives | What comes back on pop() |
|---|---|---|
| Menu | builds the menu again (build_ui()) |
nothing: the menu has no place to keep |
| Form | draws the form again | values and anything typed that has not parsed yet, for fields the form still has. Errors are cleared |
| Wizard | builds the current step again, no on_step_entered |
the current step and answers, answers first so a step's condition reads them |
| Tabs | builds the open tab again, no on_tab_switched |
the open tab, kept inside the tab count |
| Paginated | draws the current page again | current_page, kept inside the page count |
| Leaderboard | rebuild_pages(), then the page |
as Paginated |
| Roles | (the panel holds no state of its own) | nothing |
An override that adds to either nav hook calls super(). Anything else kept on the instance starts over, since
pop() builds the view again from its class.
build_extra_items() (override)¶
Adds custom controls beside the pattern's. Form, Wizard, Tabs, Paginated, Leaderboard, and the V1 menu take it (Controls of Your Own):
- Form, Wizard, Tabs, Paginated, and Leaderboard call it once, when the view is built, and keep what it adds
through every redraw. A click on a
CollapsibleorPaginatedRegionit drew runs the hook again, so the click shows - The V1 menu calls it on every
build_ui(), so it builds its items fresh each time - On a V1 view the items share the five rows the pattern leaves free. A V1 paginator's row 0 holds its buttons,
and an item given no
rowjoins the first row with room - Items with no room raise
ValueErrornamingbuild_extra_items()and what they sit beside, with what each row holds (V1) or how many of Discord's 40 components each part takes (V2), on the hook's own run or when a page, tab, or step change puts them back. APaginatedLayoutViewsizes every page it is given beside its buttons and these items, when built and inrefresh_data()
The V2 menu has build_header() and build_footer() instead, and Roles has
neither.
auto_exit_button (class attribute)¶
Adds the library's Exit button and keeps it through every redraw. True on a menu, False on the other
patterns.
The button's id is fixed (menu_exit, form_exit, wizard_exit, tab_exit, paginated_exit), so it keeps
working after a restart on a persistent panel. On a V1 view other than the form it takes a slot on row 4 (a
FormView gives it the next free row), and a row 4 that
build_extra_items() already filled raises ValueError naming the attribute.
An instance override set with set_class_attribute() takes effect at the next
render. On a paginator, and on a V1 tab view or wizard, the call itself raises when the view has no room for the
button: a page given to a PaginatedLayoutView, or row 4 of a V1 view. A leaderboard, a menu, and a V2 tab view or
wizard draw their content when they render, and the render refuses it.
Renamed Hooks¶
Seven hooks have public names. A class that still overrides the old name keeps working, called through the new
one, and gets a DeprecationWarning when it is defined. The old names go in 5.0.0
(Stability Policy):
| Old name | New name |
|---|---|
_build_extra_items() |
build_extra_items() |
_build_category_item() |
build_category_item() (V2 menu) |
_build_category_button() |
build_category_button() (V1 menu) |
_build_category_card() |
build_menu_card() (V2 menu) |
_build_tab_rows() |
build_tab_rows() |
_build_progress_header() |
build_progress_header() |
_extract_page() |
page_kwargs() (V1 paginator) |
Menu¶
MenuLayoutView(*args, categories=None, **kwargs)¶
A hub of buttons, each opening another view with push(). Menu teaches it.
categories(list of dict, or any iterable of them, read once): one dict per button. A menu built with none raisesTypeError, and one given an empty listValueError. Acategoriesset in the class body is not read: one built that way raisesTypeErrorsaying to pass it when the view is built
| Key | Meaning |
|---|---|
"label" |
The button's text. Required |
"view" |
The view class the button opens. Required |
"description" |
Text beside the button. Without it the label shows as the text |
"emoji" |
An emoji on the button |
"style" |
The button's style, over menu_style |
"rebuild" |
Passed to push(rebuild=), called with the view the push builds |
Raises TypeError at construction for a "view" of the other component version (see
Between the Two Kinds of View),
and for one that is not a view class: every click builds a new view from it, so pass the class, not an instance.
A key one letter off one of these ("descripton") raises TypeError naming the key it means. Any other key is
kept as the caller's own.
A "rebuild" that is not callable or cannot take the view raises TypeError there too.
| Attribute | Default | Meaning |
|---|---|---|
menu_style |
ButtonStyle.primary |
Every category button's style |
auto_exit_button |
True |
The Exit button, below the card |
categories reads back the list the menu was built with. build_ui() draws the menu (header, card, footer) and
runs again on each state change. A push draws the new screen with the category's "rebuild", else the
screen's own nav_rebuild, else its build_ui()
(What a Screen Shows).
build_header() (override)¶
Returns what goes above the card: a V2 component, a list of them, or text, which shows as a TextDisplay. The
default returns []. Anything else raises TypeError naming the hook.
build_footer() (override)¶
What goes below the card, on the same terms as build_header().
build_category_item(category, index) (override)¶
Builds one category's entry in the card. The default is an action_section() with the category's text and its
button.
build_menu_card(items) (override)¶
Wraps the entries in one card. The default is a card() in the theme's color. Override it to change the color
or the structure.
on_category_selected(category, index, interaction) (async, override)¶
Runs before the push. Return False to keep the menu on screen and open nothing: reply through
self.respond(interaction, ...) to say why, or the click is acknowledged with no message. Any other return opens
the category, and the default returns None.
MenuView(*args, categories=None, **kwargs)¶
The V1 menu: each category is a StatefulButton, five to a row, with the same keys ("description" is not
shown), menu_style, auto_exit_button, on_category_selected(), and checks as MenuLayoutView. A V1 message
holds 25 buttons, the Exit button included, so more than 25 categories (24 with Exit) raise ValueError when the
menu is built.
build_embed()(override): the hub's embed, a list of embeds, orNonefor none. The default is an embed titled "Menu". Any other return raisesTypeErrornaming the hookbuild_category_button(category, index)(override): builds one category's buttonbuild_extra_items()(override): called on everybuild_ui(), after the category buttons- A push draws the new screen with the category's
"rebuild", else the screen's ownnav_rebuild, else the embed itsbuild_embed()returns
Form¶
FormLayoutView(*args, title="Form", fields=None, schema=None, **kwargs)¶
Fields a person fills in, then Submit. Form teaches it.
title(str): the heading above the fieldsfields(list of dict orFormField): the fields, in order (Fields)schema(FormSchema): the fields fromget_fields()instead
A field dict takes the keys FormField names. The form is one card: the title, then each group of fields under
its heading. A group's text, integer, float, and date fields show their answers beside an Edit button,
which opens a modal of that group's fields. Discord takes five inputs in a modal, so a group's sixth typed field
raises ValueError.
A select with five options or fewer, none with a description, is a row of buttons with the pick highlighted.
A longer one and a multi_select are dropdowns, as is every select when the buttons would take more than a
message's 40 components. A boolean is an On/Off toggle. An answer past 100 characters shows its start and an
ellipsis, and values keeps it whole.
A form past 40 components even with dropdowns draws a denser card: each dropdown under its label (named in its
group's answers instead when the labels do not fit), each boolean as one button showing its answer, three to
a row, and each group's Edit button beside Submit.
Raises at construction, so nothing a form would store or show wrong reaches a click:
ValueErrorfor two fields with oneid, or two options of one field with onevalueValueErrorfor a field whose control would share itscustom_idwith another control (aselectnamedsubmitbeside the Submit button) or pass Discord's 100 charactersValueErrorfor a form that passes 40 components even in its densest card, naming the form, raised too by aset_class_attribute()that would push it there, before the setting landsTypeErrorfor a select option with no textlabel, or avaluethat is not text (ValueErrorwhen empty)TypeErrorfor adefaultabooleanfield cannot hold,ValueErrorfor any other field'sTypeErrorfor a field key a letter or two off one the form reads ("requried"), or an option key a letter or two offlabel,value, ordescription("valeu"). Other custom keys are kept- whatever the modal's inputs refuse, such as a
placeholderover 100 characters
A default is stored as typed input is ("7" becomes 7 on an integer field), and a multi_select default of
one value becomes a one-item list.
Read values (each field's id to its answer), fields (the field dicts), and title. A field's validators run
when the modal is submitted and again at Submit (Checking Answers).
| Attribute | Default | Meaning |
|---|---|---|
text_edit_button_label |
None |
The Edit button's text, and the modal's title. None reads "Edit" on the button, and the modal takes the group's name, else "Edit {label}" for one field, "Edit Text Fields" when every field is text, else "Edit Fields" (with fields_in_modal, the form's title when it fits). FormView's button reads the modal's title, and "Edit" with fields_in_modal. Empty or over 45 characters raises ValueError when the class is defined or set_class_attribute() sets it |
text_edit_button_emoji |
"✏️" |
The Edit button's emoji. None shows none |
text_edit_button_style |
ButtonStyle.secondary |
The Edit button's style |
text_edit_modal_auto_defer_delay |
2.5 |
Seconds before the library acknowledges a submission of the modal, as auto_defer_delay does for a click. Raise it for a slow validator, below 3.0 |
fields_in_modal |
False |
Every field is answered in the modal: the card lists the answers with one Edit and one Submit button, and the modal holds a text box per typed field, a radio group per select of 2 to 10 options (a dropdown otherwise), a checkbox group per multi_select of up to 10 (a dropdown past that), and a Yes/No choice per boolean, which an optional one may leave blank. A form with more than five fields, a field label over 45 characters, two fields sharing a label, or a select with no options or more than 25 raises ValueError at construction or when set_class_attribute() turns it on (Answers in the Modal) |
auto_exit_button |
False |
The Exit button, beside Submit (on a row of its own on FormView) |
set_form_error(message) (async)¶
Shows message under the form's title, inside its card, and redraws. None clears it. An error set in
on_submit() keeps the form open, an empty message included.
set_field_error(field_id, *messages) (async)¶
Shows the messages under one field and redraws. No messages clear the field's errors. Raises ValueError for an
id the form does not have, and TypeError for a message that is not a str, before anything is stored.
on_submit(interaction, values) (async, override)¶
Runs when Submit finds no errors. values maps each field's id to its answer. The default replies "Submitted."
with the answers as the form shows them (a secret field's as dots), cut to Discord's 2000 characters. When it
returns, the form closes by its exit_policy, unless it set an error or already closed or navigated
(When Submit Passes).
on_field_changed(field_name, old, new) (async, override)¶
Runs when a pick, a toggle (Yes or No on FormView), or the modal changes a field's answer, after values holds the new one and
before the form redraws, so a change it makes to values shows in that render. A submission that changes
nothing does not call it. An exception it raises is logged, and the form redraws anyway.
FormView(*args, title="Form", fields=None, schema=None, **kwargs)¶
The V1 form, with the same fields, attributes, methods, and hooks as FormLayoutView. The form is one embed, and
each select (a dropdown) and boolean field (a Yes and a No button) takes one of the message's five rows. The
Edit and Submit buttons take the rows after them and share the last row once all five are used, which a boolean
row has room for and a select row does not.
A field or button that does not fit raises ValueError at construction, naming it, as does a
set_class_attribute() that would leave one, or a build_extra_items() item, without a row, before the setting
lands. Its one Edit button opens every typed field, so a sixth in the form raises too.
FormField(id, label, type="text", required=False, default=None, placeholder=None, min_length=None, max_length=None, min_value=None, max_value=None, options=None, max_values=None, validators=None, style=None, group=None, secret=False)¶
One field, as a dataclass (Fields):
id(str): the key invalueslabel(str): the text the person seestype(str):"text","integer","float","date","boolean","select", or"multi_select"required(bool): Submit refuses an empty answerdefault: the starting answerplaceholder(str): grey text in an empty inputmin_length,max_length(int): the length a text answer may bemin_value,max_value(float): the range a number may beoptions(list of dict): a select's choices, each{"label": ..., "value": ...}max_values(int): how many amulti_selectmay pickvalidators(list): validators run on the answerstyle(discord.TextStyle):shortorparagraph, for a text inputgroup(str): fields with the same group show together under that heading (Groups)secret(bool): shows the answer as dots in the form and in the default Submit reply. The person still sees what they type: Discord's modal has no hidden input
to_dict() returns the dict the form reads, keys whose value is None left out.
FormSchema()¶
A form's fields declared once. Subclass it, return the FormField list from get_fields(), and pass an instance
as schema=.
Wizard¶
WizardLayoutView(*args, steps=None, schema=None, **kwargs)¶
Steps one after another, with Back and Next, and Finish on the last. Wizard teaches it.
steps(list of dict orWizardStep, or any iterable of them, read once): the steps, in order (Steps)schema(WizardSchema): the steps fromget_steps()instead
A step dict takes "name", "builder", and optionally "validator" and "condition", as WizardStep names
them. Raises at construction:
TypeErrorfor no steps (ValueErrorfor an empty list), or steps that are text, a number, or a mapping. Astepsorschemaset in the class body is not read, and raises the same wayTypeErrorfor a step key a letter or two off one the wizard reads ("validate"). Other custom keys are keptTypeErrornaming the step for abuilderorvalidatorthat cannot be called with no arguments, an asynccondition, or one that cannot take the view
The wizard opens on the first step whose condition passes. answers is a dict for what the steps collect,
empty at first, or the dict the subclass set before super().__init__(). It and the current step travel across
pop() (Keeping Answers).
current_step(int): the index of the step on screen, counting steps a condition hides. Read-onlystep_count(int): how many steps the wizard has, hidden ones included
| Attribute | Default | Meaning |
|---|---|---|
back_button_label, next_button_label, finish_button_label |
None |
The buttons' text. None reads "Back", "Next", "Finish", and "" beside the button's emoji shows the emoji alone. Over 80 characters raises ValueError when the class is defined or set_class_attribute() sets it |
back_button_emoji, next_button_emoji, finish_button_emoji |
None |
An emoji on each |
back_button_style |
ButtonStyle.secondary |
Back's style |
next_button_style |
ButtonStyle.primary |
Next's style |
finish_button_style |
ButtonStyle.success |
Finish's style |
step_indicator_label |
None |
A (current, total) -> str for the counter, which reads Step 2/5 without it |
validation_failed_message |
"Finish this step first." |
What the default on_validation_failed() sends for a refusal with no message. None sends nothing |
show_progress_bar |
True |
V2 only. Shows build_progress_header() at the top of the step's card |
nav_inside_container |
False |
V2 only. Puts Back, the counter, and Next inside the step's card, below its content. A step that cannot join the card, or a step card marked as a spoiler, keeps them on a row of their own |
nav_divider |
False |
V2 only. With nav_inside_container, a divider above the buttons |
auto_exit_button |
False |
The Exit button, below Back and Next (beside them on V1) |
Back is disabled with no visible step behind it. The counter counts the steps a condition shows.
A step_indicator_label may be a staticmethod, a method taking self first, or anything the instance reads as
(current, total) (a classmethod, another object's bound method). Raises TypeError when the class is defined
for:
- a string
- a function that cannot take
selffirst - a
functools.partial(wrap it instaticmethod()) - an
async def
set_class_attribute() takes a plain (current, total) callable, which the instance calls as it is.
refresh_content() (async)¶
Builds the current step again in place, after a callback changed what its builder reads
(Redrawing a Step). A redraw made while a reload() runs waits for it.
on_step_entered(step_index) (async, override)¶
Runs when Back or Next moves to step_index, before its builder runs, so data it sets up reaches the build. When
the step's render does not land, the wizard stays on the step it showed and neither hook is called again, so data
prepared here is best keyed by step. An exception it raises is logged and the move goes on.
on_step_exited(step_index) (async, override)¶
Runs before the wizard leaves step_index, while current_step still names it, to commit what the step
collected. An exception it raises is logged and the move goes on.
on_validation_failed(step_index, error, interaction=None) (async, override)¶
Runs when a step's validator refuses it. error is the validator's message, or None for a bare False. The
default sends error, else validation_failed_message, as a private reply. With neither, the click is
acknowledged and nothing is sent.
interaction is None for a check made outside a Next click. An exception it raises is logged, and the step
stays.
on_finish(interaction) (async, override)¶
Runs when Finish is clicked and the last step's validator passes. The default closes the wizard. Override it to save the answers, reply, or open another screen (When Finish Is Clicked). The library acknowledges a click it leaves unanswered.
Of the Finish clicks sent before it returns, only the first runs it, so a double-click does not run an override
that leaves the wizard open twice. A Finish the validator refused does not count, so one sent after fixing the
input runs. A button whose meaning changed after it was drawn, because a step's condition changed, does not run:
a Next that would now finish, a Finish that would now go on, or a Back with no step behind it. The step is drawn
again so the buttons show what they do.
build_progress_header(visible_indices) (override)¶
V2 only. Builds the header at the top of the step's card while show_progress_bar is True and more than one
step is counted.
visible_indices holds the steps the person moves through, the one on screen included. The default is a card() with the step's name as
a heading above a progress_bar over those steps (the bar alone when the name is not text).
Return a component, a list of them, or text to replace it, or None for no header on that render
(Progress Header). Anything else raises TypeError naming the
hook. A header of one card joins the step's content below a divider, when the step returns one plain card or
components with no card. Any other header or step keeps its own place, and so does a header built with
discord.ui.Container or given a color, spoiler, or id above a step card, or any header above a step card
marked as a spoiler.
WizardView(*args, steps=None, schema=None, **kwargs)¶
The V1 wizard, with the same steps, attributes, hooks, and checks as WizardLayoutView, less the progress
header. A builder returns the step's embed, a list of embeds, or None. Any other return raises TypeError
naming the step.
WizardStep(name, builder, validator=None, condition=None)¶
One step, as a dataclass (Steps):
name(str): the step's name, the progress header's headingbuilder: called with no arguments, returns the step's content. On V2: one component, a list, tuple, or generator of them, text (shown as acard(), or as aTextDisplayinside a list), orNonevalidator: called with no arguments when Next or Finish is clicked, returns(valid, error).Noneis no validator. A bareboolis read as the answer it is, and a refusal with no message sendsvalidation_failed_message. Any other shape raisesTypeErrornaming the step: a two-character string or a two-key dict would unpack and passcondition: called with the view, synchronously, returns whether the step shows (Steps That Come and Go)
to_dict() returns the dict the wizard reads.
WizardSchema()¶
A wizard's steps declared once. Subclass it, return the WizardStep list from get_steps(), and pass an
instance as schema=.
Tabs¶
TabLayoutView(*args, tabs=None, **kwargs)¶
A row of tab buttons above the open tab's content. Tabs teaches it.
tabs: a{name: builder}mapping or(name, builder)pairs. A tab's name is its button's label, and its builder, called with no arguments, returns the tab's content: one V2 component, a list, tuple, or generator of them, text (shown as acard(), or as aTextDisplayinside a list), orNone
The first tab opens on send. The view keeps its own copy of tabs. Raises at construction:
TypeErrorfor anything else astabs, text and0included, and for no tabs (ValueErrorfor an empty mapping). Atabsset in the class body is not read, and raises the same wayValueErrorfor pairs that repeat a name, and a name that is empty,None, or over 80 charactersTypeErrornaming the tab for a builder that cannot be called with no arguments
| Attribute | Default | Meaning |
|---|---|---|
active_tab_style |
ButtonStyle.primary |
The open tab's button |
inactive_tab_style |
ButtonStyle.secondary |
The other tabs' buttons |
tab_overflow_policy |
"fill" |
How tabs past five a row split into rows: "fill", "balance", "pin_first", "pin_last", or a tuple of row widths (Many Tabs) |
auto_exit_button |
False |
The Exit button, kept through every switch |
active_tab¶
The name of the tab on screen. Read-only.
switch_tab(name, *, notify=True) (async)¶
Opens the tab named name and redraws. notify=False skips on_tab_switched, for a switch the view makes on its
own. Naming the tab already open draws it again and calls no hook. Raises ValueError for a name the view does
not have.
refresh_content() (async)¶
Builds the open tab again in place, after a callback changed what its builder reads (Redrawing a Tab).
on_tab_switched(index) (async, override)¶
Runs when a switch opens another tab, before the redraw, with active_tab already naming it, for analytics or
setup the tab's builder reads. It cannot stop the switch: an exception it raises is logged and the tab opens. A
click on the open tab, or switch_tab() naming it, draws the tab again without calling it. When the redraw does
not land, the view stays on the tab it showed and the hook is not called again, so data set up here is best keyed
by tab.
build_tab_rows(buttons) (override)¶
Splits the tab buttons into rows, returning a list of lists, one per row. The default applies
tab_overflow_policy.
Override it for a layout the presets do not give (Laying Out the Rows Yourself). The return is checked when the view is built, and one that breaks a rule raises naming the hook and the row or tab:
- at most five of the given buttons in a row
- every button once
- no empty V2 row
- at most five V1 rows
TabView(*args, tabs=None, **kwargs)¶
The V1 tab view, with the same tabs, attributes, methods, and hooks as TabLayoutView. A builder returns the
tab's embed, a list of embeds, or None. Any other return raises TypeError naming the tab.
The tab rows set each button's row, and share the message's five rows with what build_extra_items() adds.
More than 25 tabs under "fill" or "balance", or more than 21 under "pin_first" or "pin_last", raise
ValueError at construction naming the count, and a set_class_attribute("tab_overflow_policy", ...) those
rows cannot hold raises ValueError and keeps the previous layout.
Paginated¶
PaginatedLayoutView(*args, pages=None, **kwargs)¶
Pages with buttons to move between them. Paginated teaches it.
pages(sequence): one entry per page. A page is text (shown as acard()in the theme's accent color), a component, or a list or tuple of components, text among them shown as aTextDisplay. It may also be a synchronous callable returning one of those, called with no arguments each time the page is drawn
Raises at construction:
TypeErrorforpagesgiven as a str, a mapping, or an iterable that cannot be indexedTypeErrorfor a page of another kind, naming its place inpages: a dict, a number, a generator, a list holding something that is not a component, or a callable that isasyncor cannot be called with no argumentsValueErrorfor text past the 4000 characters one text display holds, as a page or as an entry in a page's list, naming its place
A callable that returns None, or text past that cap, raises when its page is drawn.
With no pages the view shows a "No pages." card.
Load data that must be awaited with from_cursor() or in on_load().
Read pages and current_page (the page shown, from 0). Setting current_page does not redraw: use
set_page().
| Attribute | Default | Meaning |
|---|---|---|
{first,prev,next,last}_button_label |
"⏮", "◀", "▶", "⏭" |
The arrows' text |
{first,prev,next,last}_button_emoji |
None |
An emoji on each arrow. One with an emoji and no label of its own shows the emoji alone |
{first,prev,next,last}_button_style |
ButtonStyle.secondary |
Each arrow's style |
indicator_button_label |
None |
Fixed text for the indicator, over the format |
indicator_button_format |
None |
A template for the indicator, {page} and {total} counting from 1. It reads Page 3/12 without one. A template that cannot fill in raises ValueError when the class is defined |
indicator_button_emoji |
None |
An emoji on the go-to button |
indicator_button_style |
ButtonStyle.primary |
The go-to button's style |
jump_threshold |
5 |
The page count from which first, last, and go-to-page appear. None never shows them. set_class_attribute() raises ValueError when a page given, or a V1 view's row 0, has no room for the two extra buttons |
auto_exit_button |
False |
The Exit button, kept on every page |
Below jump_threshold the indicator is a greyed button, always secondary with no emoji. Its text still follows
the label and format (Customizing).
nav_inside_container (class attribute)¶
True puts the page and its buttons in one card. Default False.
A page that is one card keeps its color and id in the new card (a fresh one, since Discord does not take a card inside a
card). A page that mixes a card with other items, a card of a Container subclass, or a card marked as a spoiler (which would
hide the buttons) keeps its own layout with the buttons below, as does a page that fits 40 components only
beside its buttons. A view of one page has no buttons, so the setting changes nothing there (One
Card).
nav_divider (class attribute)¶
True draws a line between the page and the buttons inside the card. Default False. No effect without
nav_inside_container.
from_data(items, per_page, formatter, **kwargs) (async, classmethod)¶
Builds a paginator by cutting items into pages of per_page and passing each slice to formatter, which
returns the page in any shape a page takes (From a List).
items is any iterable, read once into a list. kwargs go to the constructor.
Raises TypeError for:
- a mapping as
items(pass itsvalues()oritems()as a list) - a
formatterthat is not callable, or one that returnsNone, naming the page - a
per_pagethat is not an int (a bool or a float included)
Raises ValueError for a per_page below 1.
from_cursor(fetch_fn, *, total, per_page, formatter, cache_size=10, **kwargs) (classmethod)¶
Builds a paginator whose pages load when visited, for data too large to hold (From a Database). Not a coroutine: nothing is fetched until the first render.
fetch_fn(offset, limit): returns the items for one pagetotal(int): how many items there areper_page(int): items per pageformatter: turns one page's items into the pagecache_size(int): pages kept, the least recently used dropped first, never the page on screen
Raises TypeError for:
- a
fetch_fnorformatterthat is not callable or cannot take its arguments, naming the signature it saw - a
total,per_page, orcache_sizethat is not an int - a formatter that returns
None, when that page loads
Raises ValueError for a negative total, and a per_page or cache_size below 1.
set_page(page, *, notify=True) (async)¶
Moves to zero-based page, kept inside the page count, calls on_page_changed, and redraws
(Turning Pages). notify=False skips the hook, for a move the view
makes on its own. Raises TypeError for a page that is not an int (a bool included), before anything moves.
refresh_data(items) (async)¶
Pages new data with the per_page and formatter from_data() was given. items takes what from_data()
takes, and an empty list shows the "No pages." card. Waits for a reload already running, so an older fetch cannot
land over a newer one. Raises RuntimeError, naming refresh_pages(), on a view from_cursor() built.
Raises TypeError for a mapping as items and for a page the formatter makes that cannot be shown, as from_data()
does, and ValueError when the new pages leave no room: a V1 view's page buttons with no room on row 0 beside its
other items there, or a V2 page past Discord's 40 components beside its buttons and build_extra_items() items.
The view keeps the pages it had.
refresh_pages(*, new_total=None) (async)¶
The from_cursor() counterpart: empties the page cache, fetches the page on screen again, and redraws it (the
rest load as they are visited). Pass
new_total when the count changed: the page list resizes, the jump buttons follow the new count, a page past the
end moves to the last, and 0 shows the "No pages." card. Waits for a reload() already fetching.
Raises RuntimeError on a view from_data() built, TypeError for a new_total that is not an int, and
ValueError for a negative one, or for a count whose page buttons a V1 view has no room for on row 0 beside its
other items there. A refused count changes nothing, and the view keeps the pages it had.
on_page_changed(page) (async, override)¶
Runs when a turn moves current_page, before the redraw, with the page asked for
(When the Page Changes). When the redraw does not land, the
view stays on the page it showed and the hook is not called again, so data prepared here is best keyed by page.
An override that cannot take page raises TypeError when its class is defined.
PaginatedView(*args, pages=None, **kwargs)¶
The V1 paginator, with the same class methods, methods, hook, and button attributes as PaginatedLayoutView. Its
buttons sit on row 0.
pages(sequence): each page anEmbed, a str, or a dict giving"embed","embeds", or"content"(other keys left alone)
Raises TypeError naming the page when the view is built for any other page:
None(what a formatter that returns nothing makes)- a dict giving none of the three, or both
"embed"and"embeds" - a dict with a key a letter or two off one of the three (
"contnet") - an
"embed"that is not anEmbed, or"embeds"that is not a list or tuple of them
More than ten embeds, or text over Discord's 2000-character cap, raises ValueError.
refresh_data() refuses one the same way and keeps the pages it had. A from_cursor() view checks each page as
it loads. With no pages the message reads "No pages." and the indicator Page 0/0.
A page turn shows exactly the new page: it clears what the previous page set and this one does not, and shows
again what send() was given for a field no page sets.
page_kwargs(page) (override)¶
Returns the keywords one page's edit takes: embed, embeds, or content, leaving out what the page does not
give. Override it for pages of another kind. With it overridden, the library does not check the pages, and a
return that is not a mapping, a coroutine included, raises TypeError naming the hook when the page is drawn.
Leaderboard¶
LeaderboardLayoutView(*args, entries=None, title=..., subtitle=..., banner=..., banner_description=..., bot=None, **kwargs)¶
A ranked board over pages, V2 only, built on PaginatedLayoutView. Leaderboard
teaches it.
entries:(user_id, stats_dict)pairs in rank ordertitle,subtitle,banner,banner_description: set the class attributes below for this board. Left out, the class attribute appliesbot(discord.Client): lets the defaultget_avatar_url()read avatars from the bot's user cache
entries also takes a {user_id: stats_dict} mapping, a generator or other one-pass iterable, and two-element
lists, each read as the pairs. A Member, or any object with an integer .id, stands for its id. A wrong entry
is refused when the board is built, naming the class, the argument, and the entry's index: ValueError for a
row that is not two items, TypeError for anything else, such as stats that are not a dict.
| Attribute | Default | Meaning |
|---|---|---|
leaderboard_top_n |
10 |
How many entries to rank. None ranks every entry |
leaderboard_per_page |
5 |
Entries per page. None puts every ranked entry on one page |
title |
"Leaderboard" |
The heading on the card. None or "" shows none, and with no banner either, no divider |
subtitle |
"Rankings" |
The line above the rows. None or "" leaves a gap in its place |
banner |
None |
A full-width image above the title: a URL, a discord.File, or anything with a str .url (guild.icon) |
banner_description |
None |
The banner's alt text, up to 1024 characters. None uses a discord.File banner's own |
leaderboard_empty_message |
"No entries recorded yet." |
The text with no entries |
entry_layout |
"lines" |
"lines" puts the rows in one text block, and "sections" gives each row a Section with an avatar |
podium_emojis |
{1: "🥇", 2: "🥈", 3: "🥉"} |
The glyph format_rank() shows for each rank |
entry_separator |
" -- " |
Between the name and the stats in a row |
card_color |
None |
The card's color. None takes the theme's |
show_title_divider |
True |
A line below the title |
avatar_backfill |
False |
Sections only. Draws default avatars at once, reads the real ones afterwards, then redraws (Loading Avatars Later) |
Checked when the class is defined, raising TypeError (ValueError for a value out of range) naming the
attribute:
titleandsubtitle: a str orNoneentry_separatorandleaderboard_empty_message: a strpodium_emojis: a mapping from int ranks to textcard_color: adiscord.Colouror an int from 0x000000 to 0xFFFFFFbanner_description: text within its cap
A page over Discord's 40 components raises when it builds, naming the rows and the fix. With a bot bound, a section row costs four.
A discord.File banner is uploaded by the board's own get_files() on every send, a pop() back to the board
included. A persistent board saves it as its attachment:// reference, which the
message's upload answers after a restart, and a send to a new message reads that upload back. A file sent with
spoiler=True shows blurred.
Defaults the board sets: owner_only = True, exit_policy = "delete", state_scope = None, and allowed_mentions
that ping no one (a row's <@id> shows the name without a ping).
Hooks¶
| Hook | Returns |
|---|---|
get_entries() |
The entries, read once per rebuild. The default returns entries |
format_rank(rank) |
The rank column: podium_emojis for its ranks, else **{rank}.** |
format_name(user_id, stats) |
The name column: stats["display_name"] when present, else a mention |
format_stats(user_id, stats) |
The stats column: {wins}W / {games}G |
format_accessory(user_id, stats) |
Text at the row's end. The default returns None |
format_entry(rank, user_id, stats) |
A whole "lines" row, from the four columns above |
format_primary(rank, user_id, stats) |
A section row's first line |
format_secondary(rank, user_id, stats) |
A section row's second line |
get_avatar_url(user_id, stats) (async) |
A section row's thumbnail URL. The default reads the bot's user cache (a default avatar on a miss), and returns None with no bot, so the row shows as two lines of text. A digit-string id is looked up as the id it names, and an id that names no Discord user gets None |
resolve_avatar_urls(user_ids) (async) |
A {user_id: url} dict, for avatar_backfill |
build_title(page) |
Components replacing the banner and title inside the card. None (the default) draws them from the attributes, [] draws none. A Container raises ValueError naming the hook |
build_subtitle(page) |
The line above the rows. None draws subtitle as a ### heading, or a gap without one. A str shows as written, and "" shows no line and no gap. Not called on the empty page |
build_header(page) |
What goes above the card: a Container shows as its own card, anything else as a top-level item |
build_footer(page) |
What goes below the rows: a component inside the card, a Container as its own card below it |
on_leaderboard_empty() |
The empty page's content, drawn in a card_color card under the masthead. A returned card is copied with its color |
page counts from 0. The frame hooks return a component, a list of them, text, or None, and
on_leaderboard_empty() the same but None. Anything else raises TypeError naming the hook
(Around the Rows). format_rank, format_name,
format_stats, and format_accessory run inside the synchronous format_entry, so an async def one raises
TypeError when the class is defined.
ranked_entries reads the ranked slice the current render draws, for stats in a frame hook. Totals across every
entry come from get_entries(). bot reads the bot the board was given (bot).
rebuild_pages(*, force=False) (async)¶
Reads the entries again and builds the pages, without editing the message. It runs on every state change and
skips the build when the entries match the last ones read. force=True builds anyway, for a change outside the
entries (a filter, or a select a frame hook reads).
reload(*, force=False) (async)¶
reload() for a board: reads the entries, builds the pages, and edits the message, for a
Refresh button or on_restore(). force as on rebuild_pages(), kept when the reload queues behind one
already running (Keeping It Current).
get_files() (override)¶
Returns the banner's file when banner is a discord.File, else None (get_files()). An
override that supplies files of its own adds them to super().get_files().
PersistentLeaderboardLayoutView(*args, **kwargs)¶
A board posted once that survives restarts (A Board That Survives a Restart).
Requires a persistence_key, passed or set in the class body (ValueError without one). Its defaults are
owner_only = False, exit_policy = "disable", and timeout = None.
bot is not saved with the panel: the library gives the board its bot at each send and restore, before
on_bind(bot). With none bound, bot is None, as on every view, and the board still draws
avatars through the bot PersistenceMiddleware holds.
Its on_restore(bot) calls reload() at each restore, which reads the entries and edits
the message, so its controls answer clicks at once. An override that does not call super().on_restore(bot)
skips that redraw.
Roles¶
Deprecated, removed in 5.0.0: RolesLayoutView, PersistentRolesLayoutView, and RoleCategory work through 4.x,
and a panel class defined on either view warns with a DeprecationWarning
(Roles says what to build instead).
RolesLayoutView(*args, **kwargs)¶
A panel where members give themselves roles, V2 only: one card per category, one button per role. Roles teaches it.
from cascadeui import PersistentRolesLayoutView, RoleCategory
class MyRoles(PersistentRolesLayoutView):
categories = [
RoleCategory(name="Colors", roles={"Red": 111, "Blue": 222}, exclusive=True),
]
title = "Server Roles"
A role button is a DynamicPersistentButton: a click finds its category
by the button's id, whatever view is attached, and runs with no view instance. So the panel's hooks are
classmethods, the *_message and hint_* attributes are read from the class, and set_class_attribute()
refuses them and categories (title and subtitle may be set on one panel). A click runs the hooks of the class of the live panel on the clicked message, so a subclass's
replies answer its panel. With none live there, the class that declares the category answers
(How a Click Works).
A member's clicks in one category take turns, and a click that waited reads the member's roles from Discord. An
exclusive swap adds the new role before removing the old, so a role Discord refuses leaves the old one in place.
build_ui() draws the title and the cards, and raises ValueError naming the category that would pass Discord's
40 components. Its defaults are owner_only = False, exit_policy = "delete", and state_scope = None.
| Attribute | Default | Meaning |
|---|---|---|
categories |
[] |
The RoleCategory list. A panel built with none raises ValueError |
title |
"Server Roles" |
The heading above the cards. None shows none |
subtitle |
None |
A line below the title, as written |
hint_normal |
None |
The hint under a category with neither rule |
hint_exclusive |
"◉" |
Under an exclusive category |
hint_required |
"*" |
Under a required category |
hint_exclusive_required |
"◉ *" |
Under a category with both |
assigned_message |
"Gave you **{role}**." |
The reply when a role is added |
removed_message |
"Removed **{role}**." |
The reply when a role is removed |
required_message |
"You must keep at least one **{category}** role." |
The reply when the last role of a required category is refused |
swap_message |
"Switched to **{role}** (removed {removed})." |
The reply after an exclusive swap |
role_error_message |
"Could not update roles: {error}" |
The reply when Discord refuses the change |
Checked when the class is defined: each *_message against the placeholders it names ({role}, {category},
{removed}, {error}), raising ValueError naming the attribute and the placeholders it takes, and title,
subtitle, and the hint_* attributes as a str or None (TypeError). A category of more than five roles raises
ValueError then too: a card holds one row of buttons.
Hooks¶
Each hook is a @classmethod, and a hook written as a plain method raises TypeError when the class is defined
(a format_* hook only while the class keeps the default build_category_card()). An override replies through
respond_safe(interaction, ...), which falls back to a followup once the click is
acknowledged. The format_* hooks run inside the synchronous build_ui(), so an async def one raises
TypeError when the class is defined. The on_role_* hooks may be either.
| Hook | Returns or does |
|---|---|
format_category_title(category) |
The heading: ### {name}, after category.icon when set |
format_category_hint(category) |
The hint under the heading, from the hint_* attributes. None shows none |
format_button_label(role_name, role_id, category) |
A button's label, role_name by default. "" or None with an emoji shows the emoji alone. A button with neither, or a label over 80 characters, raises ValueError when its card is built |
format_button_emoji(role_name, role_id, category) |
A button's emoji. None by default |
format_button_style(role_name, role_id, category) |
A button's style: category.button_style, else ButtonStyle.secondary. A link or premium style raises ValueError, and anything but a ButtonStyle TypeError, when its card is built |
build_category_card(category) |
One category's card, from the format_* hooks |
on_role_assigned(interaction, member, role, category) (async) |
Replies after a role is added |
on_role_removed(interaction, member, role, category) (async) |
Replies after a role is removed |
on_role_swap(interaction, member, role_added, roles_removed, category) (async) |
Replies after an exclusive swap |
on_role_required_block(interaction, member, role, category) (async) |
Replies when the last role of a required category is refused |
on_role_error(interaction, error) (async) |
Replies when Discord refuses the change |
PersistentRolesLayoutView(*args, **kwargs)¶
A role panel that survives restarts (A Panel That Survives a Restart). Requires
a persistence_key, passed or set in the class body (ValueError without one). Its defaults are owner_only = False, exit_policy = "disable", and timeout =
None.
Its buttons keep working after a restart once PersistenceMiddleware(bot=...) is installed, whatever view is attached. Its
on_restore(bot) draws the panel again from the current categories, so a change to them in the class
shows, at one edit per panel each restore. An override that does not call super().on_restore(bot) keeps the last render.
RoleCategory(name, roles, exclusive=False, required=False, color=None, button_style=None, icon=None, description=None, key=None)¶
One category, as a dataclass (Categories):
name(str): the card's headingroles: a{label: role_id}mapping or(label, role_id)pairs, kept as a copy in the order givenexclusive(bool): a member holds at most one role of the category, and a click swapsrequired(bool): a member keeps at least one, and removing the last is refusedcolor(discord.Colouror int): the card's accentbutton_style(discord.ButtonStyle): the buttons' style,secondarywhenNoneicon(str): an emoji before the headingdescription(str): text between the heading and the buttonskey(str): the middle part of each button's id,roles:{key}:{role_id}. Without it the part is made fromname, so renaming the category gives its buttons new ids: a persistent panel is redrawn with them when it is restored, and any other posted panel must be posted again. Akey(lowercase letters, digits,_,-) keeps the ids through a rename (Button Ids and Renames)
Raises ValueError for:
- an empty
name, emptyroles, or an empty label - pairs that repeat a label, or one role id under two labels
- a
keywith other characters, or ids that would pass Discord's 100 characters - a link or premium
button_style
Raises TypeError for:
- a role id that is not an int
- an
exclusiveorrequiredthat is not a bool - a
colorthat is neither adiscord.Colournor an int - a
button_stylethat is not adiscord.ButtonStyle, or adescriptionthat is not a str