CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-py-cord

A modern, async-ready Python API wrapper for Discord with comprehensive bot development features

Overall
score

93%

Overview
Eval results
Files

ui-components.mddocs/

UI Components and Views

Interactive user interface elements including buttons, select menus, modals, and the view system for creating rich, interactive Discord bot interfaces. These components enable modern, engaging user experiences within Discord.

Capabilities

Views and Component Containers

Views act as containers for UI components and handle their lifecycle and interactions.

class View:
    """
    A container for UI components attached to messages.
    """
    
    def __init__(
        self,
        *,
        timeout: Optional[float] = 180.0,
        disable_on_timeout: bool = False
    ) -> None:
        """
        Create a view.
        
        Parameters:
        - timeout: float - Seconds before the view times out (None for no timeout)
        - disable_on_timeout: bool - Whether to disable components on timeout
        """
    
    @property
    def timeout(self) -> Optional[float]:
        """The view's timeout in seconds."""
    
    @property
    def children(self) -> List[Item]:
        """List of child components."""
    
    def add_item(self, item: Item) -> View:
        """Add a component to the view."""
    
    def remove_item(self, item: Item) -> View:
        """Remove a component from the view."""
    
    def clear_items(self) -> View:
        """Remove all components from the view."""
    
    def get_item(self, custom_id: str) -> Optional[Item]:
        """Get a component by custom ID."""
    
    def disable_all_items(self, *, exclusions: List[Item] = None) -> View:
        """
        Disable all components in the view.
        
        Parameters:
        - exclusions: List[Item] - Components to exclude from disabling
        """
    
    def enable_all_items(self, *, exclusions: List[Item] = None) -> View:
        """
        Enable all components in the view.
        
        Parameters:
        - exclusions: List[Item] - Components to exclude from enabling
        """
    
    def stop(self) -> None:
        """Stop the view and prevent further interactions."""
    
    def is_finished(self) -> bool:
        """Check if the view has finished."""
    
    def is_dispatching(self) -> bool:
        """Check if the view is currently handling interactions."""
    
    def is_persistent(self) -> bool:
        """Check if the view is persistent (survives bot restarts)."""
    
    async def wait(self) -> bool:
        """Wait until the view finishes."""
    
    async def on_timeout(self) -> None:
        """Called when the view times out."""
    
    async def on_error(
        self,
        error: Exception,
        item: Item,
        interaction: Interaction
    ) -> None:
        """
        Called when an error occurs in a component callback.
        
        Parameters:
        - error: Exception - The error that occurred
        - item: Item - The component that caused the error
        - interaction: Interaction - The interaction that caused the error
        """
    
    async def interaction_check(self, interaction: Interaction) -> bool:
        """
        Check if an interaction should be processed.
        
        Parameters:
        - interaction: Interaction - The interaction to check
        
        Returns:
        bool - Whether the interaction should be processed
        """

class Item:
    """
    Base class for all UI components.
    """
    
    @property
    def type(self) -> ComponentType:
        """The component type."""
    
    @property
    def custom_id(self) -> Optional[str]:
        """The component's custom ID."""
    
    @property
    def row(self) -> Optional[int]:
        """The component's row (0-4)."""
    
    @property
    def width(self) -> int:
        """The component's width (1-5 for buttons, 5 for others)."""
    
    @property
    def view(self) -> Optional[View]:
        """The view containing this component."""
    
    def is_dispatching(self) -> bool:
        """Check if the component is handling an interaction."""
    
    def is_persistent(self) -> bool:
        """Check if the component is persistent."""

