Components

Components

class discord_ui.Components(client: discord.ext.commands.bot.Bot, override_dpy=True, auto_defer=False)

A class for using and receiving message components in discord

client: discord.Client

The main discord client

override_dpy: bool
Whether some of discord.py’s default methods should be overriden with this libary’s; Default True

For more information see https://github.com/discord-py-ui/discord-ui/blob/main/discord_ui/override.py

auto_defer: Tuple[bool, bool]

Settings for the auto-defer; Default (True, False)

[0]: Whether interactions should be deferred automatically

[1]: Whether the deferration should be hidden (True) or public (False)

Example for using the listener

...
# Your bot declaration should be here
components = Components(client)

for listening to button presses, use

...
@client.event('on_button')
async def on_button(ButtonInteraction):
    ...

for listening to select menu selections, use

...
@client.event('on_select')
async def on_select(seletedMenu):
    ...

For components that will listen to a custom id, use

...
@components.listening_component(custom_id="custom_id_here")
async def my_func(ctx):
    ...
add_listening_component(callback, custom_id, messages=None, users=None, component_type: Optional[Literal['button', 2, 'select', 3]] = None, check: Callable[[Union[discord_ui.components.Component, discord_ui.components.Button, discord_ui.components.SelectMenu]], bool] = empty_check)

Adds a listener to received components

callback: function

The callback function that will be called when the component was received

custom_id: str

The custom_id of the components to listen to

messages: List[discord.Message | int str], Optional

A list of messages or message ids to filter the listening component

users: List[discord.User | discord.Member | int | str], Optional

A list of users or user ids to filter

component_type: str | int

The type of which the component has to be

check: function, Optional
A function that has to return True in order to invoke the listening component

The check function takes to parameters, the component and the message

MissingListenedComponentParameters

The callback for the listening component is missing required parameters

NoAsyncCallback

The callback is not defined with the async keyword

attach_listener_to(target_message, listener)

Attaches a listener to a message after it was sent

target_message: Message

The message to which the listener should be attached

listener: Listener

The listener that will be attached

clear_listeners()

Removes all component listeners

listening_component(custom_id, messages=None, users=None, component_type: Optional[Literal['button', 'select']] = None, check: Callable[[Union[discord_ui.receive.ButtonInteraction, discord_ui.receive.SelectInteraction]], bool] = empty_check)

Decorator for add_listening_component

custom_id: str

The custom_id of the components to listen to

messages: List[discord.Message | int str], Optional

A list of messages or message ids to filter the listening component

users: List[discord.User | discord.Member | int | str], Optional

A list of users or user ids to filter

component_type: Literal['button' | 'select']

What type the used component has to be of (select: SelectMenu, button: Button)

check: function, Optional
A function that has to return True in order to invoke the listening component

The check function takes to parameters, the component and the message

callback: method(ctx)

The asynchron function that will be called if a component with the custom_id was invoked

There will be one parameters passed

ctx: ButtonInteraction or SelectInteraction

The invoked component

Note

ctx is just an example name, you can use whatever you want for it

@ui.components.listening_component("custom_id", [539459006847254542], [53945900682362362])
async def callback(ctx):
    ...
listening_components: Dict[str, List[discord_ui.cogs.ListeningComponent]]

A list of components that are listening for interaction

async put_listener_to(target_message, listener)

Adds a listener to a message and edits it if the components are missing

target_message: Message

The message to which the listener should be attached

listener: Listener

The listener which should be put to the message

remove_listening_component(listening_component)

Removes a listening component

listening_component: ListeningComponent

The listening component which should be removed

remove_listening_components(custom_id)

Removes all listening components for a custom_id

custom_id: str

The custom_id for the listening component

async send(channel, content=..., *, tts=False, embed=..., embeds=..., file=..., files=..., delete_after=..., nonce=..., allowed_mentions=..., reference=..., mention_author=..., components=...) discord_ui.receive.Message

Sends a message to a textchannel

channel: discord.TextChannel | int | str

The target textchannel or the id of it

content: str, optional

The message text content; default None

tts: bool, optional

True if this is a text-to-speech message; default False

embed: discord.Message, optional

Embedded rich content (up to 6000 characters)

embeds: List[discord.Embed], optional

Up to 10 embeds; default None

file: discord.File, optional

