Skip to content

Layout Rules and Limits

A V2 panel is a tree of components, and Discord refuses the whole message when the tree has a shape it does not take. A panel built from the layout builders gets its shape right as it is built. The rules here matter when you use discord.py's components directly, and CascadeUI checks them before every send and edit, so a mistake is named where it is in the tree instead of coming back from Discord as an error that names neither.

Animation: send() checks the Scoreboard's tree first and finds its Reset button on its own at the top level, so it raises ValueError naming the path, Scoreboard -> StatefulButton[1], and the fix, and nothing is sent. With Reset wrapped in an ActionRow the check passes and the panel posts

What Goes Where

LayoutView (the panel)
  - Container       a card: the main grouping block
      - TextDisplay     markdown text
      - Section         one to three lines of text, plus a button or a thumbnail beside them
      - ActionRow       up to five buttons, or one select
      - MediaGallery    one to ten images
      - File            a file to download
      - Separator       a divider or a gap
  - ActionRow, Section, MediaGallery, File, TextDisplay, Separator

A panel holding each of these, each named beside its part: inside the Container, a TextDisplay heading, a Section with a Thumbnail beside its text, a Section with a Button beside its text, a Separator, a MediaGallery of three images, a File, and an ActionRow of two buttons. Under the card, at the panel's top level, an ActionRow holding a Close button

  • The panel's top level and a card take the same components, except that a card cannot hold another card. card() refuses a card among its children when it is built.
  • An action row holds up to five buttons, or one select with nothing beside it.
  • A section holds one to three lines of text and one accessory, a button or a thumbnail, and cannot hold another section.
  • A button or a select always sits in an action row, and a thumbnail only beside a section's text.

Controls Inside a Card

A card takes action rows, and choice_row() returns one, so a set of options goes inside the card it belongs to. Collapsible.render() and PaginatedRegion.controls() return plain components too, so the part they reveal or page through opens inside the card when you add them to it:

from cascadeui import Collapsible, StatefulLayoutView, card, choice_row, key_value


class Filters(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.league = "Gold"
        self.more = Collapsible(
            label="More Filters",
            reveal=lambda: [key_value({"Region": "EU", "Season": "12"})],
        )
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(
            "## Filters",
            choice_row(
                {"Bronze": "Bronze", "Silver": "Silver", "Gold": "Gold"},
                selected=self.league,
                on_select=self.pick,
            ),
            *self.more.render(self),  # (1)!
        ))

    async def pick(self, interaction, league):
        self.league = league
        self.build_ui()
        await self.refresh()
  1. The More Filters button, and the filters it reveals when opened, inside the card.

Animation: the Filters card with Gold picked. Picking Silver redraws the row inside the card in one request, and clicking More Filters opens Region: EU and Season: 12 inside the same card, under the button

What reveal returns lands inside the card as well, so it cannot be another card.

When a Tree Is Refused

Before the send, and before every edit the library makes (refresh(), a push or pop), the tree is checked against Discord's rules. A tree Discord would refuse raises ValueError there, before anything is sent, naming what is wrong, where it is, and how to fix it:

from cascadeui import StatefulButton, StatefulLayoutView, card


