Skip to content

How-to

Recipes for jobs that use more than one part of the library. Each runs as shown.

Find a Task

To See
Keep what a wizard's steps collect when the person goes Back Wizard: Keeping Answers
Page through rows from a database, and fetch again when they change Paginated: From a Database
Load a panel's data, and load it again from a Refresh button Building and Sending: Loading Data
Ask for typed answers Modals and Inputs, or a whole Form
Let only some people click Who Can Click
Keep one panel per person How Many Can Exist
Move between screens on one message Navigation
Give each server its own settings Scoped State
Keep a panel working after the bot restarts Panels That Survive Restarts
Let members pick their own roles Dynamic Persistent Buttons: a button for each role
Test a view without Discord Test a View Without Discord, below
Let people pick an emoji, or type their own Build an Emoji Picker, below

Test a View Without Discord

A view is a Python object, so a test can build one, call its callback, and read what the panel would show, with no bot and no connection. cascadeui.testing supplies the stand-ins. This test runs Your First Panel's counter under pytest with pytest-asyncio:

import discord
import pytest

from cascadeui.testing import stub_interaction

from mybot.counter import CounterView  # (1)!


@pytest.mark.asyncio
async def test_a_click_counts():
    view = CounterView(user_id=1, guild_id=2)  # (2)!
    await view.increment(stub_interaction())  # (3)!

    texts = [c.content for c in view.walk_children() if isinstance(c, discord.ui.TextDisplay)]
    assert texts == ["Count: **1**"]
    view.validate()  # (4)!
    assert view.total_components == 4
  1. Your First Panel's CounterView, wherever your bot keeps it.
  2. user_id and guild_id stand for the person and the server a command would give the view.
  3. Calls the callback as a click would. The view has no message yet, so its refresh() sends nothing.
  4. validate() comes with every view. It raises if Discord would refuse the panel, with the checks send() runs first.

Calling the callback directly skips what the library does between a click and the callback: who may click, the dropped double-click, and the answer to Discord. Three more stand-ins cover the rest:

Build an Emoji Picker

Discord has no emoji picker for a bot's panel, but the parts make one: a choice_row() of the emoji you offer, and a Custom option that opens a modal whose input takes any emoji through the emoji() validator.

Animation: the icon panel shows Trophy picked. Kael picks Crown, and pick_icon() stores it and redraws, so one request draws Crown picked. Kael clicks Custom, and open_modal() shows the Custom Icon modal as the click's answer. Kael types the fire emoji and submits. emoji() passes it, submitted() stores it, and one request redraws the panel with Fire picked.

import discord

from cascadeui import Choice, Modal, StatefulLayoutView, TextInput, card, choice_row, emoji


class IconView(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.icon = "\N{TROPHY}"
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"Your icon: {self.icon}"))
        self.add_item(
            choice_row(
                [
                    Choice("Trophy", "\N{TROPHY}", emoji="\N{TROPHY}"),
                    Choice("Crown", "\N{CROWN}", emoji="\N{CROWN}"),
                    Choice("Fire", "\N{FIRE}", emoji="\N{FIRE}"),
                    Choice("Custom", "custom", emoji="\N{PENCIL}"),  # (1)!
                ],
                selected=self.icon,
                on_select=self.pick_icon,
            )
        )

    async def pick_icon(self, interaction: discord.Interaction, value):
        if value == "custom":
            await self.open_modal(interaction, self.custom_modal())  # (2)!
            return
        self.icon = value
        self.build_ui()
        await self.refresh()

    def custom_modal(self):
        field = TextInput(label="Emoji", validators=[emoji()])  # (3)!

        async def submitted(interaction: discord.Interaction, values):
            self.icon = field.value
            self.build_ui()
            await self.refresh()  # (4)!

        return Modal(title="Custom Icon", inputs=[field], callback=submitted)
  1. Its value is no emoji, so pick_icon() can tell it from the others.
  2. open_modal() comes with every view: it shows the modal as the click's answer, so nothing else is sent.
  3. emoji() takes one emoji or a custom server emoji, and refuses anything else before submitted() runs: the person is told "Enter a single emoji or a custom server emoji."
  4. Answers the submission and redraws the panel in one request.

The emoji you offer are yours to choose. A choice_row() draws up to five options as buttons and more as a dropdown. is_emoji() is the check emoji() runs, for a value that comes from somewhere else.