# Modals

> Ask for text, choices and files in a form that pops up over Klang. Open a modal from a command or a component, its fields (text inputs, select menus, file uploads, radio groups and checkboxes), receive MODAL_SUBMIT and answer it, and what Klang checks before your bot gets it.

## What a modal is

A modal is a form your bot opens over Klang in answer to an interaction: a title, some text and
up to five fields. The person fills it in and sends it, and your bot gets what they wrote and chose
as a new interaction.

- **Open it** with callback type `9` (`MODAL`), as the first answer to a slash, user or message
  command or to a [component](https://docs.klang.gg/bots/components/). Not to an autocomplete, and not to the submission
  of another modal.
- **It opens only for the person** who used the command or pressed, in the window or tab where
  they did it.
- **Receive it** as an interaction of type `5` (`MODAL_SUBMIT`), and answer that one like any
  other.

A `9` has to be the first answer, within the 3 seconds: your bot can’t defer and then open a
modal.

## Open a modal

A form to report a boat sighting, with a line of text, a short field, a menu, a long field and a
menu of people:

```js
import { ModalBuilder, TextInputStyle } from 'discord.js';

const sighting = new ModalBuilder()
  .setCustomId('sighting')
  .setTitle('Report a sighting')
  .addTextDisplayComponents((text) =>
    text.setContent('Seen something odd near the harbor? Tell the harbor master.'),
  )
  .addLabelComponents(
    (label) =>
      label
        .setLabel('Boat name')
        .setTextInputComponent((input) =>
          input.setCustomId('boat').setStyle(TextInputStyle.Short).setMinLength(2).setMaxLength(40),
        ),
    (label) =>
      label
        .setLabel('Where')
        .setDescription('The closest landmark')
        .setStringSelectMenuComponent((select) =>
          select
            .setCustomId('where')
            .addOptions(
              { label: 'North pier', value: 'north-pier' },
              { label: 'Lighthouse', value: 'lighthouse' },
              { label: 'Open sea', value: 'open-sea' },
            ),
        ),
    (label) =>
      label
        .setLabel('What did you see?')
        .setTextInputComponent((input) =>
          input.setCustomId('details').setStyle(TextInputStyle.Paragraph).setRequired(false),
        ),
    (label) =>
      label
        .setLabel('Who else saw it?')
        .setUserSelectMenuComponent((select) =>
          select.setCustomId('witnesses').setRequired(false).setMaxValues(3),
        ),
  );

client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isChatInputCommand() && interaction.commandName === 'report') {
    await interaction.showModal(sighting);
  }
  if (interaction.isButton() && interaction.customId === 'report') {
    await interaction.showModal(sighting);
  }
});
```

```python
class Sighting(discord.ui.Modal, title="Report a sighting"):
    intro = discord.ui.TextDisplay("Seen something odd near the harbor? Tell the harbor master.")
    boat = discord.ui.Label(text="Boat name", component=discord.ui.TextInput(min_length=2, max_length=40))
    where = discord.ui.Label(
        text="Where",
        description="The closest landmark",
        component=discord.ui.Select(
            options=[
                discord.SelectOption(label="North pier", value="north-pier"),
                discord.SelectOption(label="Lighthouse", value="lighthouse"),
                discord.SelectOption(label="Open sea", value="open-sea"),
            ]
        ),
    )
    details = discord.ui.Label(
        text="What did you see?",
        component=discord.ui.TextInput(style=discord.TextStyle.paragraph, required=False),
    )
    witnesses = discord.ui.Label(
        text="Who else saw it?",
        component=discord.ui.UserSelect(required=False, max_values=3),
    )

    async def on_submit(self, interaction: discord.Interaction):
        ...  # see "Receive what was sent"


@client.tree.command(description="Report a boat sighting")
async def report(interaction: discord.Interaction):
    await interaction.response.send_modal(Sighting())
```

Underneath, the callback’s `data` is the modal:

```json
{
  "type": 9,
  "data": {
    "custom_id": "sighting",
    "title": "Report a sighting",
    "components": [
      { "type": 10, "content": "Seen something odd near the harbor? Tell the harbor master." },
      {
        "type": 18,
        "label": "Boat name",
        "component": {
          "type": 4,
          "custom_id": "boat",
          "style": 1,
          "min_length": 2,
          "max_length": 40
        }
      },
      {
        "type": 18,
        "label": "Where",
        "description": "The closest landmark",
        "component": {
          "type": 3,
          "custom_id": "where",
          "options": [
            { "label": "North pier", "value": "north-pier" },
            { "label": "Lighthouse", "value": "lighthouse" },
            { "label": "Open sea", "value": "open-sea" }
          ]
        }
      },
      {
        "type": 18,
        "label": "What did you see?",
        "component": { "type": 4, "custom_id": "details", "style": 2, "required": false }
      },
      {
        "type": 18,
        "label": "Who else saw it?",
        "component": { "type": 5, "custom_id": "witnesses", "required": false, "max_values": 3 }
      }
    ]
  }
}
```

With `?with_response=true`, the answer is `{ "interaction": { "id": "…", "type": 2 }, "resource":
{ "type": 9 } }`. A modal isn’t a message, so the token’s message routes answer `10015` after a
`9`; your bot answers again when the modal comes back.

## The fields

| `type`  | Component                                 | Notes                                                                                                                                                                                                   |
| ------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `18`    | Label                                     | A field: `label` (1 to 45 characters), an optional `description` (up to 100) and one `component`, any of the ones below but the text display.                                                           |
| `4`     | Text input                                | Inside a label. `style` `1` is one line, `2` a paragraph. `min_length` and `max_length` up to 4,000, `required` (`true` unless you say otherwise), `value` to fill it in and `placeholder` (up to 100). |
| `3`     | Text menu                                 | Inside a label, with its `options`, as in a [message](https://docs.klang.gg/bots/components/#select-menus).                                                                                                                  |
| `5`–`8` | User, role, mentionable and channel menus | Inside a label, as in a message.                                                                                                                                                                        |
| `19`    | File upload                               | Inside a label. 0 to 10 files, and `file_types` to take only some. See [Files, choices and checkboxes](https://docs.klang.gg/bots/modals/#files-choices-and-checkboxes).                                                                  |
| `21`    | Radio group                               | Inside a label. 2 to 10 options; the person picks one.                                                                                                                                                  |
| `22`    | Checkbox group                            | Inside a label. 1 to 10 options; the person ticks as many as `min_values` and `max_values` allow.                                                                                                       |
| `23`    | Checkbox                                  | Inside a label. One box, ticked or not.                                                                                                                                                                 |
| `10`    | Text display                              | Markdown text between the fields.                                                                                                                                                                       |

The menus of a modal take `required` (`true` unless you say otherwise) and can’t be `disabled`. A
required menu needs `min_values` of at least 1. A modal has a `custom_id` of 1 to 100 characters,
a `title` of 1 to 45 and 1 to 5 components. Every field and its limits are in the
[Components reference](https://docs.klang.gg/bots/reference/components/#modal-components).

**The older form**, an action row (`1`) with one text input that carries its own `label`, works
too. Libraries that don’t know labels yet send it, and Klang answers their submission in the same
form.

In Klang, the modal shows your bot’s title, its name and avatar with a **Bot** tag, and the
fields in order. A field that isn’t required is marked **Optional**. The person can cancel; your
bot isn’t told, as in Discord. A new modal replaces one that’s open.

## Receive what was sent

When the person sends the form, your bot gets an interaction of type `5`. Its `data` has the
modal’s `custom_id` and its `components` in the same order, each field with what was written
(`value`) or chosen (`values`). Text displays come back with only their `type` and `id`:

```json
{
  "custom_id": "sighting",
  "components": [
    { "type": 10, "id": 1 },
    {
      "type": 18,
      "id": 2,
      "component": { "type": 4, "id": 3, "custom_id": "boat", "value": "Sea Swallow" }
    },
    {
      "type": 18,
      "id": 4,
      "component": { "type": 3, "id": 5, "custom_id": "where", "values": ["north-pier"] }
    },
    {
      "type": 18,
      "id": 6,
      "component": { "type": 4, "id": 7, "custom_id": "details", "value": "Lights off after dark." }
    },
    {
      "type": 18,
      "id": 8,
      "component": {
        "type": 5,
        "id": 9,
        "custom_id": "witnesses",
        "values": ["1575618979053707264"]
      }
    }
  ],
  "resolved": {
    "users": {
      "1575618979053707264": {
        "id": "1575618979053707264",
        "username": "nora",
        "discriminator": "0",
        "global_name": "Nora",
        "avatar": null,
        "banner": null,
        "accent_color": null,
        "public_flags": 0
      }
    },
    "members": {
      "1575618979053707264": {
        "nick": null,
        "avatar": null,
        "banner": null,
        "roles": [],
        "joined_at": "2026-11-26T21:07:19.649Z",
        "premium_since": null,
        "flags": 0,
        "pending": false,
        "communication_disabled_until": null,
        "permissions": "7328575711604735"
      }
    }
  }
}
```

A field that isn’t required and was left empty comes back with `""` or `[]` (a radio group, with
`null`). `resolved` holds the people, roles and channels chosen in the menus. With the older form, each field comes back as an
action row with its text input. If a component opened the modal, the interaction also has
`message`, the message of that component.

```js
client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isModalSubmit() && interaction.customId === 'sighting') {
    const boat = interaction.fields.getTextInputValue('boat');
    const [where] = interaction.fields.getStringSelectValues('where');
    const details = interaction.fields.getTextInputValue('details');
    const witnesses = interaction.fields.getSelectedUsers('witnesses');
    await interaction.reply({
      content: `Thanks, ${interaction.user.displayName}. The harbor master has your report on **${boat}**.`,
      flags: MessageFlags.Ephemeral,
    });
  }
});
```

```python
class Sighting(discord.ui.Modal, title="Report a sighting"):
    # …the fields as above…

    async def on_submit(self, interaction: discord.Interaction):
        boat = self.boat.component.value
        where = self.where.component.values[0]
        witnesses = self.witnesses.component.values
        await interaction.response.send_message(
            f"Thanks, {interaction.user.display_name}. The harbor master has your report on **{boat}**.",
            ephemeral=True,
        )
```

## Answer a submission

A submitted modal has its own token, its 3 seconds and its 15 minutes. It takes callbacks `4` (a
message) and `5` (thinking, then a message). If a component opened the modal, it also takes `7`
and `6`, which update that component’s message: discord.js checks this with
`interaction.isFromMessage()`. Any other type answers `50035`:

```json
{
  "code": 50035,
  "message": "The request body isn’t valid.",
  "errors": {
    "type": {
      "_errors": [{ "code": "BASE_TYPE_CHOICES", "message": "Value must be one of {4, 5}." }]
    }
  }
}
```

The message your bot sends is an ordinary message (type `0`) with `interaction_metadata` of type
`5`.

## Files, choices and checkboxes

Four more fields go inside a label: a **file upload** (`19`) for pictures or documents, a **radio
group** (`21`) to pick one option from a short list, a **checkbox group** (`22`) to tick several,
and a single **checkbox** (`23`) for a yes or no. A form to report something lost at the harbor,
with up to three photos:

```js
import {
  CheckboxBuilder,
  CheckboxGroupBuilder,
  FileUploadBuilder,
  LabelBuilder,
  ModalBuilder,
  RadioGroupBuilder,
} from 'discord.js';

const lostItem = new ModalBuilder()
  .setCustomId('lost-item')
  .setTitle('Report a lost item')
  .addLabelComponents(
    new LabelBuilder()
      .setLabel('Photos')
      .setDescription('Up to three pictures of it')
      .setFileUploadComponent(
        new FileUploadBuilder().setCustomId('photos').setMaxValues(3).setFileTypes(['image']),
      ),
    new LabelBuilder()
      .setLabel('Where did you lose it?')
      .setRadioGroupComponent(
        new RadioGroupBuilder()
          .setCustomId('place')
          .addOptions(
            { label: 'North pier', value: 'north-pier' },
            { label: 'South pier', value: 'south-pier' },
            { label: 'On a boat', value: 'boat', description: 'Say which one in the photos' },
          ),
      ),
    new LabelBuilder()
      .setLabel('What is it?')
      .setCheckboxGroupComponent(
        new CheckboxGroupBuilder()
          .setCustomId('kind')
          .setMaxValues(2)
          .addOptions(
            { label: 'Keys', value: 'keys' },
            { label: 'A bag', value: 'bag' },
            { label: 'Something else', value: 'other' },
          ),
      ),
    new LabelBuilder()
      .setLabel('Post it in the channel')
      .setCheckboxComponent(new CheckboxBuilder().setCustomId('public').setDefault(true)),
  );
```

```python
class LostItem(discord.ui.Modal, title="Report a lost item"):
    photos = discord.ui.Label(
        text="Photos",
        description="Up to three pictures of it",
        component=discord.ui.FileUpload(max_values=3),
    )
    place = discord.ui.Label(
        text="Where did you lose it?",
        component=discord.ui.RadioGroup(
            options=[
                discord.RadioGroupOption(label="North pier", value="north-pier"),
                discord.RadioGroupOption(label="South pier", value="south-pier"),
                discord.RadioGroupOption(
                    label="On a boat", value="boat", description="Say which one in the photos"
                ),
            ]
        ),
    )
    kind = discord.ui.Label(
        text="What is it?",
        component=discord.ui.CheckboxGroup(
            max_values=2,
            options=[
                discord.CheckboxGroupOption(label="Keys", value="keys"),
                discord.CheckboxGroupOption(label="A bag", value="bag"),
                discord.CheckboxGroupOption(label="Something else", value="other"),
            ],
        ),
    )
    public = discord.ui.Label(
        text="Post it in the channel",
        component=discord.ui.Checkbox(default=True),
    )
```

What each one takes:

- **File upload**: `min_values` and `max_values` from 0 to 10 (one and one unless you say
  otherwise), `required`, and `file_types` to take only some files: `image`, `video`, `audio` or
  extensions with their dot, such as `.pdf`, up to 10. discord.py 2.7.1 has no `file_types` yet,
  so its uploads take any file.
- **Radio group**: 2 to 10 `options`, each with `label`, `value`, an optional `description` and
  `default` (one at most), and `required`. Its options have no emoji.
- **Checkbox group**: 1 to 10 `options`, like a radio group’s, `min_values` (1 unless you say
  otherwise) and `max_values` (all the options unless you say otherwise), and `required`.
- **Checkbox**: `default`, to show it ticked. It’s never required.

In Klang, radio and checkbox groups look like the answers of a poll, one row per option, and a
checkbox is one row with its label beside the box. A file upload is an area to drop files on or
pick them from, which says how many files it takes and of which kinds. Each file uploads as soon
as the person picks it, the way files go into a message, and **Send** waits until they’re all up.

When the form comes back, the four fields are in `data.components` like the others: a file
upload has `values`, the IDs of the files; a radio group has `value`, the option chosen or `null`;
a checkbox group has `values`; and a checkbox has `value`, `true` or `false`. The files themselves
are in `resolved.attachments`, by ID, as [attachments](https://docs.klang.gg/bots/reference/objects/#attachment) with
`ephemeral: true`:

```json
{
  "custom_id": "lost-item",
  "components": [
    {
      "type": 18,
      "id": 1,
      "component": {
        "type": 19,
        "id": 2,
        "custom_id": "photos",
        "values": ["1575719347472695296", "1575719347594330112"]
      }
    },
    {
      "type": 18,
      "id": 3,
      "component": { "type": 21, "id": 4, "custom_id": "place", "value": "boat" }
    },
    {
      "type": 18,
      "id": 5,
      "component": { "type": 22, "id": 6, "custom_id": "kind", "values": ["keys", "bag"] }
    },
    {
      "type": 18,
      "id": 7,
      "component": { "type": 23, "id": 8, "custom_id": "public", "value": true }
    }
  ],
  "resolved": {
    "attachments": {
      "1575719347472695296": {
        "id": "1575719347472695296",
        "filename": "keys.png",
        "content_type": "image/png",
        "size": 153,
        "url": "https://cdn.klangcdn.com/adjuntos/251915898243383296/251916474435895296-2FaBaFJZPdjfTx1Fu0kQBA",
        "proxy_url": "https://cdn.klangcdn.com/adjuntos/251915898243383296/251916474435895296-2FaBaFJZPdjfTx1Fu0kQBA",
        "ephemeral": true
      },
      "1575719347594330112": {
        "id": "1575719347594330112",
        "filename": "bag.png",
        "content_type": "image/png",
        "size": 155,
        "url": "https://cdn.klangcdn.com/adjuntos/251915898243383296/251916474557530112-GynPLokd216L3F49qrOylA",
        "proxy_url": "https://cdn.klangcdn.com/adjuntos/251915898243383296/251916474557530112-GynPLokd216L3F49qrOylA",
        "ephemeral": true
      }
    }
  }
}
```

**The files’ addresses work for a day.** They belong to no message, and Klang deletes them a day
after they were uploaded. If your bot wants to keep one, it downloads it, or sends it again in a
message of its own, as this answer does. Unticking the checkbox makes the answer
[ephemeral](https://docs.klang.gg/bots/interactions/#ephemeral-messages), files included:

```js
client.on(Events.InteractionCreate, async (interaction) => {
  if (interaction.isModalSubmit() && interaction.customId === 'lost-item') {
    const photos = interaction.fields.getUploadedFiles('photos', true);
    const place = interaction.fields.getRadioGroup('place', true);
    const kinds = interaction.fields.getCheckboxGroup('kind');
    const isPublic = interaction.fields.getCheckbox('public');

    // The photos' URLs work for a day: download the ones you want to keep.
    const files = await Promise.all(
      photos.map(async (photo) => ({
        attachment: Buffer.from(await (await fetch(photo.url)).arrayBuffer()),
        name: photo.name,
      })),
    );
    await interaction.reply({
      content: `Noted: ${kinds.join(' and ')}, lost at ${place}.`,
      files,
      flags: isPublic ? undefined : MessageFlags.Ephemeral,
    });
  }
});
```

```python
class LostItem(discord.ui.Modal, title="Report a lost item"):
    # …the fields as above…

    async def on_submit(self, interaction: discord.Interaction):
        # The photos' URLs work for a day: download the ones you want to keep.
        files = [await photo.to_file() for photo in self.photos.component.values]
        await interaction.response.send_message(
            f"Noted: {' and '.join(self.kind.component.values)}, lost at {self.place.component.value}.",
            files=files,
            ephemeral=not self.public.component.value,
        )
```

## What Klang checks for you

Klang keeps the modal your bot opened, and checks the submission against it before your bot gets
anything:

- it’s the person the modal was opened for, and the 15 minutes of the interaction aren’t over;
- every field is one of the modal’s, once: text in a text input, values in a menu;
- required fields aren’t empty, text is between `min_length` and `max_length`, and a menu’s
  values are among its options and between `min_values` and `max_values`;
- a radio group’s value is one of its options, and a checkbox group’s values are among its
  options, without repeats, and between `min_values` and `max_values`;
- people, roles and channels are ones the person can see there, as in a
  [menu on a message](https://docs.klang.gg/bots/components/#what-klang-checks-for-you);
- the files were uploaded by that person, in full, and aren’t in a message. Each one fits
  `file_types` by its extension, and **its first bytes match its type**: a file named `.png` that
  isn’t a picture doesn’t get through. Each one fits the size the person can upload in that
  channel, with the better of their plan and the server’s, as when they attach a file to a
  message. They also need **Attach files** in the channel;
- a modal is sent **once**. The person can’t send the same one twice.

The person sees a problem under its field, and the form stays open to fix it. A form that
expired or was already sent closes with **This form isn’t open any more: it expired or was
already sent.** Your bot hears nothing about either. A person can send 5 modals every 10 seconds.