class Scoreboard(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.add_item(card("## Scores", "Ann 12, Bo 9"))
        self.add_item(StatefulButton(label="Reset", callback=self.reset))  # (1)!

    async def reset(self, interaction):
        ...
  1. A button on its own at the panel's top level.
ValueError: Invalid V2 placement: Button cannot be a child of LayoutView.
  Path: Scoreboard -> StatefulButton[1]
  Discord rejects this composition with HTTP 400.
  Fix: Wrap the Button in an ActionRow before adding it to the LayoutView.

Here the fix is ActionRow(StatefulButton(...)), or a button_row(). An edit whose tree has not changed since the last one sends nothing and is not checked again. view.validate() runs the same checks without sending anything, for a test.

What Is Checked

discord.py refuses some shapes itself, when you build them:

  • a V2 component added to a V1 view
  • a section with more than three lines of text, or with no accessory=
  • a sixth item in an action row, or a select added after a button (a select added before buttons is built, and the check below refuses it)
  • anything but a component passed to add_item() or Container() (only Section turns a string into text)
  • a 41st component in a panel

Discord refuses the rest when the message is sent, and CascadeUI checks for them first:

  • a card inside a card, or a section inside a section
  • a button, a select, or a thumbnail at the top level or directly in a card
  • anything but buttons or a select in an action row, or a select beside anything else
  • anything but text beside a section's accessory, or an accessory that is not a button or a thumbnail
  • a modal's input (Label, TextInput, RadioGroup, CheckboxGroup, Checkbox, FileUpload) anywhere in a panel
  • an empty section, action row, or gallery, a gallery of more than ten items, empty text, and an option with an empty label or value
  • an empty media or link-button URL
  • a File component naming a web address: it shows only a file uploaded with the message
  • any text over its length: a text display, a button's label or URL, a select's placeholder, an option's label, value, or description, and a media description

One more is CascadeUI's own: an empty card, which has nothing to show.

Discord Limits lists every length. A component type the check does not know passes, so a component Discord adds later is not refused before the check learns it.

Generated Ids

A button or select given no custom_id gets one each time the panel renders, worked out from what a click on it does (its callback and the values the callback carries) and from its label. A click finds its control by that id, so a click sent from a screen that has changed since reaches a control only if it would still do the same thing. Any other click is acknowledged and dropped, and a panel still showing the older screen is drawn again.

A label that changes between renders, such as a vote count, gives the control a new id each time, so a click from the render before is dropped too. Give such a control a custom_id= of its own to keep those clicks. A panel that survives a restart sets one on every control: see A Panel That Comes Back.

The id comes from what the callback carries, not from what it reads when it runs. A Lock button whose callback reads the match the page shows has one id on every page, so a click from the page before locks the match shown now. Pass the match to the callback instead (functools.partial(lock, match), or a default argument), and the id changes with the page, so that click is dropped.

Animation: a Vote button whose label counts, with no custom_id and with custom_id="vote". Mira votes and the message shows Vote (4). With no custom_id its id changes with the label, while Kael's screen still shows Vote (3). Kael clicks Vote (3): with no custom_id the id Kael's click carries is on no control any more, so the click is acknowledged and dropped and the count stays at 4. With custom_id="vote" the id is the same, so the vote counts and the button reads Vote (5)

Repeated Ids and Values

Some rules apply to V1 views as well, and run with the placement check turned off:

  • A custom_id that is empty or over 100 characters. Discord takes 1 to 100.
  • Two components with one custom_id. Discord refuses the message (HTTP 400, code 50035). Ids CascadeUI generates never repeat, so this is two ids you passed, most often a builder used twice with its default key (PaginatedRegion, Collapsible).
  • Two components with one id=, or an id= that is not a whole number from 1 to 2147483647.
  • Two options of one select with one value. Discord refuses it, although its reference does not state the rule. StatefulSelect and Dropdown refuse it when built. The check also catches a raw discord.ui.Select, and options changed after the select was built.
  • A select no pick can satisfy: a min_values outside 0-25, a max_values outside 1-25, a min_values above the max_values or above the options a select offers, a string select with no options, and more or fewer default_values than the bounds allow. StatefulSelect and CascadeUI's typed selects refuse a bound outside its range, or a min_values above the max_values, when they are built.
  • A button with neither a label nor an emoji. Discord refuses it ("label: This field is required"), and an empty label counts as none. Link and premium buttons pass. button_row() and tab_nav() refuse such an entry when they build the row.
  • Button and select text over Discord's caps: a button label over 80 characters, a select placeholder over 150, and option text over 100.

Each raises a ValueError naming the component:

ValueError: Duplicate select option value: 'a47c3a95' is shared by the options 'Post 666' and 'Post 672' in the select 'photos' of QueueView.
  Discord rejects this message with HTTP 400 (code 50035: the specified option value is already used).
  Fix: Give each option of the select its own value.

Values built from data, such as a hash or a name, are where a repeat creeps in: two records with the same key give two options one value. The error names both options' labels, since a hash names neither record.

A dropdown as built, drawn open with two options, Post 666 and Post 672, both with the value a47c3a95, beside the ValueError send() raises before anything is sent

Counting What a Panel Holds

A V2 message holds at most 40 components, counted through the whole tree. discord.py refuses the 41st when it is added, and CascadeUI names the count it reached. To check before adding, compare what the panel holds and what a part would add against MAX_MESSAGE_COMPONENTS:

from cascadeui import MAX_MESSAGE_COMPONENTS, count_components

details = card("## Details", *lines)
if self.total_components + count_components(details) <= MAX_MESSAGE_COMPONENTS:
    self.add_item(details)

Animation: total_components counts a Server panel part by part: the card 1, two texts 1 each, a section 3 (itself, its text, its button), and a row 4 (itself and three buttons), 10 in all. count_components(details) counts the Details card 5, and 10 + 5 is within 40, so the card is added

The text of a whole V2 message is capped too, at 4000 characters across every text display. No one display has to be over its own limit for the total to cross it, so the send or edit that takes a panel over logs a warning naming the total. content_length() gives the panel's running total, and count_characters() what a part would add, to compare against MAX_MESSAGE_CHARACTERS. Both count text displays only: button labels and select text are not in them.

Turning the Check Off

validate_placement = False on a view class turns off the placement check:

class Dashboard(StatefulLayoutView):
    validate_placement = False

It is for a shape Discord has started to accept before the check knows it. For anything else, a refusal points at a real mistake, and fixing the tree is the way through. The checks under Repeated Ids and Values still run.

Less common cases

The path. Each step of the path in an error carries its position, so the component at fault is clear when several of one type sit at the same depth.

A close. The edit that freezes a panel at a timeout or exit() logs a tree the check refuses and skips the edit, rather than raising.

Modal inputs. A modal refuses two inputs with the same label when it is built. Labels that differ only in punctuation, case, or script each get their own custom_id.

Measuring a leaderboard. A section-style leaderboard row is four components with a client bound and one without, so a test with no client counts too few. from cascadeui.testing import stub_client supplies an offline client to count with.