class Component:
    """
    Represents a Discord message component.
    """
    
    @property
    def type(self) -> ComponentType: ...
    @property
    def custom_id(self) -> Optional[str]: ...
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> Component:
        """Create a component from raw data."""
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert the component to raw data."""

class ActionRow(Component):
    """
    Represents an action row containing components.
    """
    
    def __init__(self, *children: Item) -> None: ...
    
    @property
    def children(self) -> List[Item]: ...
    
    def add_item(self, item: Item) -> ActionRow: ...
    def append_item(self, item: Item) -> ActionRow: ...
    def insert_item(self, index: int, item: Item) -> ActionRow: ...
    def remove_item(self, item: Item) -> ActionRow: ...

Buttons

Interactive button components that users can click to trigger actions.

class Button(Item):
    """
    Represents a button component.
    """
    
    def __init__(
        self,
        *,
        style: ButtonStyle = ButtonStyle.secondary,
        label: Optional[str] = None,
        disabled: bool = False,
        custom_id: Optional[str] = None,
        url: Optional[str] = None,
        emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
        row: Optional[int] = None
    ) -> None:
        """
        Create a button.
        
        Parameters:
        - style: ButtonStyle - Visual style of the button
        - label: str - Button text (required for non-emoji buttons)
        - disabled: bool - Whether the button is disabled
        - custom_id: str - Custom ID for identifying the button
        - url: str - URL for link buttons (style must be link)
        - emoji: Union[str, Emoji, PartialEmoji] - Button emoji
        - row: int - Row to place the button (0-4)
        """
    
    @property
    def style(self) -> ButtonStyle:
        """The button's style."""
    
    @property
    def label(self) -> Optional[str]:
        """The button's label."""
    
    @property
    def disabled(self) -> bool:
        """Whether the button is disabled."""
    
    @property
    def url(self) -> Optional[str]:
        """The button's URL (for link buttons)."""
    
    @property
    def emoji(self) -> Optional[Union[str, Emoji, PartialEmoji]]:
        """The button's emoji."""
    
    async def callback(self, interaction: Interaction) -> None:
        """Called when the button is clicked."""

def button(
    *,
    label: str = None,
    style: ButtonStyle = ButtonStyle.secondary,
    disabled: bool = False,
    custom_id: str = None,
    url: str = None,
    emoji: Union[str, Emoji, PartialEmoji] = None,
    row: int = None
) -> Callable:
    """
    Decorator to create a button component.
    
    Parameters:
    - label: str - Button text
    - style: ButtonStyle - Visual style
    - disabled: bool - Whether disabled
    - custom_id: str - Custom identifier
    - url: str - URL for link buttons
    - emoji: Union[str, Emoji, PartialEmoji] - Button emoji
    - row: int - Button row (0-4)
    """

class ButtonStyle(Enum):
    """Button visual styles."""
    primary = 1      # Blurple
    secondary = 2    # Grey
    success = 3      # Green
    danger = 4       # Red
    link = 5         # Grey, navigates to URL
    
    # Aliases
    blurple = 1
    grey = 2
    gray = 2
    green = 3
    red = 4
    url = 5

Select Menus

Dropdown menus for selecting from predefined options or Discord entities.

class Select(Item):
    """
    Base class for select menu components.
    """
    
    def __init__(
        self,
        *,
        custom_id: str = None,
        placeholder: str = None,
        min_values: int = 1,
        max_values: int = 1,
        disabled: bool = False,
        row: int = None
    ) -> None:
        """
        Create a select menu.
        
        Parameters:
        - custom_id: str - Custom identifier
        - placeholder: str - Placeholder text when nothing is selected
        - min_values: int - Minimum number of selections
        - max_values: int - Maximum number of selections
        - disabled: bool - Whether the select menu is disabled
        - row: int - Row to place the select menu (0-4)
        """
    
    @property
    def placeholder(self) -> Optional[str]:
        """The select menu's placeholder text."""
    
    @property
    def min_values(self) -> int:
        """Minimum number of selections required."""
    
    @property
    def max_values(self) -> int:
        """Maximum number of selections allowed."""
    
    @property
    def disabled(self) -> bool:
        """Whether the select menu is disabled."""
    
    @property
    def values(self) -> List[str]:
        """The currently selected values."""
    
    async def callback(self, interaction: Interaction) -> None:
        """Called when selections are made."""

class SelectMenu(Select):
    """
    String-based select menu with custom options.
    """
    
    def __init__(
        self,
        *,
        options: List[SelectOption] = None,
        **kwargs
    ) -> None:
        """
        Create a string select menu.
        
        Parameters:
        - options: List[SelectOption] - Available options
        """
    
    @property
    def options(self) -> List[SelectOption]:
        """The select menu's options."""
    
    def add_option(
        self,
        *,
        label: str,
        value: str = None,
        description: str = None,
        emoji: Union[str, Emoji, PartialEmoji] = None,
        default: bool = False
    ) -> SelectMenu:
        """Add an option to the select menu."""

