Skip to content

Menu

A menu is a hub: one button per category, each opening its own screen on the same message, and Back on that screen leads here again. You list the categories, and the menu wires each button to push().

Kael clicks Appearance on the Settings menu: the Appearance screen opens on the same message with Back and Exit, and current_view reads AppearanceView. Kael clicks Back: the menu is built again and shows as it was. Kael clicks Notifications: the Notifications screen opens the same way

from cascadeui import MenuLayoutView, StatefulLayoutView, card, divider


class AppearanceView(StatefulLayoutView):
    def build_ui(self):  # (1)!
        self.clear_items()
        self.add_item(card("## Appearance", "Theme: dark"))
        self.add_item(self.make_nav_row())  # (2)!


class NotificationsView(StatefulLayoutView):
    def build_ui(self):
        self.clear_items()
        self.add_item(card("## Notifications", "Mentions: on"))
        self.add_item(self.make_nav_row())


class SettingsMenu(MenuLayoutView):
    auto_exit_button = False  # (4)!

    def __init__(self, **kwargs):
        super().__init__(
            categories=[
                {
                    "label": "Appearance",
                    "emoji": "\N{ARTIST PALETTE}",
                    "description": "Theme and accent colors",
                    "view": AppearanceView,  # (3)!
                },
                {
                    "label": "Notifications",
                    "emoji": "\N{BELL}",
                    "description": "DMs, mentions, and event alerts",
                    "view": NotificationsView,
                },
            ],
            **kwargs,
        )

    def build_menu_card(self, items):  # (5)!
        return card(
            "## Settings",
            "-# Pick a category.",
            divider(),
            *items,
            divider(),
            self.make_nav_row(back=False),
        )
  1. The menu runs the screen's build_ui() each time it opens the screen.
  2. make_nav_row() comes with every V2 view: Back returns to the menu, and Exit closes the panel. A screen has no Back button unless it adds one.
  3. The class, not an instance: each click builds a new screen.
  4. Leaves out the Exit row the menu adds below its card, since this menu puts Exit inside the card.
  5. The card that holds the categories. This one puts the heading above them and Exit below a line, so the menu is one card. See Hooks for the others.

The panel is one card: the heading, each category's description beside its button, and Exit under a line.

Send it like any view: await SettingsMenu(interaction=interaction).send() (see Sending a View).

Categories

Each category is a dict:

Key Required What it does
label yes The button's label.
view yes The view class the button opens.
emoji no An emoji on the button.
description no MenuLayoutView only: the text beside the button. Without one, the label shows there in bold.
style no The button's ButtonStyle, in place of the menu's menu_style.
rebuild no A function that sets the screen up before it shows. See What a Screen Shows.

The menu checks the list when it is built, so a mistake raises there and never on a click:

  • no categories= at all, or an empty list. The menu reads them only from the keyword, so a categories set in the class body raises too, saying to pass it to super().__init__() as above
  • an entry that is not a mapping, or one missing label or view
  • a key a letter or two off one above, such as "descripton" (keys of your own are left alone)
  • a view that is not a view class, an instance of one included, since each click builds a new screen from it
  • a view of the other kind: a MenuLayoutView opens StatefulLayoutViews and a MenuView opens StatefulViews, because a message cannot switch between the two (see Between the Two Kinds of View)
  • a rebuild that cannot be called with the screen
  • a style that is a link or premium style, which sends the bot no click

The categories property reads back the list the menu was built with.

What a Screen Shows

One click on a category, step by step: on_category_selected() runs first, and returning False keeps the menu with nothing opened while the click is still answered. Otherwise push() builds a new screen from the category's view, its on_load() runs, then the category's rebuild or, without one, the screen's own drawing (build_ui() here), and one edit shows the screen on the same message

A click first runs the screen's on_load(), then draws it:

  • A screen that names its own nav_rebuild, or one built from a pattern (a form, a wizard, tabs, a paginated view, another menu), draws itself.
  • Otherwise a StatefulLayoutView with a build_ui() has it run, as in the example above. One without shows what its __init__ or on_load() built.
  • Otherwise a StatefulView shows the embed its build_embed() returns. Without a build_embed(), it shows the content of the dict its build_ui() returns.

A screen that reads a database loads in on_load(), which runs each time the screen opens, so every visit shows fresh data (see Screens That Load From a Database).

A category's rebuild takes the place of that drawing step. The menu calls it with the new screen after the screen's on_load(), so one screen class can open differently from two categories:

