Bots
Buttons, menus and layouts
Put buttons and select menus on your bot’s messages, build whole messages out of layout components with IS_COMPONENTS_V2, and answer when someone presses or chooses. What Klang checks before your bot hears about a press, the limits and what isn’t supported.
Two kinds of messages
Your bot’s messages can carry components, in a components array, the same way Discord’s
API takes them. There are two ways to use them, and a message is one or the other:
- Buttons and select menus under an ordinary message, with its text and embeds. They go in action rows: up to 5 rows, each with up to 5 buttons or a single select menu.
- Layout components: the whole message is made of blocks of text, images, files, separators
and boxes, mixed with rows of buttons and menus. The message needs the
IS_COMPONENTS_V2flag and has nocontentorembedsof its own. See Layout components.
Components go wherever your bot writes a message with its token or an interaction’s token:
sending and
editing messages, the callback of an interaction
(types 4 and 7), follow-ups and @original. People can’t send components, and incoming
webhooks ignore them. Every type and field is in the
components reference.
Send buttons and select menus
A panel where people pick their harbor roles, with a row of buttons, a menu of options and a menu of people:
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
StringSelectMenuBuilder,
UserSelectMenuBuilder,
} from 'discord.js';
const roles = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('role:sailor')
.setLabel('Sailor')
.setEmoji('⛵')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId('role:fisher').setLabel('Fisher').setStyle(ButtonStyle.Success),
new ButtonBuilder().setCustomId('report').setLabel('Report').setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId('role:none').setLabel('Leave all').setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setURL('https://example.com/tides')
.setLabel('Tide tables')
.setStyle(ButtonStyle.Link),
);
const boats = new ActionRowBuilder().addComponents(
new StringSelectMenuBuilder()
.setCustomId('boats')
.setPlaceholder('Which boats do you sail?')
.setMinValues(1)
.setMaxValues(2)
.addOptions(
{ label: 'Dinghy', value: 'dinghy' },
{ label: 'Ketch', value: 'ketch', description: 'Two masts' },
{ label: 'Trawler', value: 'trawler' },
),
);
const crew = new ActionRowBuilder().addComponents(
new UserSelectMenuBuilder()
.setCustomId('crew')
.setPlaceholder('Who sails with you?')
.setMaxValues(3),
);
await channel.send({ content: 'Pick your harbor roles:', components: [roles, boats, crew] });class HarborRoles(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(discord.ui.Button(label="Tide tables", url="https://example.com/tides"))
@discord.ui.button(label="Sailor", emoji="⛵", style=discord.ButtonStyle.primary, custom_id="role:sailor")
async def sailor(self, interaction: discord.Interaction, button: discord.ui.Button):
... # see "Handle a press"
@discord.ui.select(
custom_id="boats",
placeholder="Which boats do you sail?",
min_values=1,
max_values=2,
options=[
discord.SelectOption(label="Dinghy", value="dinghy"),
discord.SelectOption(label="Ketch", value="ketch", description="Two masts"),
discord.SelectOption(label="Trawler", value="trawler"),
],
)
async def boats(self, interaction: discord.Interaction, select: discord.ui.Select):
...
@discord.ui.select(cls=discord.ui.UserSelect, custom_id="crew", placeholder="Who sails with you?", max_values=3)
async def crew(self, interaction: discord.Interaction, select: discord.ui.UserSelect):
...
await channel.send("Pick your harbor roles:", view=HarborRoles())With timeout=None and a custom_id on every item but the link, discord.py keeps the view working
after a restart once you register it with client.add_view(HarborRoles()) in setup_hook.
The message comes back with its components, each with a numeric id that Klang fills in when
you don’t send one. The first row of the answer:
{
"type": 1,
"id": 1,
"components": [
{
"type": 2,
"id": 2,
"emoji": { "id": null, "name": "⛵" },
"label": "Sailor",
"style": 1,
"custom_id": "role:sailor"
},
{ "type": 2, "id": 3, "label": "Fisher", "style": 3, "custom_id": "role:fisher" },
{ "type": 2, "id": 4, "label": "Report", "style": 2, "custom_id": "report" },
{ "type": 2, "id": 5, "label": "Leave all", "style": 4, "custom_id": "role:none" },
{ "type": 2, "id": 6, "url": "https://example.com/tides", "label": "Tide tables", "style": 5 }
]
}Buttons
style |
Name | Looks like | Sends an interaction |
|---|---|---|---|
1 |
Primary | Klang’s accent color. | Yes, with its custom_id. |
2 |
Secondary | A neutral button. | Yes. |
3 |
Success | Green. | Yes. |
4 |
Danger | Red. | Yes. |
5 |
Link | Neutral, with an arrow. Opens url. |
No: it has a url and no custom_id. |
A button needs a label (up to 80 characters), an emoji or both. disabled: true shows it
dimmed, and nobody can press it. Klang doesn’t sell anything through apps, so style 6 (a
purchase) is refused.
Select menus
type |
Menu | What people choose |
|---|---|---|
3 |
Text | Among your options: up to 25, each with a label, a value and, if you like, a description, an emoji and default. |
5 |
User | Members of the server, or the other person in a direct message. |
6 |
Role | Roles of the server. |
7 |
Mentionable | Members and roles. |
8 |
Channel | Channels the person can see, filtered by channel_types if you send it. |
min_values and max_values say how many can be chosen (by default, one), up to 25, and
placeholder is the text shown before anything is chosen. In the user, role, mentionable and
channel menus, default_values preselects some: [{ "id": "…", "type": "user" }], with user,
role or channel.
In Klang, a menu that takes one value sends it as soon as the person picks it. One that takes several sends the choice when it closes.
Handle a press
When someone presses a button or chooses in a menu, your bot gets an interaction of type 3
(MESSAGE_COMPONENT), by the gateway as
INTERACTION_CREATE or at your
interactions endpoint URL, exactly like a command. In data:
| Field | What it is |
|---|---|
custom_id |
The custom_id of the button or menu. |
component_type |
2 a button, or the menu’s type. |
values |
Menus only: the chosen values, or the IDs of the people, roles or channels. |
resolved |
User, role, mentionable and channel menus: the full objects behind values, under users, members, roles and channels. |
The interaction also carries message, the message the component is on, with its content even
without the Message content intent, and the usual member or user, channel, locale and
token.
What your bot got when Leo chose Nora in the menu of people:
{
"custom_id": "crew",
"component_type": 5,
"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"
}
}
}
}The libraries turn these into their own objects:
import { Events, MessageFlags } from 'discord.js';
client.on(Events.InteractionCreate, async (interaction) => {
if (interaction.isButton() && interaction.customId === 'role:sailor') {
await interaction.update({
content: `Pick your harbor roles: ${interaction.user.displayName} is now a sailor. ⛵`,
});
}
if (interaction.isStringSelectMenu() && interaction.customId === 'boats') {
await interaction.deferUpdate();
// …slow work…
await interaction.editReply({
content: `Pick your harbor roles: ${interaction.user.displayName} sails ${interaction.values.join(' and ')}.`,
});
}
if (interaction.isUserSelectMenu() && interaction.customId === 'crew') {
const names = interaction.users.map((user) => user.displayName).join(', ');
await interaction.reply({ content: `You sail with ${names}.`, flags: MessageFlags.Ephemeral });
}
});class HarborRoles(discord.ui.View):
# The same __init__ and decorators as above; these are the callbacks’ bodies.
async def sailor(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(
content=f"Pick your harbor roles: {interaction.user.display_name} is now a sailor. ⛵"
)
async def boats(self, interaction: discord.Interaction, select: discord.ui.Select):
await interaction.response.defer()
# …slow work…
await interaction.edit_original_response(
content=f"Pick your harbor roles: {interaction.user.display_name} sails {' and '.join(select.values)}."
)
async def crew(self, interaction: discord.Interaction, select: discord.ui.UserSelect):
names = ", ".join(user.display_name for user in select.values)
await interaction.response.send_message(f"You sail with {names}.", ephemeral=True)Answer a press
A press has the same clock as a command: the first answer within 3 seconds, and the token works for 15 minutes. Besides a new message, your bot can change the message the component is on:
| Callback | What it does | discord.js | discord.py |
|---|---|---|---|
7 |
Updates the message, with the body of an edit. What you don’t send stays. | update() |
response.edit_message() |
6 |
Says “got it” and nothing else. Edit the message later with PATCH …/messages/@original, within the 15 minutes. |
deferUpdate(), editReply() |
response.defer(), edit_original_response() |
4 |
Sends a new message, ephemeral or not. | reply() |
response.send_message() |
5 |
Defers a new message: the person sees that your bot is thinking. | deferReply() |
response.defer(thinking=True) |
9 |
Opens a modal. | showModal() |
response.send_modal() |
After a 6 or a 7, @original is the message the component is on, as in Discord. A 7 can
remove the components (components: []), change them, or add files. The message
your bot sends with a 4 is an ordinary message (type 0, without the line that says who used a
command), with interaction_metadata of type 3 and interacted_message_id, the message that
was pressed.
The person sees the pressed control waiting, with three dots, until your answer arrives. With a
7 or a 6 and its edit, the message changes in place; with a 5, a “thinking” line appears
below. If your bot doesn’t answer within 3 seconds, the person reads The application didn’t
respond. under the components.
Components work in ephemeral messages too: only the
person who sees the message can press them, and a 7 updates it where it is.
Layout components
With the IS_COMPONENTS_V2 flag (1 << 15, 32768), the components are the message. A tide
report in a box with a colored bar, a thumbnail beside the title, a gallery, a file and a button:
import {
ButtonBuilder,
ButtonStyle,
ContainerBuilder,
MessageFlags,
SeparatorSpacingSize,
} from 'discord.js';
const card = new ContainerBuilder()
.setAccentColor(0x2b6cb0)
.addSectionComponents((section) =>
section
.addTextDisplayComponents(
(text) => text.setContent('## North Pier\nHigh tide at **06:42** and **18:57**.'),
(text) => text.setContent('-# Updated every morning at 05:00.'),
)
.setThumbnailAccessory((thumbnail) =>
thumbnail.setURL('attachment://north-pier.png').setDescription('The north pier at dawn'),
),
)
.addSeparatorComponents((separator) => separator.setSpacing(SeparatorSpacingSize.Small))
.addTextDisplayComponents((text) =>
text.setContent('Low tide at 12:48 (0.6 m). Small craft advisory after 16:00.'),
)
.addMediaGalleryComponents((gallery) =>
gallery.addItems(
(item) => item.setURL('attachment://monday.png').setDescription('Monday'),
(item) => item.setURL('attachment://tuesday.png').setDescription('Tuesday'),
),
)
.addFileComponents((file) => file.setURL('attachment://tides-week.pdf'))
.addActionRowComponents((row) =>
row.addComponents(
new ButtonBuilder()
.setCustomId('tides:refresh')
.setLabel('Refresh')
.setStyle(ButtonStyle.Secondary),
),
);
await channel.send({
flags: MessageFlags.IsComponentsV2,
components: [card],
files: ['north-pier.png', 'monday.png', 'tuesday.png', 'tides-week.pdf'],
});class TideCard(discord.ui.LayoutView):
card = discord.ui.Container(
discord.ui.Section(
"## North Pier\nHigh tide at **06:42** and **18:57**.",
"-# Updated every morning at 05:00.",
accessory=discord.ui.Thumbnail("attachment://north-pier.png", description="The north pier at dawn"),
),
discord.ui.Separator(),
discord.ui.TextDisplay("Low tide at 12:48 (0.6 m). Small craft advisory after 16:00."),
discord.ui.MediaGallery(
discord.MediaGalleryItem("attachment://monday.png", description="Monday"),
discord.MediaGalleryItem("attachment://tuesday.png", description="Tuesday"),
),
discord.ui.File("attachment://tides-week.pdf"),
discord.ui.ActionRow(discord.ui.Button(label="Refresh", custom_id="tides:refresh")),
accent_colour=0x2B6CB0,
)
files = [discord.File(name) for name in ("north-pier.png", "monday.png", "tuesday.png", "tides-week.pdf")]
await channel.send(view=TideCard(), files=files)discord.py sets the flag on its own when you send a LayoutView.
type |
Component | What it shows | Where it goes |
|---|---|---|---|
10 |
Text display | Markdown, like a message’s text, mentions included. | The message, a container, a section. |
9 |
Section | 1 to 3 text displays with a thumbnail or a button beside them (accessory). |
The message, a container. |
11 |
Thumbnail | A small image. description is its alt text; spoiler hides it. |
Only as a section’s accessory. |
12 |
Media gallery | 1 to 10 images (items, each with media, description and spoiler). |
The message, a container. |
13 |
File | One file of the message, as a download card. | The message, a container. |
14 |
Separator | Space between blocks: spacing 1 (small) or 2 (large), with a line unless divider is false. |
The message, a container. |
17 |
Container | A box around other components, with an accent_color bar if you give one; spoiler hides it all. |
The message. |
1 |
Action row | Buttons or a select menu, as in an ordinary message. | The message, a container. |
The rules of a v2 message:
- No
content,embeds, stickers or polls. Sending them with the flag is50035. - Up to 40 components, counting the ones inside others, and up to 4,000 characters of text displays in all.
- The flag stays. An edit can set it on a message, but never take it away (
50035onflags). An edit withoutflagskeeps what the message has. - Only the files the components show are shown. A file the message has but no thumbnail, gallery or file component names is kept, but not displayed.
Images (media.url) are attachment:// and the name of one of the message’s
files, or an https address on the Internet, which
Klang loads through its image proxy and gives back with proxy_url. Addresses on Discord’s image
servers are refused. A file component takes only attachment://. In the answer, each piece of
media comes back filled in, with url, proxy_url, content_type, attachment_id and, for
images, width and height; a file component adds the file’s name and size.
People find v2 messages with Klang’s search by the text of their text displays, as they find
other messages by their content. The labels of buttons and the options of menus aren’t
searched.
What Klang checks for you
When your bot sends components, Klang checks every limit and rule in the
reference and answers 400 with 50035 and the path of
what’s wrong, the way libraries show it:
{
"code": 50035,
"message": "The request body isn’t valid.",
"errors": {
"components": {
"0": {
"components": {
"1": {
"custom_id": {
"_errors": [{ "code": "INVALID", "message": "Custom IDs must be unique." }]
}
}
}
}
}
}
}When someone presses, Klang checks the press against the message as your bot last saved it, before your bot hears anything:
- the person can see the channel, isn’t timed out, and meets the server’s verification level;
- the message still exists, and your bot is still in the server and can see the channel;
- the
custom_idis on that message, with that type, isn’t disabled and isn’t a link button; - the values of a menu are among its
options, there are betweenmin_valuesandmax_valuesof them, and each person, role or channel is one the person can see there (a member of the server, a role of the server, a channel they can open, of the menu’schannel_types).
So the custom_id and values your bot gets always come from its own message. Anyone who can see
the message can press it, though: if a button does something only some people should do, check
the member and its permissions in your bot.
When a check fails, your bot gets nothing. The person sees That button or menu isn’t available any more. (a component that isn’t there, is disabled, or a message or bot that’s gone) or That choice isn’t one of the options. (values that don’t fit). A person can press 20 times every 10 seconds; more waits.
Not supported
- Buttons that sell something (style
6, withsku_id): Klang has no paid apps. - Incoming webhooks ignore
components, as before. Your app’s webhook, with an interaction’s token, takes them.
Differences from Discord’s API has the rest.