A file sent as an attachment to the message; default None

files: List[discord.File], optional

A list of file attachments; default None

delete_after: float, optional

After how many seconds the message should be deleted; default None

nonce: int, optional

The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value; default None

allowed_mentions: discord.AllowedMentions, optional

A list of mentions proceeded in the message; default None

reference: discord.MessageReference | discord.Message, optional

A message to refer to (reply); default None

mention_author: bool, optional

True if the author should be mentioned; default None

components: List[Button | LinkButton | SelectMenu], optional

A list of message components included in this message; default None

WrongType

Channel is not an instance of discord.abc.GuildChannel, discord.abc.PrivateChannel:, :class:`int, str

Message

Returns the sent message

send_webhook(webhook, content=..., *, wait=False, username=..., avatar_url=..., tts=False, files=..., embed=..., embeds=..., allowed_mentions=..., components=...) Optional[discord.webhook.WebhookMessage]

Sends a webhook message

webhook: discord.Webhook

The webhook which will send the message

content: str, optional

the message contents (up to 2000 characters); default None

wait: bool, optional

if True, waits for server confirmation of message send before response, and returns the created message body; default False

username: str, optional

override the default username of the webhook; default None

avatar_url: str, optional

override the default avatar of the webhook; default None

tts: bool, optional

true if this is a TTS message; default False

files: discord.File

A list of files which will be sent as attachment

embed: discord.Embed

Embed rich content, optional

embeds: List[discord.Embed], optional

embedded rich content; default None

allowed_mentions: discord.AllowedMentions, optional

allowed mentions for the message; default None

components: List[Button | LinkButton | SelectMenu], optional

the message components to include with the message; default None

WebhookMessage | None

The message which was sent, if wait was True, else nothing will be returned

import discord
from discord.ext import commands
from discord_ui import Components

client = commands.Bot(" ")
components = Components(client)

Events

We got 3 events to listen for your client

component

This event will be dispatched whenever a component was invoked

A sole parameter will be passed

  • ComponentContext: The used component

@client.listen()
async on_componet(component: ComponentContext):
    ...
await client.wait_for('component', check=lambda com: ...)

button

This event will be dispatched whenever a button was pressed

A sole parameter will be passed:

@client.listen()
def on_button(btn: ButtonInteraction):
    ...
await client.wait_for('button', check=lambda btn: ...)

select

This event will be dispatched whenever a value was selected in a SelectInteraction

A sole paremeter will be passed

@client.listen()
def on_select(menu: SelectInteraction):
    ...
await client.wait_for('select', check=lambda menu: ...)

Components

Button

class discord_ui.Button(label='\u200b', custom_id=None, color='blurple', emoji=None, new_line=False, disabled=False)

A ui-button

custom_id: str, optional
A identifier for the button, max 100 characters

If no custom_id was passed, a random 100 character string will be generated

label: str, optional

Text that appears on the button, max 80 characters; default ​ (“empty” char)

color: str | int, optional

The color of the button; default “blurple”

emoji: discord.Emoji | str, optional

The emoji displayed before the text; default MISSING

new_line: bool, optional

Whether a new line should be added before the button; default False

disabled: bool, optional

Whether the button is disabled; default False

WrongType

A value you want to set is not an instance of a valid type

InvalidLenght

The lenght of a value is not valid

OutOfValidRange

A value is out of its valid range

InvalidArgument

The color you provided is not a valid color alias

LinkButton

class discord_ui.LinkButton(url, label='\u200b', emoji=None, new_line=False, disabled=False)

A ui-button that will open a link when it’s pressed

url: str

A url which will be opened when pressing the button

label: str, optional

Text that appears on the button, max 80 characters; default ​ (“empty” char)

emoji: discord.Emoji | str, optional

Emoji that appears before the label; default MISSING

new_line: bool, optional

Whether a new line should be added before the button; default False

disabled: bool, optional

Whether the button is disabled; default False

WrongType

A value you want to set is not an instance of a valid type

InvalidLenght

The lenght of a value is not valid

OutOfValidRange

A value is out of its valid range

property color: int

The color for the button

property component_type: discord_ui.enums.ComponentType

The component type

property content: str

The complete content in the button (“{emoji} {label}”)

property emoji: str

The mention of the emoji before the text

Note

For setting the emoji, you can use a str or discord.Emoji

property label: str

The label displayed on the button

property url: str

The link which will be opened when the button was pressed

ButtonStyle

class discord_ui.ButtonStyle(value)

An enumeration.

SelectMenu

class discord_ui.SelectMenu(options, custom_id=None, min_values=1, max_values=1, placeholder=None, default=None, disabled=False)

A ui-dropdown selectmenu

options: List[SelectOption]

A list of options to select from

custom_id: str, optional

The custom_id for identifying the menu, max 100 characters

min_values: int, optional

The minimum number of items that must be chosen; default 1, min 0, max 25

max_values: int, optional

The maximum number of items that can be chosen; default 1, max 25

placeholder: str, optional

A custom placeholder text if nothing is selected, max 100 characters; default MISSING

default: int | range, optional

The position of the option that should be selected by default; default MISSING

disabled: bool, optional

Whether the select menu should be disabled or not; default False

property component_type: discord_ui.enums.ComponentType

The component type

property custom_id: str

A custom identifier for this component

property default_options: List[discord_ui.components.SelectOption]

The option selected by default

disabled

Whether the selectmenu is disabled or not

max_values: int

The maximum number of items that can be chosen; default 1, max 25

min_values: int

The minimum number of items that must be chosen; default 1, min 0, max 25

placeholder: str

Custom placeholder text if nothing is selected

set_default_option(position) discord_ui.components.SelectMenu

Selects the default selected option

position: int | range

The position of the option that should be default. If position is of type range, it will iterate through it and disable all components with the index of the indexes.

SelectOption

class discord_ui.SelectOption(value, label='\u200b', description=None, emoji=None, default=False)

An option for a select menu

value: str

The dev-define value of the option, max 100 characters

label: str

The user-facing name of the option, max 25 characters; default ​ (“empty” char)

description: str, optional

An additional description of the option, max 50 characters

emoji: discord.Emoji | str, optional

Emoji appearing before the label; default MISSING

default: bool

Whether this option should be selected by default in the select menu; default False

WrongType

A value you want to set is not an instance of a valid type

InvalidLenght

The lenght of a value is not valid

OutOfValidRange

A value is out of its valid range

property content: str

The complete option content, consisting of the emoji and label

default: bool

Whether this option is selected by default in the menu or not

property description: str

A short description for the option

property emoji: str

The mention of the emoji before the text

Note

For setting the emoji, you can use a str or a discord.Emoji

property label: str

The main text appearing on the option

property value: str

A unique value for the option, which will be usedd to identify the selected value

Interactions

Message

class discord_ui.Message

A discord.Message optimized for components

attach_listener(listener)

Attaches a listener to this message after it was sent

listener: Listener

The listener that should be attached

property buttons: List[Union[discord_ui.components.Button, discord_ui.components.LinkButton]]

The button components in the message

components

The components in the message

async disable_components(index=<discord_ui.tools._All object>, disable=True, **fields)

Disables component(s) in the message

index: int | str | range | List[int | str], optional

Index(es) or custom_id(s) for the components that should be disabled or enabled; default all components

disable: bool, optional

Whether to disable (True) or enable (False) components; default True

**fields

Other parameters for editing the message (like content=, embed=)

async edit(content=..., *, embed=..., embeds=..., attachments=..., suppress=..., delete_after=..., allowed_mentions=..., components=...)

Edits the message and updates its properties

Note

If a paremeter is None, the attribute will be removed from the message

content: str

The new message content

embed: discord.Embed

The new embed of the message

embeds: List[discord.Embed]

The new list of discord embeds

attachments: List[discord.Attachment]

A list of new attachments

supress: bool

Whether the embeds should be shown

delete_after: float

After how many seconds the message should be deleted

allowed_mentions: discord.AllowedMentions

The mentions proceeded in the message

components: List[Button | LinkButton | SelectMenu]

A list of components to be included the message

async put_listener(listener)

Adds a listener to this message and edits the message if the components of the listener are missing in this message

listener: Listener

The listener which should be put to the message

remove_listener()

Removes the listener from this message

property select_menus: List[discord_ui.components.SelectMenu]

The select menus components in the message

async wait_for(event_name: Literal['select', 'button', 'component'], client, custom_id=None, by=None, check=empty_check, timeout=None) Union[discord_ui.receive.ButtonInteraction, discord_ui.receive.SelectInteraction, discord_ui.receive.ComponentContext]

Waits for a message component to be invoked in this message

event_name: str

The name of the event which will be awaited ["select" | "button" | "component"]

Note

event_name must be select for a select menu selection, button for a button press and component for any component

client: discord.ext.commands.Bot

The discord client

custom_id: str, Optional

Filters the waiting for a custom_id

by: discord.User | discord.Member | int | str, Optional

The user or the user id by that has to create the component interaction

check: function, Optional
A check that has to return True in order to break from the event and return the received component

The function takes the received component as the parameter

timeout: float, Optional

After how many seconds the waiting should be canceled. Throws an asyncio.TimeoutError Exception

discord_ui.errors.InvalidEvent

The event name passed was invalid

ButtonInteraction | SelectInteraction

The component that was waited for

# send a message with comoponents
msg = await ctx.send("okay", components=[Button(custom_id="a_custom_id", ...)])
try:
    # wait for the button
    btn = await msg.wait_for("button", client, "a_custom_id", by=ctx.author, timeout=20)
    # send response
    btn.respond()
except asyncio.TimeoutError:
    # no button press was received in 20 seconds timespan

ButtonInteraction

class discord_ui.ButtonInteraction

An interaction that was created by a Button

application_id: int

The ID of the bot application

author: discord.member.Member

The user who pressed the button

property channel: Union[discord.abc.GuildChannel, discord.abc.PrivateChannel]

The channel where the interaction was created

channel_id: int

The channel-id where the interaction was created

component: discord_ui.components.Button

The component that created the interaction

property created_at

The interaction’s creation time in UTC

data: dict

The passed data of the interaction

async defer(hidden=False)

This will acknowledge the interaction. This will show the (Bot is thinking…) Dialog

Note

This function should be used if the bot needs more than 15 seconds to respond

hidden: bool, optional

Whether the loading thing should be only visible to the user; default False.

property guild: discord.guild.Guild

The guild where the interaction was created

guild_id: int

The guild-id where the interaction was created

id: int

The id of the interaction

message: discord_ui.receive.Message

The message in which the interaction was created

async respond(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, nonce=None, allowed_mentions=None, mention_author=None, components=None, delete_after=None, listener=None, hidden=False, ninja_mode=False) Union[Message, EphemeralMessage]

Responds to the interaction

content: str, optional

The raw message content

tts: bool

Whether the message should be send with text-to-speech

embed: discord.Embed

Embed rich content

embeds: List[discord.Embed]

A list of embeds for the message

file: discord.File

The file which will be attached to the message

files: List[discord.File]

A list of files which will be attached to the message

nonce: int

The nonce to use for sending this message

allowed_mentions: discord.AllowedMentions

Controls the mentions being processed in this message

mention_author: bool

Whether the author should be mentioned

components: List[Button | LinkButton | SelectMenu]

A list of message components to be included

delete_after: float

After how many seconds the message should be deleted, only works for non-hiddend messages; default MISSING

listener: Listener

A component-listener for this message

hidden: bool

Whether the response should be visible only to the user

ninja_mode: bool

If true, the client will respond to the button interaction with almost nothing and returns nothing

Message | EphemeralMessage

Returns the sent message

async send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, nonce=None, allowed_mentions=None, mention_author=None, components=None, delete_after=None, listener=None, hidden=False, force=False) Union[discord_ui.receive.Message, discord_ui.receive.EphemeralMessage]

Sends a message to the interaction using a webhook

content: str, optional

The raw message content

tts: bool, optional

Whether the message should be send with text-to-speech

embed: discord.Embed, optional

Embed rich content

embeds: List[discord.Embed], optional

A list of embeds for the message

file: discord.File, optional

The file which will be attached to the message

files: List[discord.File], optional

A list of files which will be attached to the message

nonce: int, optional

The nonce to use for sending this message

allowed_mentions: discord.AllowedMentions, optional

Controls the mentions being processed in this message

mention_author: bool, optional

Whether the author should be mentioned

components: List[Button | LinkButton | SelectMenu]

A list of message components to be included

delete_after: float, optional

After how many seconds the message should be deleted, only works for non-hiddend messages; default MISSING

listener: Listener, optional

A component-listener for this message

hidden: bool, optional

Whether the response should be visible only to the user

ninja_mode: bool, optional

If true, the client will respond to the button interaction with almost nothing and returns nothing

force: bool, optional

Whether sending the follow-up message should be forced. If False, then a follow-up message will only be send if .responded is True; default False

Message | EphemeralMessage

Returns the sent message

token: str

The token for responding to the interaction

type: int

The type of the interaction. See InteractionType for more information

SelectInteraction

class discord_ui.SelectInteraction

An interaction that was created by a SelectMenu

application_id: int

The ID of the bot application

author: discord.member.Member

The user who selected the value

property channel: Union[discord.abc.GuildChannel, discord.abc.PrivateChannel]

The channel where the interaction was created

channel_id: int

The channel-id where the interaction was created

property created_at

The interaction’s creation time in UTC

data: dict

The passed data of the interaction

async defer(hidden=False)

This will acknowledge the interaction. This will show the (Bot is thinking…) Dialog

Note

This function should be used if the bot needs more than 15 seconds to respond

hidden: bool, optional

Whether the loading thing should be only visible to the user; default False.

property guild: discord.guild.Guild

The guild where the interaction was created

guild_id: int

The guild-id where the interaction was created

id: int

The id of the interaction

message: discord_ui.receive.Message

The message in which the interaction was created

async respond(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, nonce=None, allowed_mentions=None, mention_author=None, components=None, delete_after=None, listener=None, hidden=False, ninja_mode=False) Union[Message, EphemeralMessage]

Responds to the interaction

content: str, optional

The raw message content

tts: bool

Whether the message should be send with text-to-speech

embed: discord.Embed

Embed rich content

embeds: List[discord.Embed]

A list of embeds for the message

file: discord.File

The file which will be attached to the message

files: List[discord.File]

A list of files which will be attached to the message

nonce: int

The nonce to use for sending this message

allowed_mentions: discord.AllowedMentions

Controls the mentions being processed in this message

mention_author: bool

Whether the author should be mentioned

components: List[Button | LinkButton | SelectMenu]

A list of message components to be included

delete_after: float

After how many seconds the message should be deleted, only works for non-hiddend messages; default MISSING

listener: Listener

A component-listener for this message

hidden: bool

Whether the response should be visible only to the user

ninja_mode: bool

If true, the client will respond to the button interaction with almost nothing and returns nothing

Message | EphemeralMessage

Returns the sent message

selected_options: List[discord_ui.components.SelectOption]

The list of the selected options

selected_values: List[str]

The list of raw values which were selected

async send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, nonce=None, allowed_mentions=None, mention_author=None, components=None, delete_after=None, listener=None, hidden=False, force=False) Union[discord_ui.receive.Message, discord_ui.receive.EphemeralMessage]

Sends a message to the interaction using a webhook

content: str, optional

The raw message content

tts: bool, optional

Whether the message should be send with text-to-speech

embed: discord.Embed, optional

Embed rich content

embeds: List[discord.Embed], optional

A list of embeds for the message

file: discord.File, optional

The file which will be attached to the message

files: List[discord.File], optional

A list of files which will be attached to the message

nonce: int, optional

The nonce to use for sending this message

allowed_mentions: discord.AllowedMentions, optional

Controls the mentions being processed in this message

mention_author: bool, optional

Whether the author should be mentioned

components: List[Button | LinkButton | SelectMenu]

A list of message components to be included

delete_after: float, optional

After how many seconds the message should be deleted, only works for non-hiddend messages; default MISSING

listener: Listener, optional

A component-listener for this message

hidden: bool, optional

Whether the response should be visible only to the user

ninja_mode: bool, optional

If true, the client will respond to the button interaction with almost nothing and returns nothing

force: bool, optional

Whether sending the follow-up message should be forced. If False, then a follow-up message will only be send if .responded is True; default False

Message | EphemeralMessage

Returns the sent message

token: str

The token for responding to the interaction

type: int

The type of the interaction. See InteractionType for more information

Tools

discord_ui.components_to_dict(components) List[dict]

Converts a list of components to a dict that can be used for other extensions

components: list

A list of components that should be converted.

Example

components_to_dict([Button(...), [LinkButton(...), Button(...)]])
Exception

Invalid data was passed

List[dict]

The converted data