Skip to content

Modals and Inputs

A modal is the dialog a click opens to ask for text, choices, or files. Build one from CascadeUI's inputs, open it with open_modal(), and read each input's value in the modal's callback.

This panel renames itself through a modal:

import discord

from cascadeui import Modal, StatefulButton, StatefulLayoutView, TextInput, card, min_length


class ProfileView(StatefulLayoutView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.name = "Unnamed"
        self.build_ui()

    def build_ui(self):
        self.clear_items()
        self.add_item(card(f"## {self.name}"))
        self.add_item(discord.ui.ActionRow(StatefulButton(label="Rename", callback=self.rename)))

    async def rename(self, interaction):
        field = TextInput("Name", default=self.name, max_length=32, validators=[min_length(2)])  # (1)!

        async def save(interaction, values):  # (2)!
            self.name = field.value
            self.build_ui()
            await self.refresh()  # (3)!

        await self.open_modal(interaction, Modal(title="Rename", inputs=[field], callback=save))
  1. A new modal for each click: a modal takes one submission.
  2. Runs once every validator has passed.
  3. Answers the submission by redrawing the panel, as a click's refresh() does.

Kael clicks Rename, and open_modal() shows a modal whose Name box holds the current name, Unnamed. Kael types Ada and submits. save() runs and refresh() answers the submission, so one request redraws the panel as Ada

Opening a Modal

Open a modal from a view's callback with open_modal(). A modal has to be the click's first answer, and open_modal() sends a short notice instead when something answered first. A slash command has no view, so it opens one with await interaction.response.send_modal(modal), and the modal works the same way. A modal's submission can be answered with another modal: open_modal() from its callback opens the next dialog.

A modal takes one submission. Once someone submits it, discord.py stops listening for it, even when a validator refused the answer, so build a new Modal each time you open one, as the example does. Opening a modal that already took a submission raises RuntimeError, since the dialog would show and the answer would go nowhere.

Discord tells the bot nothing when someone closes a modal without submitting it. When the same person next opens a modal through open_modal(), the library lets go of the one they closed, so a bot that opens many modals does not keep them all. A dialog the person left open on another device can then no longer be submitted: see A Dialog Left Open on a Second Device.

A modal holds up to five items, and its title is up to 45 characters.

The Five Inputs

Input What the person gives After submit
TextInput a line or a paragraph of text .value, a str
Checkbox yes or no .value, a bool
CheckboxGroup any of up to 10 options .values, a list[str]
RadioGroup one of 2 to 10 options .value, a str, or None when nothing was picked
FileUpload up to 10 files .values, a list[discord.Attachment]

One modal holding each of the five inputs, filled in: TextInput (Name) gives back .value, a str. Checkbox (I agree to the rules) gives .value, a bool. CheckboxGroup (Roles) gives .values, a list of str. RadioGroup (Region) gives .value, a str. FileUpload (Portrait) gives .values, a list of discord.Attachment

Each takes a label of up to 45 characters, shown above it, and an optional description of up to 100, shown in smaller text beneath. Labels can be in any language. Each also takes validators=, covered under Checking Answers.

TextInput

from cascadeui import TextInput

name = TextInput("Name", placeholder="What should we call you?", max_length=32)
bio = TextInput("Bio", style=discord.TextStyle.paragraph, required=False)

placeholder (up to 100 characters) shows in the empty box, default (up to 4000) fills it, and min_length and max_length bound the answer (up to 4000). A required box answered with only spaces is refused as empty: Discord accepts spaces, so the library checks it. A default has to fit the bounds: one longer than max_length, or shorter than min_length unless it is empty, raises ValueError when the input is built.

Checkbox

from cascadeui import Checkbox

agree = Checkbox("I agree to the rules", default=False)

CheckboxGroup and RadioGroup

from cascadeui import CheckboxGroup, RadioGroup

roles = CheckboxGroup(
    "Roles",
    options=[
        {"label": "Tank", "value": "tank"},
        {"label": "Healer", "value": "healer", "default": True},
        {"label": "Damage", "value": "damage"},
    ],
    max_values=2,
)
region = RadioGroup("Region", options=[{"label": r, "value": r} for r in ("NA", "EU", "APAC")])

An option is a dict of label, value, and optionally description and default, or a discord.CheckboxGroupOption (discord.RadioGroupOption for a radio group). Each text is up to 100 characters, and a value left out takes the label. min_values and max_values bound how many boxes a checkbox group takes, and a min_values of 0 needs required=False. With neither set, at least one box has to be ticked before the dialog can be submitted.

FileUpload

from cascadeui import FileUpload

portrait = FileUpload("Portrait", required=False, max_values=1)

Each discord.Attachment links to the file on Discord's servers. Read or save the file in the callback (await attachment.read()), rather than keeping the attachment for later.

Reading What Was Submitted

The modal's callback runs once every validator has passed. It receives the submission's interaction and the answers, and may be async def or a plain def. A callback that cannot take both is refused when the modal is built.

Read each answer from its input, as the example does with field.value. The values argument holds the same answers keyed by each input's id ("input_name" for a label of "Name"), and modal.values_by_input holds them keyed by the input itself. The ids are worked out from the labels, so reading the inputs is the simpler way.

A modal with no callback still acknowledges every submission.

Checking Answers

Give an input a list of validators, and the modal runs them on submit:

from cascadeui import TextInput, min_length, regex

username = TextInput(
    "Username",
    description="Letters, numbers, and underscores.",
    validators=[min_length(3), regex(r"^\w+$", "Letters, numbers, and underscores only")],
)

When one fails, the person gets a private reply naming each field and what was wrong with it (Username: Must be at least 3 characters), the callback does not run, and every input keeps the value it had. Discord closes the dialog on submit, so they open it again to fix the answer. Validation lists the built-in validators and how to write your own.

In the opening example, Kael types A and submits. min_length(2) refuses it, so save() never runs: the panel still reads Unnamed, and a private reply says Name: Must be at least 2 characters

A slow validator does not cost the submission: if nothing has answered it 2.5 seconds after it arrives, the modal acknowledges it. A Modal subclass can change that with auto_defer_delay, kept under 3 seconds.

Editing Saved Values

To let people edit what they saved, build the modal from the saved values each time it opens, so a person who changes one field submits the rest as they were. A method that returns the modal keeps the button's callback to one line. On a view that keeps bio, region, roles, and dms:

from cascadeui import Checkbox, CheckboxGroup, Modal, RadioGroup, TextInput

REGIONS = ["NA", "EU", "APAC"]
ROLES = ["Tank", "Healer", "Damage"]


class ProfileEditor(StatefulLayoutView):
    def profile_modal(self):
        bio = TextInput("Bio", style=discord.TextStyle.paragraph, default=self.bio or None, required=False)
        region = RadioGroup(
            "Region", options=[{"label": r, "value": r, "default": r == self.region} for r in REGIONS]
        )
        roles = CheckboxGroup(
            "Roles",
            max_values=2,
            options=[{"label": r, "value": r, "default": r in self.roles} for r in ROLES],
        )
        dms = Checkbox("Allow DMs", default=self.dms)

        async def save(interaction, values):
            self.bio = bio.value or ""
            self.region = region.value
            self.roles = roles.values
            self.dms = dms.value
            self.build_ui()
            await self.refresh()

        return Modal(title="Edit Profile", inputs=[bio, region, roles, dms], callback=save)

    async def edit(self, interaction):
        await self.open_modal(interaction, self.profile_modal())

examples/v2_wizard.py runs this shape: its name step pairs a text input with an optional portrait upload, and its background step puts a text box, a radio group, a checkbox group, and a checkbox in one modal.

Replying From a Modal

A submission is an interaction of its own, with its own 3 seconds to answer. A callback that redraws the view with refresh() answers it, as in the example. To say something, use respond(), which works before or after a redraw:

async def save(interaction, values):
    self.name = field.value
    self.build_ui()
    await self.refresh()
    await self.respond(interaction, "Saved.", ephemeral=True)

Responding to Clicks covers respond() and the 3-second rule. The library acknowledges the submission for you, so the callback needs no defer(). Defer only right before a followup.send() of your own, or in a raw discord.ui.Modal you write yourself.

When the View Closes First

A modal stays open after the view that opened it closes: a person can still be typing when the view times out. Their submission still runs the callback, and then they are told "This session has ended." unless the callback answered them.

Kael has the Rename modal open when the view's timeout runs out, and on_timeout() closes the panel with Rename disabled. Kael submits anyway: save() still runs and its refresh() updates the closed message to Ada, Rename still disabled, and then a private notice says This session has ended.

  • Reply with self.respond(), or defer first and then send a followup, and the notice is left out. A raw interaction.followup.send() sent without a defer first is followed by the notice too.
  • Override on_session_ended(interaction) on the view to answer these submissions your own way, or set session_ended_message = None to send nothing. An override that cannot take the interaction is refused when its class is defined.
  • A callback that rebuilds the view and calls refresh() updates the closed message, with its controls still disabled or removed, so the panel still reads as closed.
  • An answer a validator refuses gets the notice instead of the list of fields, since the form cannot be opened again.

Testing a Modal Offline

submit() runs a submission without Discord, through the same validators and callback a real one takes:

from cascadeui.testing import stub_interaction

accepted = await modal.submit(stub_interaction(), {"Name": "Ada"})

It returns True when the callback ran and False when a validator refused the answer. Key the values by each input's label or its id. See the reference.

A field left out keeps the value it has, and a choice never given one holds the options marked as defaults, as the dialog opens. A choice takes its options' values ("yes", not True): a list of them for a select or a checkbox group, even one that takes a single pick, and one value for a radio group. Anything else raises at the call.

Less common cases

discord.py inputs. inputs= also takes a discord.ui.TextInput, a discord.ui.Label around any modal input (which is how a select goes into a modal), and a discord.ui.TextDisplay, shown as text. A button, or a select outside a Label, raises TypeError when the modal is built, since Discord would refuse the modal. open_modal() checks these items against Discord's limits before the modal opens (a Label's text up to 45 characters, a select with 1 to 25 options and not disabled, a TextDisplay with text) and raises ValueError naming the one past them.

A fixed custom_id. discord.py files an open modal by its custom_id alone, so two people with a modal of the same custom_id= open share one. Leave it unset unless only one person at a time can have the modal open. A modal opened with open_modal() refuses a submission from anyone it was not opened for: the person is told "This form is no longer open. Please open it again." (set stale_submission_message on a Modal subclass to change it, or to None for no reply), and the log names the custom_id.

Recording the submission. view_id=self.id makes the modal dispatch a MODAL_SUBMITTED action, with the answers and the person's id, before the callback runs. See Built-in Actions.

Refused when built. Each of these raises ValueError where the modal or input is built, instead of failing when the modal opens:

  • a label or title over 45 characters
  • a placeholder, description, or option text over 100
  • a default over 4000 or outside its length bounds
  • a minimum above its maximum
  • two inputs with the same label

A keyword the modal does not take, such as on_submit= where callback= was meant, raises TypeError.

A pick that opened the modal. A dropdown option that opens a modal leaves the pick showing until the panel redraws, and the submission redraws it, as described in Keeping a Pick on Screen.