class SelectOption:
    """
    Represents an option in a select menu.
    """
    
    def __init__(
        self,
        *,
        label: str,
        value: str = None,
        description: str = None,
        emoji: Union[str, Emoji, PartialEmoji] = None,
        default: bool = False
    ) -> None:
        """
        Create a select option.
        
        Parameters:
        - label: str - Option display text
        - value: str - Option value (defaults to label)
        - description: str - Option description
        - emoji: Union[str, Emoji, PartialEmoji] - Option emoji
        - default: bool - Whether this option is selected by default
        """
    
    @property
    def label(self) -> str: ...
    @property
    def value(self) -> str: ...
    @property
    def description(self) -> Optional[str]: ...
    @property
    def emoji(self) -> Optional[Union[str, Emoji, PartialEmoji]]: ...
    @property
    def default(self) -> bool: ...

# Select Menu Decorators and Specialized Selects
def select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    options: List[SelectOption] = None,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """Decorator to create a string select menu."""

def string_select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    options: List[SelectOption] = None,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """Decorator to create a string select menu."""

def user_select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """
    Decorator to create a user select menu.
    
    Users can select from guild members and the bot user.
    """

def role_select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """
    Decorator to create a role select menu.
    
    Users can select from guild roles.
    """

def mentionable_select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """
    Decorator to create a mentionable select menu.
    
    Users can select from users and roles.
    """

def channel_select(
    *,
    placeholder: str = None,
    custom_id: str = None,
    min_values: int = 1,
    max_values: int = 1,
    channel_types: List[ChannelType] = None,
    disabled: bool = False,
    row: int = None
) -> Callable:
    """
    Decorator to create a channel select menu.
    
    Parameters:
    - channel_types: List[ChannelType] - Types of channels to include
    """

Modals and Text Input

Modal dialogs for collecting text input from users.

class Modal:
    """
    Represents a modal dialog for collecting user input.
    """
    
    def __init__(
        self,
        *children: InputText,
        title: str,
        custom_id: str = None,
        timeout: Optional[float] = None
    ) -> None:
        """
        Create a modal.
        
        Parameters:
        *children: InputText - Text input components
        - title: str - Modal title
        - custom_id: str - Custom identifier
        - timeout: float - Timeout in seconds
        """
    
    @property
    def title(self) -> str:
        """The modal's title."""
    
    @property
    def custom_id(self) -> str:
        """The modal's custom ID."""
    
    @property
    def timeout(self) -> Optional[float]:
        """The modal's timeout."""
    
    @property
    def children(self) -> List[InputText]:
        """The modal's input components."""
    
    def add_item(self, item: InputText) -> Modal:
        """Add an input component to the modal."""
    
    def remove_item(self, item: InputText) -> Modal:
        """Remove an input component from the modal."""
    
    def clear_items(self) -> Modal:
        """Remove all input components."""
    
    def stop(self) -> None:
        """Stop the modal."""
    
    async def callback(self, interaction: Interaction) -> None:
        """
        Called when the modal is submitted.
        
        Parameters:
        - interaction: Interaction - The modal submit interaction
        """
    
    async def on_timeout(self) -> None:
        """Called when the modal times out."""
    
    async def on_error(self, error: Exception, interaction: Interaction) -> None:
        """
        Called when an error occurs.
        
        Parameters:
        - error: Exception - The error that occurred
        - interaction: Interaction - The interaction that caused the error
        """