{"label": "This Week", "view": StatsView, "rebuild": lambda v: v.show("week")},
{"label": "All Time", "view": StatsView, "rebuild": lambda v: v.show("all")},

For a StatefulView, rebuild returns the keywords the edit sends, such as {"embed": ...}, as push(rebuild=) does.

Going Back

A screen opened from the menu has no Back button until it adds one. It can return make_nav_row() for Back and Exit in one row, as above, or make_back_button() for Back alone, or set auto_back_button = True (see Back Buttons).

Back runs pop(), which builds the menu again from the arguments it was built with, so a header that reads live data shows it fresh.

A category's view can be another menu, for categories inside categories. Give the inner menu auto_back_button = True so it has a way back to the outer one.

Styles and the Exit Button

Attribute Default What it does
menu_style ButtonStyle.primary The style of every category's button, unless the category gives its own.
auto_exit_button True Adds an Exit button: on row 4 of a MenuView, in a row below the card on a MenuLayoutView.

Exit closes the menu the way its exit_policy says. Set auto_exit_button = False to leave it out, or to place your own with make_exit_button(), or with make_nav_row(back=False) as the menu at the top of this page does. A menu_style that is a link or premium style raises when the class is defined.

Hooks

on_category_selected(category, index, interaction) runs after the click and before the screen opens. category is the category's dict and index its place in the list. Use it to record the visit or to prepare what the screen reads:

async def on_category_selected(self, category, index, interaction):
    await self.dispatch("MENU_OPENED", {"category": category["label"]})

Return False to keep the menu on screen and open nothing. Reply through respond() to tell the person why. Without a reply the click is acknowledged and nothing else happens:

async def on_category_selected(self, category, index, interaction):
    if category["label"] == "Billing" and not interaction.user.guild_permissions.administrator:
        await self.respond(interaction, "Billing is for admins.")
        return False

Any other return, including none, opens the category. An exception raised there stops it too, but the person then gets the reply from on_error() instead.

A menu with each part labeled by what draws it: build_header() above the card, build_menu_card(items) for the card around the items, build_category_item() for each category's section, its text beside its button, menu_style or the category's style for the button, build_footer() below the card, and auto_exit_button for the Exit row

The other hooks draw the menu:

Hook On Returns
build_header() MenuLayoutView What shows above the category card: a component, a list of them, or text.
build_footer() MenuLayoutView What shows below it, in the same forms. A row of extra buttons goes here.
build_category_item(category, index) MenuLayoutView One category's component. The default is an action_section() holding the description and the button.
build_menu_card(items) MenuLayoutView The card that holds the items. The default is a card() in the theme's accent color.
build_category_button(category, index) MenuView One category's button. The default is a StatefulButton, five to a row.
build_embed() MenuView The embed above the buttons, a list of embeds, or None. The default is titled "Menu".
build_extra_items() MenuView Nothing: it adds controls with self.add_item(). It runs each time the menu draws, so build the controls fresh.

Anything build_header() or build_footer() returns that is not a component or text raises TypeError naming the hook, as does a build_embed() that returns something other than an embed, a list of them, or None.

V1 and V2

MenuView is the same menu on a StatefulView. Each category is a button, five to a row, under the embed build_embed() returns, and description is not shown. When send() is given no embed, the first message carries that embed, below any content= text.

import discord

from cascadeui import MenuView


class SettingsMenu(MenuView):
    def __init__(self, **kwargs):
        super().__init__(
            categories=[
                {"label": "Appearance", "emoji": "\N{ARTIST PALETTE}", "view": AppearanceView},
                {"label": "Notifications", "emoji": "\N{BELL}", "view": NotificationsView},
            ],
            **kwargs,
        )

    def build_embed(self):
        return discord.Embed(title="Settings", description="Pick a category.")

Here AppearanceView and NotificationsView are StatefulViews.

How many categories fit:

  • A MenuView holds 25 buttons, so 25 categories, or 24 with the Exit button. More than that raises ValueError when the menu is built.
  • On a MenuLayoutView each category takes three of a message's 40 components (the section, its text, and its button), and the card one more. That is 13 categories with no header, footer, or Exit button, and 12 with Exit. Building a menu past the limit raises naming the count and what to trim.
Changing the style or the Exit button for one menu

set_class_attribute() changes menu_style or auto_exit_button on one menu, from its next draw:

menu = SettingsMenu(interaction=interaction)
menu.set_class_attribute("menu_style", discord.ButtonStyle.secondary)
await menu.send()