class InputText(Item):
    """
    Represents a text input field in a modal.
    """
    
    def __init__(
        self,
        *,
        label: str,
        style: InputTextStyle = InputTextStyle.short,
        placeholder: str = None,
        custom_id: str = None,
        value: str = None,
        required: bool = True,
        min_length: int = None,
        max_length: int = None,
        row: int = None
    ) -> None:
        """
        Create a text input.
        
        Parameters:
        - label: str - Input label
        - style: InputTextStyle - Input style (short or long)
        - placeholder: str - Placeholder text
        - custom_id: str - Custom identifier
        - value: str - Pre-filled value
        - required: bool - Whether input is required
        - min_length: int - Minimum input length
        - max_length: int - Maximum input length
        - row: int - Row position (0-4)
        """
    
    @property
    def label(self) -> str:
        """The input's label."""
    
    @property
    def style(self) -> InputTextStyle:
        """The input's style."""
    
    @property
    def placeholder(self) -> Optional[str]:
        """The input's placeholder text."""
    
    @property
    def value(self) -> Optional[str]:
        """The input's current value."""
    
    @property
    def default(self) -> Optional[str]:
        """The input's default value."""
    
    @property
    def required(self) -> bool:
        """Whether the input is required."""
    
    @property
    def min_length(self) -> Optional[int]:
        """Minimum input length."""
    
    @property
    def max_length(self) -> Optional[int]:
        """Maximum input length."""

class InputTextStyle(Enum):
    """Text input styles."""
    short = 1    # Single line input
    long = 2     # Multi-line input (paragraph)
    
    # Aliases
    paragraph = 2

Modal Store for Persistent Modals

Storage system for handling modals across bot restarts.

class ModalStore:
    """
    Stores modal callbacks for persistent modals.
    """
    
    def __init__(self) -> None: ...
    
    def add_modal(self, modal: Modal, *, user_id: int = None) -> None:
        """
        Add a modal to the store.
        
        Parameters:
        - modal: Modal - The modal to store
        - user_id: int - User ID for user-specific modals
        """
    
    def remove_modal(self, custom_id: str, *, user_id: int = None) -> Optional[Modal]:
        """
        Remove a modal from the store.
        
        Parameters:
        - custom_id: str - Modal custom ID
        - user_id: int - User ID for user-specific modals
        """
    
    def get_modal(self, custom_id: str, *, user_id: int = None) -> Optional[Modal]:
        """
        Get a modal from the store.
        
        Parameters:
        - custom_id: str - Modal custom ID
        - user_id: int - User ID for user-specific modals
        """
    
    def clear(self) -> None:
        """Clear all stored modals."""

Component Types and Enumerations

Enumerations for component identification and configuration.

class ComponentType(Enum):
    """Message component types."""
    action_row = 1
    button = 2
    select = 3
    text_input = 4
    user_select = 5
    role_select = 6
    mentionable_select = 7
    channel_select = 8
    
    # Aliases
    string_select = 3

Usage Examples

Example implementations showing common UI patterns:

# Example: Confirmation Dialog
class ConfirmView(discord.ui.View):
    def __init__(self, *, timeout=180):
        super().__init__(timeout=timeout)
        self.value = None

    @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
    async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.value = True
        self.stop()

    @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
    async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.value = False
        self.stop()

# Example: Dropdown Selection
class DropdownView(discord.ui.View):
    @discord.ui.select(
        placeholder="Choose an option...",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(label="Option 1", description="First option"),
            discord.SelectOption(label="Option 2", description="Second option"),
            discord.SelectOption(label="Option 3", description="Third option")
        ]
    )
    async def select_callback(self, select, interaction):
        await interaction.response.send_message(f"You chose {select.values[0]}")

# Example: Modal Form
class FeedbackModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(
            discord.ui.InputText(
                label="Subject",
                placeholder="What is this about?"
            ),
            discord.ui.InputText(
                label="Details", 
                style=discord.InputTextStyle.long,
                placeholder="Please provide more details..."
            ),
            title="Feedback Form",
            *args, **kwargs
        )

    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(
            title="Feedback Received",
            description=f"**Subject:** {self.children[0].value}\n**Details:** {self.children[1].value}",
            color=discord.Color.green()
        )
        await interaction.response.send_message(embed=embed, ephemeral=True)

The UI components system enables rich, interactive Discord applications with modern user interfaces that provide engaging and intuitive user experiences through buttons, select menus, modals, and sophisticated view management.

Install with Tessl CLI

npx tessl i tessl/pypi-py-cord

docs

commands-interactions.md

core-clients.md

discord-objects.md

error-handling.md

extensions.md

index.md

ui-components.md

utilities-helpers.md

tile.json