Browse Source

Merge branch 'master' into feat/community-invite

pull/10386/head
Soheab 4 months ago
parent
commit
ad69fb837f
  1. 4
      discord/app_commands/commands.py
  2. 6
      discord/app_commands/models.py
  3. 7
      discord/app_commands/tree.py
  4. 12
      discord/channel.py
  5. 362
      discord/components.py
  6. 4
      discord/enums.py
  7. 4
      discord/ext/commands/cog.py
  8. 34
      discord/interactions.py
  9. 10
      discord/message.py
  10. 24
      discord/permissions.py
  11. 3
      discord/threads.py
  12. 62
      discord/types/components.py
  13. 51
      discord/types/interactions.py
  14. 2
      discord/ui/__init__.py
  15. 391
      discord/ui/checkbox.py
  16. 3
      discord/ui/item.py
  17. 246
      discord/ui/radio.py
  18. 6
      discord/ui/select.py
  19. 17
      discord/ui/view.py
  20. 38
      discord/webhook/async_.py
  21. 37
      discord/webhook/sync.py
  22. 1
      docs/api.rst
  23. 93
      docs/interactions/api.rst
  24. 13
      pyproject.toml

4
discord/app_commands/commands.py

@ -1802,7 +1802,7 @@ class Group:
yield from command.walk_commands() yield from command.walk_commands()
@mark_overrideable @mark_overrideable
async def on_error(self, interaction: Interaction, error: AppCommandError, /) -> None: async def on_error(self, interaction: Interaction[ClientT], error: AppCommandError, /) -> None:
"""|coro| """|coro|
A callback that is called when a child's command raises an :exc:`AppCommandError`. A callback that is called when a child's command raises an :exc:`AppCommandError`.
@ -1850,7 +1850,7 @@ class Group:
self.on_error = coro # type: ignore self.on_error = coro # type: ignore
return coro return coro
async def interaction_check(self, interaction: Interaction, /) -> bool: async def interaction_check(self, interaction: Interaction[ClientT], /) -> bool:
"""|coro| """|coro|
A callback that is called when an interaction happens within the group A callback that is called when an interaction happens within the group

6
discord/app_commands/models.py

@ -597,8 +597,7 @@ class AppCommandChannel(Hashable):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this channel. A value of ``0`` denotes that it is disabled. in this channel. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~discord.Permissions.manage_channels` or Bots and users with :attr:`~discord.Permissions.bypass_slowmode` bypass slowmode.
:attr:`~discord.Permissions.manage_messages` bypass slowmode.
.. versionadded:: 2.6 .. versionadded:: 2.6
nsfw: :class:`bool` nsfw: :class:`bool`
@ -779,8 +778,7 @@ class AppCommandThread(Hashable):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this thread. A value of ``0`` denotes that it is disabled. in this thread. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~discord.Permissions.manage_channels` or Bots and users with :attr:`~discord.Permissions.bypass_slowmode` bypass slowmode.
:attr:`~discord.Permissions.manage_messages` bypass slowmode.
.. versionadded:: 2.6 .. versionadded:: 2.6
message_count: :class:`int` message_count: :class:`int`

7
discord/app_commands/tree.py

@ -1289,7 +1289,12 @@ class CommandTree(Generic[ClientT]):
await command._invoke_autocomplete(interaction, focused, namespace) await command._invoke_autocomplete(interaction, focused, namespace)
except Exception: except Exception:
# Suppress exception since it can't be handled anyway. # Suppress exception since it can't be handled anyway.
_log.exception('Ignoring exception in autocomplete for %r', command.qualified_name) _log.exception(
'Ignoring exception in autocomplete for %r (Guild: %s, User: %s)',
command.qualified_name,
interaction.guild_id,
interaction.user.id,
)
return return

12
discord/channel.py

@ -322,8 +322,7 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this channel. A value of ``0`` denotes that it is disabled. in this channel. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or Bots and users with :attr:`~Permissions.bypass_slowmode` bypass slowmode.
:attr:`~Permissions.manage_messages` bypass slowmode.
nsfw: :class:`bool` nsfw: :class:`bool`
If the channel is marked as "not safe for work" or "age restricted". If the channel is marked as "not safe for work" or "age restricted".
default_auto_archive_duration: :class:`int` default_auto_archive_duration: :class:`int`
@ -1516,8 +1515,7 @@ class VoiceChannel(VocalGuildChannel):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this channel. A value of ``0`` denotes that it is disabled. in this channel. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or Bots and users with :attr:`~Permissions.bypass_slowmode` bypass slowmode.
:attr:`~Permissions.manage_messages` bypass slowmode.
.. versionadded:: 2.2 .. versionadded:: 2.2
""" """
@ -1744,8 +1742,7 @@ class StageChannel(VocalGuildChannel):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this channel. A value of ``0`` denotes that it is disabled. in this channel. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or Bots and users with :attr:`~Permissions.bypass_slowmode` bypass slowmode.
:attr:`~Permissions.manage_messages` bypass slowmode.
.. versionadded:: 2.2 .. versionadded:: 2.2
""" """
@ -2409,8 +2406,7 @@ class ForumChannel(discord.abc.GuildChannel, Hashable):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between creating threads The number of seconds a member must wait between creating threads
in this forum. A value of ``0`` denotes that it is disabled. in this forum. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or Bots and users with :attr:`~Permissions.bypass_slowmode` bypass slowmode.
:attr:`~Permissions.manage_messages` bypass slowmode.
nsfw: :class:`bool` nsfw: :class:`bool`
If the forum is marked as "not safe for work" or "age restricted". If the forum is marked as "not safe for work" or "age restricted".
default_auto_archive_duration: :class:`int` default_auto_archive_duration: :class:`int`

362
discord/components.py

@ -73,6 +73,11 @@ if TYPE_CHECKING:
UnfurledMediaItem as UnfurledMediaItemPayload, UnfurledMediaItem as UnfurledMediaItemPayload,
LabelComponent as LabelComponentPayload, LabelComponent as LabelComponentPayload,
FileUploadComponent as FileUploadComponentPayload, FileUploadComponent as FileUploadComponentPayload,
RadioGroupComponent as RadioGroupComponentPayload,
RadioGroupOption as RadioGroupOptionPayload,
CheckboxGroupComponent as CheckboxGroupComponentPayload,
CheckboxGroupOption as CheckboxGroupOptionPayload,
CheckboxComponent as CheckboxComponentPayload,
) )
from .emoji import Emoji from .emoji import Emoji
@ -92,6 +97,7 @@ if TYPE_CHECKING:
'SectionComponent', 'SectionComponent',
'Component', 'Component',
] ]
OptionPayload = Union[SelectOptionPayload, RadioGroupOptionPayload, CheckboxGroupOptionPayload]
__all__ = ( __all__ = (
@ -114,6 +120,11 @@ __all__ = (
'SeparatorComponent', 'SeparatorComponent',
'LabelComponent', 'LabelComponent',
'FileUploadComponent', 'FileUploadComponent',
'RadioGroupComponent',
'CheckboxGroupComponent',
'CheckboxComponent',
'RadioGroupOption',
'CheckboxGroupOption',
) )
@ -170,6 +181,71 @@ class Component:
raise NotImplementedError raise NotImplementedError
class BaseOption:
"""Represents a base option for components that have options.
This currently implements:
- :class:`SelectOption`
- :class:`RadioGroupOption`
- :class:`CheckboxGroupOption`
.. versionadded:: 2.7
"""
__slots__: Tuple[str, ...] = ('label', 'value', 'description', 'default')
__repr_info__: ClassVar[Tuple[str, ...]] = ('label', 'value', 'description', 'default')
def __init__(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
default: bool = False,
) -> None:
self.label: str = label
self.value: str = label if value is MISSING else value
self.description: Optional[str] = description
self.default: bool = default
def __repr__(self) -> str:
attrs = ' '.join(f'{key}={getattr(self, key)!r}' for key in self.__repr_info__)
return f'<{self.__class__.__name__} {attrs}>'
def __str__(self) -> str:
base = self.label
if self.description:
return f'{base}\n{self.description}'
return base
@classmethod
def from_dict(cls, data: OptionPayload) -> Self:
return cls(
label=data['label'],
value=data['value'],
description=data.get('description'),
default=data.get('default', False),
)
def to_dict(self) -> OptionPayload:
payload: OptionPayload = {
'label': self.label,
'value': self.value,
'default': self.default,
}
if self.description:
payload['description'] = self.description
return payload
def copy(self) -> Self:
return self.__class__.from_dict(self.to_dict())
class ActionRow(Component): class ActionRow(Component):
"""Represents a Discord Bot UI Kit Action Row. """Represents a Discord Bot UI Kit Action Row.
@ -416,7 +492,7 @@ class SelectMenu(Component):
return payload return payload
class SelectOption: class SelectOption(BaseOption):
"""Represents a select menu's option. """Represents a select menu's option.
These can be created by users. These can be created by users.
@ -454,13 +530,8 @@ class SelectOption:
Whether this option is selected by default. Whether this option is selected by default.
""" """
__slots__: Tuple[str, ...] = ( __slots__: Tuple[str, ...] = BaseOption.__slots__ + ('_emoji',)
'label', __repr_info__ = BaseOption.__repr_info__ + ('emoji',)
'value',
'description',
'_emoji',
'default',
)
def __init__( def __init__(
self, self,
@ -471,18 +542,9 @@ class SelectOption:
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None, emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
default: bool = False, default: bool = False,
) -> None: ) -> None:
self.label: str = label super().__init__(label=label, value=value, description=description, default=default)
self.value: str = label if value is MISSING else value
self.description: Optional[str] = description
self.emoji = emoji self.emoji = emoji
self.default: bool = default
def __repr__(self) -> str:
return (
f'<SelectOption label={self.label!r} value={self.value!r} description={self.description!r} '
f'emoji={self.emoji!r} default={self.default!r}>'
)
def __str__(self) -> str: def __str__(self) -> str:
if self.emoji: if self.emoji:
@ -512,7 +574,7 @@ class SelectOption:
self._emoji = None self._emoji = None
@classmethod @classmethod
def from_dict(cls, data: SelectOptionPayload) -> SelectOption: def from_dict(cls, data: SelectOptionPayload) -> Self:
try: try:
emoji = PartialEmoji.from_dict(data['emoji']) # pyright: ignore[reportTypedDictNotRequiredAccess] emoji = PartialEmoji.from_dict(data['emoji']) # pyright: ignore[reportTypedDictNotRequiredAccess]
except KeyError: except KeyError:
@ -522,28 +584,18 @@ class SelectOption:
label=data['label'], label=data['label'],
value=data['value'], value=data['value'],
description=data.get('description'), description=data.get('description'),
emoji=emoji,
default=data.get('default', False), default=data.get('default', False),
emoji=emoji,
) )
def to_dict(self) -> SelectOptionPayload: def to_dict(self) -> SelectOptionPayload:
payload: SelectOptionPayload = { payload: SelectOptionPayload = super().to_dict() # type: ignore
'label': self.label,
'value': self.value,
'default': self.default,
}
if self.emoji: if self.emoji:
payload['emoji'] = self.emoji.to_dict() payload['emoji'] = self.emoji.to_dict()
if self.description:
payload['description'] = self.description
return payload return payload
def copy(self) -> SelectOption:
return self.__class__.from_dict(self.to_dict())
class TextInput(Component): class TextInput(Component):
"""Represents a text input from the Discord Bot UI Kit. """Represents a text input from the Discord Bot UI Kit.
@ -1453,6 +1505,248 @@ class FileUploadComponent(Component):
return payload return payload
class RadioGroupComponent(Component):
"""Represents a radio group component from the Discord Bot UI Kit.
This inherits from :class:`Component`.
.. note::
The user constructible and usable type for creating a radio group is
:class:`discord.ui.RadioGroup` not this one.
.. versionadded:: 2.7
Attributes
------------
custom_id: Optional[:class:`str`]
The ID of the component that gets received during an interaction.
id: Optional[:class:`int`]
The ID of this component.
required: :class:`bool`
Whether the component is required.
Defaults to ``True``.
options: List[:class:`RadioGroupOption`]
A list of options that can be selected in this group.
"""
__slots__: Tuple[str, ...] = ('custom_id', 'required', 'id', 'options')
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: RadioGroupComponentPayload, /) -> None:
self.custom_id: str = data['custom_id']
self.required: bool = data.get('required', True)
self.id: Optional[int] = data.get('id')
self.options: List[RadioGroupOption] = [RadioGroupOption.from_dict(option) for option in data.get('options', [])]
@property
def type(self) -> Literal[ComponentType.radio_group]:
""":class:`ComponentType`: The type of component."""
return ComponentType.radio_group
def to_dict(self) -> RadioGroupComponentPayload:
payload: RadioGroupComponentPayload = {
'type': self.type.value,
'custom_id': self.custom_id,
'required': self.required,
}
if self.id is not None:
payload['id'] = self.id
if self.options:
payload['options'] = [option.to_dict() for option in self.options]
return payload
class RadioGroupOption(BaseOption):
"""Represents a radio group's option
These can be created by users.
.. versionadded:: 2.7
Parameters
-----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the label.
Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
default: :class:`bool`
Whether this option is selected by default.
Attributes
-----------
label: :class:`str`
The label of the option. This is displayed to users.
value: :class:`str`
The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the
label.
description: Optional[:class:`str`]
An additional description of the option, if any.
default: :class:`bool`
Whether this option is selected by default.
"""
class CheckboxGroupComponent(Component):
"""Represents a checkbox group component from the Discord Bot UI Kit.
This inherits from :class:`Component`.
.. note::
The user constructible and usable type for creating a checkbox group is
:class:`discord.ui.CheckboxGroup` not this one.
.. versionadded:: 2.7
Attributes
------------
custom_id: Optional[:class:`str`]
The ID of the component that gets received during an interaction.
id: Optional[:class:`int`]
The ID of this component.
required: :class:`bool`
Whether the component is required.
Defaults to ``True``.
min_values: :class:`int`
The minimum number of options that must be selected in this component.
Must be between 0 and 10. Defaults to 0.
max_values: :class:`int`
The maximum number of options that can be selected in this component.
Must be between 1 and 10. Defaults to 1.
options: List[:class:`CheckboxGroupOption`]
A list of options that can be selected in this group.
"""
__slots__: Tuple[str, ...] = ('custom_id', 'required', 'id', 'min_values', 'max_values', 'options')
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: CheckboxGroupComponentPayload, /) -> None:
self.custom_id: str = data['custom_id']
self.required: bool = data.get('required', True)
self.id: Optional[int] = data.get('id')
self.min_values: int = data.get('min_values', 0)
self.max_values: int = data.get('max_values', 1)
self.options: List[CheckboxGroupOption] = [
CheckboxGroupOption.from_dict(option) for option in data.get('options', [])
]
@property
def type(self) -> Literal[ComponentType.checkbox_group]:
""":class:`ComponentType`: The type of component."""
return ComponentType.checkbox_group
def to_dict(self) -> CheckboxGroupComponentPayload:
payload: CheckboxGroupComponentPayload = {
'type': self.type.value,
'custom_id': self.custom_id,
'min_values': self.min_values,
'max_values': self.max_values,
'required': self.required,
}
if self.id is not None:
payload['id'] = self.id
if self.options:
payload['options'] = [option.to_dict() for option in self.options]
return payload
class CheckboxGroupOption(BaseOption):
"""Represents a checkbox group's option
These can be created by users.
.. versionadded:: 2.7
Parameters
-----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the label.
Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
default: :class:`bool`
Whether this option is selected by default.
Attributes
-----------
label: :class:`str`
The label of the option. This is displayed to users.
value: :class:`str`
The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the
label.
description: Optional[:class:`str`]
An additional description of the option, if any.
default: :class:`bool`
Whether this option is selected by default.
"""
class CheckboxComponent(Component):
"""Represents a checkbox component from the Discord Bot UI Kit.
This inherits from :class:`Component`.
.. note::
The user constructible and usable type for creating a checkbox is
:class:`discord.ui.Checkbox` not this one.
.. versionadded:: 2.7
Attributes
------------
custom_id: Optional[:class:`str`]
The ID of the component that gets received during an interaction.
id: Optional[:class:`int`]
The ID of this component.
default: :class:`bool`
Whether this checkbox is selected by default.
"""
__slots__: Tuple[str, ...] = ('custom_id', 'default', 'id')
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__
def __init__(self, data: CheckboxComponentPayload, /) -> None:
self.custom_id: str = data['custom_id']
self.id: Optional[int] = data.get('id')
self.default: bool = data.get('default', False)
@property
def type(self) -> Literal[ComponentType.checkbox]:
""":class:`ComponentType`: The type of component."""
return ComponentType.checkbox
def to_dict(self) -> CheckboxComponentPayload:
payload: CheckboxComponentPayload = {
'type': self.type.value,
'custom_id': self.custom_id,
'default': self.default,
}
if self.id is not None:
payload['id'] = self.id
return payload
def _component_factory(data: ComponentPayload, state: Optional[ConnectionState] = None) -> Optional[Component]: def _component_factory(data: ComponentPayload, state: Optional[ConnectionState] = None) -> Optional[Component]:
if data['type'] == 1: if data['type'] == 1:
return ActionRow(data) return ActionRow(data)
@ -1480,3 +1774,9 @@ def _component_factory(data: ComponentPayload, state: Optional[ConnectionState]
return LabelComponent(data, state) return LabelComponent(data, state)
elif data['type'] == 19: elif data['type'] == 19:
return FileUploadComponent(data) return FileUploadComponent(data)
elif data['type'] == 21:
return RadioGroupComponent(data)
elif data['type'] == 22:
return CheckboxGroupComponent(data)
elif data['type'] == 23:
return CheckboxComponent(data)

4
discord/enums.py

@ -695,6 +695,10 @@ class ComponentType(Enum):
container = 17 container = 17
label = 18 label = 18
file_upload = 19 file_upload = 19
# checkpoint = 20
radio_group = 21
checkbox_group = 22
checkbox = 23
def __int__(self) -> int: def __int__(self) -> int:
return self.value return self.value

4
discord/ext/commands/cog.py

@ -646,7 +646,9 @@ class Cog(metaclass=CogMeta):
pass pass
@_cog_special_method @_cog_special_method
async def cog_app_command_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError) -> None: async def cog_app_command_error(
self, interaction: discord.Interaction[ClientT], error: app_commands.AppCommandError
) -> None:
"""|coro| """|coro|
A special method that is called whenever an error within A special method that is called whenever an error within

34
discord/interactions.py

@ -65,6 +65,8 @@ if TYPE_CHECKING:
ApplicationCommandInteractionData, ApplicationCommandInteractionData,
InteractionCallback as InteractionCallbackPayload, InteractionCallback as InteractionCallbackPayload,
InteractionCallbackActivity as InteractionCallbackActivityPayload, InteractionCallbackActivity as InteractionCallbackActivityPayload,
MessageComponentInteractionData,
ModalSubmitInteractionData,
) )
from .types.webhook import ( from .types.webhook import (
Webhook as WebhookPayload, Webhook as WebhookPayload,
@ -191,6 +193,8 @@ class Interaction(Generic[ClientT]):
'channel', 'channel',
'_cs_namespace', '_cs_namespace',
'_cs_command', '_cs_command',
'_cs_command_id',
'_cs_custom_id',
) )
def __init__(self, *, data: InteractionPayload, state: ConnectionState[ClientT]): def __init__(self, *, data: InteractionPayload, state: ConnectionState[ClientT]):
@ -376,6 +380,21 @@ class Interaction(Generic[ClientT]):
else: else:
return tree._get_context_menu(data) return tree._get_context_menu(data)
@utils.cached_slot_property('_cs_command_id')
def command_id(self) -> Optional[int]:
"""Optional[:class:`int`]: The ID of the command that triggered this interaction.
Only applicable if :attr:`type` is one of, :attr:`InteractionType.application_command` or
:attr:`InteractionType.autocomplete`.
.. versionadded:: 2.7
"""
if self.type not in (InteractionType.application_command, InteractionType.autocomplete):
return None
data: ApplicationCommandInteractionData = self.data # type: ignore
return int(data.get('id', 0))
@utils.cached_slot_property('_cs_response') @utils.cached_slot_property('_cs_response')
def response(self) -> InteractionResponse[ClientT]: def response(self) -> InteractionResponse[ClientT]:
""":class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction. """:class:`InteractionResponse`: Returns an object responsible for handling responding to the interaction.
@ -405,6 +424,21 @@ class Interaction(Generic[ClientT]):
""":class:`datetime.datetime`: When the interaction expires.""" """:class:`datetime.datetime`: When the interaction expires."""
return self.created_at + datetime.timedelta(minutes=15) return self.created_at + datetime.timedelta(minutes=15)
@utils.cached_slot_property('_cs_custom_id')
def custom_id(self) -> Optional[str]:
"""Optional[:class:`str`]: The custom ID of the component that triggered this interaction.
Only applicable if :attr:`type` is one of, :attr:`InteractionType.component` or
:attr:`InteractionType.modal_submit`.
.. versionadded:: 2.7
"""
if self.type not in (InteractionType.component, InteractionType.modal_submit):
return None
data: Union[MessageComponentInteractionData, ModalSubmitInteractionData] = self.data # type: ignore
return data.get('custom_id')
def is_expired(self) -> bool: def is_expired(self) -> bool:
""":class:`bool`: Returns ``True`` if the interaction is expired.""" """:class:`bool`: Returns ``True`` if the interaction is expired."""
return utils.utcnow() >= self.expires_at return utils.utcnow() >= self.expires_at

10
discord/message.py

@ -1453,7 +1453,7 @@ class PartialMessage(Hashable):
Pins the message. Pins the message.
You must have :attr:`~Permissions.manage_messages` to do You must have :attr:`~Permissions.pin_messages` to do
this in a non-private channel context. this in a non-private channel context.
Parameters Parameters
@ -1471,7 +1471,7 @@ class PartialMessage(Hashable):
The message or channel was not found or deleted. The message or channel was not found or deleted.
HTTPException HTTPException
Pinning the message failed, probably due to the channel Pinning the message failed, probably due to the channel
having more than 50 pinned messages. having more than 250 pinned messages.
""" """
await self._state.http.pin_message(self.channel.id, self.id, reason=reason) await self._state.http.pin_message(self.channel.id, self.id, reason=reason)
@ -1483,7 +1483,7 @@ class PartialMessage(Hashable):
Unpins the message. Unpins the message.
You must have :attr:`~Permissions.manage_messages` to do You must have :attr:`~Permissions.pin_messages` to do
this in a non-private channel context. this in a non-private channel context.
Parameters Parameters
@ -2221,6 +2221,7 @@ class Message(PartialMessage, Hashable):
self.application_id: Optional[int] = utils._get_as_snowflake(data, 'application_id') self.application_id: Optional[int] = utils._get_as_snowflake(data, 'application_id')
self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])] self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])]
self.message_snapshots: List[MessageSnapshot] = MessageSnapshot._from_value(state, data.get('message_snapshots')) self.message_snapshots: List[MessageSnapshot] = MessageSnapshot._from_value(state, data.get('message_snapshots'))
self.call: Optional[CallMessage] = None
# Set by Messageable.pins # Set by Messageable.pins
self._pinned_at: Optional[datetime.datetime] = None self._pinned_at: Optional[datetime.datetime] = None
@ -2513,11 +2514,8 @@ class Message(PartialMessage, Hashable):
self.interaction_metadata = MessageInteractionMetadata(state=self._state, guild=self.guild, data=data) self.interaction_metadata = MessageInteractionMetadata(state=self._state, guild=self.guild, data=data)
def _handle_call(self, data: CallMessagePayload): def _handle_call(self, data: CallMessagePayload):
self.call: Optional[CallMessage]
if data is not None: if data is not None:
self.call = CallMessage(state=self._state, message=self, data=data) self.call = CallMessage(state=self._state, message=self, data=data)
else:
self.call = None
def _rebind_cached_references( def _rebind_cached_references(
self, self,

24
discord/permissions.py

@ -95,6 +95,7 @@ if TYPE_CHECKING:
create_polls: BoolOrNoneT create_polls: BoolOrNoneT
use_external_apps: BoolOrNoneT use_external_apps: BoolOrNoneT
pin_messages: BoolOrNoneT pin_messages: BoolOrNoneT
bypass_slowmode: BoolOrNoneT
class _PermissionsKwargs(_BasePermissionsKwargs[bool]): ... class _PermissionsKwargs(_BasePermissionsKwargs[bool]): ...
@ -253,7 +254,7 @@ class Permissions(BaseFlags):
permissions set to ``True``. permissions set to ``True``.
""" """
# Some of these are 0 because we don't want to set unnecessary bits # Some of these are 0 because we don't want to set unnecessary bits
return cls(0b0000_0000_0000_1111_0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111) return cls(0b0000_0000_0001_1111_0111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111)
@classmethod @classmethod
def _timeout_mask(cls) -> int: def _timeout_mask(cls) -> int:
@ -273,6 +274,7 @@ class Permissions(BaseFlags):
base.create_public_threads = False base.create_public_threads = False
base.manage_threads = False base.manage_threads = False
base.send_messages_in_threads = False base.send_messages_in_threads = False
base.bypass_slowmode = False
return base return base
@classmethod @classmethod
@ -326,8 +328,11 @@ class Permissions(BaseFlags):
.. versionchanged:: 2.4 .. versionchanged:: 2.4
Added :attr:`send_polls`, :attr:`send_voice_messages`, attr:`use_external_sounds`, Added :attr:`send_polls`, :attr:`send_voice_messages`, attr:`use_external_sounds`,
:attr:`use_embedded_activities`, and :attr:`use_external_apps` permissions. :attr:`use_embedded_activities`, and :attr:`use_external_apps` permissions.
.. versionchanged:: 2.7
Added :attr:`pin_messages` and :attr:`bypass_slowmode` permissions.
""" """
return cls(0b0000_0000_0000_1110_0110_0100_1111_1101_1011_0011_1111_0111_1111_1111_0101_0001) return cls(0b0000_0000_0001_1110_0110_0100_1111_1101_1011_0011_1111_0111_1111_1111_0101_0001)
@classmethod @classmethod
def general(cls) -> Self: def general(cls) -> Self:
@ -377,9 +382,9 @@ class Permissions(BaseFlags):
Added :attr:`send_polls` and :attr:`use_external_apps` permissions. Added :attr:`send_polls` and :attr:`use_external_apps` permissions.
.. versionchanged:: 2.7 .. versionchanged:: 2.7
Added :attr:`pin_messages` permission. Added :attr:`pin_messages` and :attr:`bypass_slowmode` permissions.
""" """
return cls(0b0000_0000_0000_1110_0100_0000_0111_1100_1000_0000_0000_0111_1111_1000_0100_0000) return cls(0b0000_0000_0001_1110_0100_0000_0111_1100_1000_0000_0000_0111_1111_1000_0100_0000)
@classmethod @classmethod
def voice(cls) -> Self: def voice(cls) -> Self:
@ -577,7 +582,7 @@ class Permissions(BaseFlags):
@flag_value @flag_value
def manage_messages(self) -> int: def manage_messages(self) -> int:
""":class:`bool`: Returns ``True`` if a user can delete messages or bypass slowmode in a text channel. """:class:`bool`: Returns ``True`` if a user can delete messages in a text channel.
.. note:: .. note::
@ -884,6 +889,14 @@ class Permissions(BaseFlags):
""" """
return 1 << 51 return 1 << 51
@flag_value
def bypass_slowmode(self) -> int:
""":class:`bool`: Returns ``True`` if a user can bypass slowmode.
.. versionadded:: 2.7
"""
return 1 << 52
def _augment_from_permissions(cls): def _augment_from_permissions(cls):
cls.VALID_NAMES = set(Permissions.VALID_FLAGS) cls.VALID_NAMES = set(Permissions.VALID_FLAGS)
@ -1009,6 +1022,7 @@ class PermissionOverwrite:
create_polls: Optional[bool] create_polls: Optional[bool]
use_external_apps: Optional[bool] use_external_apps: Optional[bool]
pin_messages: Optional[bool] pin_messages: Optional[bool]
bypass_slowmode: Optional[bool]
def __init__(self, **kwargs: Unpack[_PermissionOverwriteKwargs]) -> None: def __init__(self, **kwargs: Unpack[_PermissionOverwriteKwargs]) -> None:
self._values: Dict[str, Optional[bool]] = {} self._values: Dict[str, Optional[bool]] = {}

3
discord/threads.py

@ -103,8 +103,7 @@ class Thread(Messageable, Hashable):
slowmode_delay: :class:`int` slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages The number of seconds a member must wait between sending messages
in this thread. A value of ``0`` denotes that it is disabled. in this thread. A value of ``0`` denotes that it is disabled.
Bots and users with :attr:`~Permissions.manage_channels` or Bots and users with :attr:`~Permissions.bypass_slowmode` bypass slowmode.
:attr:`~Permissions.manage_messages` bypass slowmode.
message_count: :class:`int` message_count: :class:`int`
An approximate number of messages in this thread. An approximate number of messages in this thread.
member_count: :class:`int` member_count: :class:`int`

62
discord/types/components.py

@ -30,7 +30,7 @@ from typing_extensions import NotRequired
from .emoji import PartialEmoji from .emoji import PartialEmoji
from .channel import ChannelType from .channel import ChannelType
ComponentType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 19] ComponentType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18, 19, 21, 22, 23]
ButtonStyle = Literal[1, 2, 3, 4, 5, 6] ButtonStyle = Literal[1, 2, 3, 4, 5, 6]
TextStyle = Literal[1, 2] TextStyle = Literal[1, 2]
DefaultValueType = Literal['user', 'role', 'channel'] DefaultValueType = Literal['user', 'role', 'channel']
@ -43,6 +43,13 @@ class ComponentBase(TypedDict):
type: int type: int
class OptionBase(TypedDict):
label: str
value: str
default: NotRequired[bool]
description: NotRequired[str]
class ActionRow(ComponentBase): class ActionRow(ComponentBase):
type: Literal[1] type: Literal[1]
components: List[ActionRowChildComponent] components: List[ActionRowChildComponent]
@ -59,11 +66,7 @@ class ButtonComponent(ComponentBase):
sku_id: NotRequired[str] sku_id: NotRequired[str]
class SelectOption(TypedDict): class SelectOption(OptionBase):
label: str
value: str
default: bool
description: NotRequired[str]
emoji: NotRequired[PartialEmoji] emoji: NotRequired[PartialEmoji]
@ -192,7 +195,7 @@ class LabelComponent(ComponentBase):
type: Literal[18] type: Literal[18]
label: str label: str
description: NotRequired[str] description: NotRequired[str]
component: Union[SelectMenu, TextInput, FileUploadComponent] component: LabelChildComponent
class FileUploadComponent(ComponentBase): class FileUploadComponent(ComponentBase):
@ -203,6 +206,34 @@ class FileUploadComponent(ComponentBase):
required: NotRequired[bool] required: NotRequired[bool]
class RadioGroupComponent(ComponentBase):
type: Literal[21]
custom_id: str
options: NotRequired[List[RadioGroupOption]]
required: NotRequired[bool]
RadioGroupOption = OptionBase
class CheckboxGroupComponent(ComponentBase):
type: Literal[22]
custom_id: str
options: NotRequired[List[CheckboxGroupOption]]
max_values: NotRequired[int]
min_values: NotRequired[int]
required: NotRequired[bool]
CheckboxGroupOption = OptionBase
class CheckboxComponent(ComponentBase):
type: Literal[23]
custom_id: str
default: NotRequired[bool]
ActionRowChildComponent = Union[ButtonComponent, SelectMenu, TextInput] ActionRowChildComponent = Union[ButtonComponent, SelectMenu, TextInput]
ContainerChildComponent = Union[ ContainerChildComponent = Union[
ActionRow, ActionRow,
@ -211,8 +242,21 @@ ContainerChildComponent = Union[
FileComponent, FileComponent,
SectionComponent, SectionComponent,
SectionComponent, SectionComponent,
ContainerComponent,
SeparatorComponent, SeparatorComponent,
ThumbnailComponent, ThumbnailComponent,
] ]
Component = Union[ActionRowChildComponent, LabelComponent, FileUploadComponent, ContainerChildComponent] LabelChildComponent = Union[
TextInput,
SelectMenu,
FileUploadComponent,
RadioGroupComponent,
CheckboxGroupComponent,
CheckboxComponent,
]
Component = Union[
ActionRowChildComponent,
LabelComponent,
LabelChildComponent,
ContainerChildComponent,
ContainerComponent,
]

51
discord/types/interactions.py

@ -27,7 +27,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Literal, TypedDict, Union, Optional from typing import TYPE_CHECKING, Dict, List, Literal, TypedDict, Union, Optional
from typing_extensions import NotRequired from typing_extensions import NotRequired
from .channel import ChannelTypeWithoutThread, GuildChannel, InteractionDMChannel, GroupDMChannel from .channel import (
ChannelTypeWithoutThread,
GuildChannel,
InteractionDMChannel,
GroupDMChannel,
)
from .sku import Entitlement from .sku import Entitlement
from .threads import ThreadType, ThreadMetadata from .threads import ThreadType, ThreadMetadata
from .member import Member from .member import Member
@ -223,14 +228,40 @@ class ModalSubmitFileUploadInteractionData(ComponentBase):
values: List[str] values: List[str]
ModalSubmitComponentItemInteractionData = Union[ class ModalSubmitRadioGroupInteractionData(ComponentBase):
ModalSubmitSelectInteractionData, ModalSubmitTextInputInteractionData, ModalSubmitFileUploadInteractionData type: Literal[21]
custom_id: str
id: int
value: Optional[str]
class ModalSubmitCheckboxGroupInteractionData(ComponentBase):
type: Literal[22]
custom_id: str
id: int
values: List[str]
class ModalSubmitCheckboxInteractionData(ComponentBase):
type: Literal[23]
custom_id: str
id: int
value: bool
ModalSubmitLabelComponentItemInteractionData = Union[
ModalSubmitSelectInteractionData,
ModalSubmitTextInputInteractionData,
ModalSubmitFileUploadInteractionData,
ModalSubmitRadioGroupInteractionData,
ModalSubmitCheckboxGroupInteractionData,
ModalSubmitCheckboxInteractionData,
] ]
class ModalSubmitActionRowInteractionData(TypedDict): class ModalSubmitActionRowInteractionData(TypedDict):
type: Literal[1] type: Literal[1]
components: List[ModalSubmitComponentItemInteractionData] components: List[ModalSubmitTextInputInteractionData]
class ModalSubmitTextDisplayInteractionData(ComponentBase): class ModalSubmitTextDisplayInteractionData(ComponentBase):
@ -240,7 +271,7 @@ class ModalSubmitTextDisplayInteractionData(ComponentBase):
class ModalSubmitLabelInteractionData(ComponentBase): class ModalSubmitLabelInteractionData(ComponentBase):
type: Literal[18] type: Literal[18]
component: ModalSubmitComponentItemInteractionData component: ModalSubmitLabelComponentItemInteractionData
ModalSubmitComponentInteractionData = Union[ ModalSubmitComponentInteractionData = Union[
@ -301,7 +332,12 @@ class ModalSubmitInteraction(_BaseInteraction):
data: ModalSubmitInteractionData data: ModalSubmitInteractionData
Interaction = Union[PingInteraction, ApplicationCommandInteraction, MessageComponentInteraction, ModalSubmitInteraction] Interaction = Union[
PingInteraction,
ApplicationCommandInteraction,
MessageComponentInteraction,
ModalSubmitInteraction,
]
class MessageInteraction(TypedDict): class MessageInteraction(TypedDict):
@ -349,7 +385,8 @@ class MessageComponentMessageInteractionMetadata(_MessageInteractionMetadata):
class ModalSubmitMessageInteractionMetadata(_MessageInteractionMetadata): class ModalSubmitMessageInteractionMetadata(_MessageInteractionMetadata):
type: Literal[5] type: Literal[5]
triggering_interaction_metadata: Union[ triggering_interaction_metadata: Union[
ApplicationCommandMessageInteractionMetadata, MessageComponentMessageInteractionMetadata ApplicationCommandMessageInteractionMetadata,
MessageComponentMessageInteractionMetadata,
] ]

2
discord/ui/__init__.py

@ -26,3 +26,5 @@ from .thumbnail import *
from .action_row import * from .action_row import *
from .label import * from .label import *
from .file_upload import * from .file_upload import *
from .radio import *
from .checkbox import *

391
discord/ui/checkbox.py

@ -0,0 +1,391 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypeVar, Dict
import os
from ..utils import MISSING
from ..components import CheckboxGroupComponent, CheckboxComponent, CheckboxGroupOption
from ..enums import ComponentType
from .item import Item
if TYPE_CHECKING:
from typing_extensions import Self
from ..interactions import Interaction
from ..types.interactions import (
ModalSubmitCheckboxGroupInteractionData as ModalSubmitCheckboxGroupInteractionDataPayload,
ModalSubmitCheckboxInteractionData as ModalSubmitCheckboxInteractionDataPayload,
)
from ..types.components import (
CheckboxGroupComponent as CheckboxGroupComponentPayload,
CheckboxComponent as CheckboxComponentPayload,
)
from .view import BaseView
from ..app_commands.namespace import ResolveKey
# fmt: off
__all__ = (
'CheckboxGroup',
'Checkbox',
)
# fmt: on
V = TypeVar('V', bound='BaseView', covariant=True)
class CheckboxGroup(Item[V]):
"""Represents a checkbox group component within a modal.
.. versionadded:: 2.7
Parameters
------------
id: Optional[:class:`int`]
The ID of the component. This must be unique across the view.
custom_id: Optional[:class:`str`]
The custom ID of the component.
options: List[:class:`discord.CheckboxGroupOption`]
A list of options that can be selected in this checkbox group.
Can only contain up to 10 items.
max_values: Optional[:class:`int`]
The maximum number of options that can be selected in this component.
Must be between 1 and 10. Defaults to 1.
min_values: Optional[:class:`int`]
The minimum number of options that must be selected in this component.
Must be between 0 and 10. Defaults to 0.
required: :class:`bool`
Whether this component is required to be filled before submitting the modal.
Defaults to ``True``.
"""
__item_repr_attributes__: Tuple[str, ...] = (
'id',
'custom_id',
'options',
'required',
)
def __init__(
self,
*,
custom_id: str = MISSING,
required: bool = True,
min_values: Optional[int] = None,
max_values: Optional[int] = None,
options: List[CheckboxGroupOption] = MISSING,
id: Optional[int] = None,
) -> None:
super().__init__()
self._provided_custom_id = custom_id is not MISSING
custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id
if not isinstance(custom_id, str):
raise TypeError(f'expected custom_id to be str not {custom_id.__class__.__name__}')
self._underlying: CheckboxGroupComponent = CheckboxGroupComponent._raw_construct(
id=id,
custom_id=custom_id,
required=required,
options=options or [],
min_values=min_values,
max_values=max_values,
)
self.id = id
self._values: List[str] = []
@property
def id(self) -> Optional[int]:
"""Optional[:class:`int`]: The ID of this component."""
return self._underlying.id
@id.setter
def id(self, value: Optional[int]) -> None:
self._underlying.id = value
@property
def values(self) -> List[str]:
"""List[:class:`str`]: A list of values that have been selected by the user."""
return self._values
@property
def custom_id(self) -> str:
""":class:`str`: The ID of the component that gets received during an interaction."""
return self._underlying.custom_id
@custom_id.setter
def custom_id(self, value: str) -> None:
if not isinstance(value, str):
raise TypeError('custom_id must be a str')
self._underlying.custom_id = value
self._provided_custom_id = True
@property
def type(self) -> Literal[ComponentType.checkbox_group]:
""":class:`.ComponentType`: The type of this component."""
return ComponentType.checkbox_group
@property
def options(self) -> List[CheckboxGroupOption]:
"""List[:class:`discord.CheckboxGroupOption`]: A list of options that can be selected in this menu."""
return self._underlying.options
@options.setter
def options(self, value: List[CheckboxGroupOption]) -> None:
if not isinstance(value, list) or not all(isinstance(obj, CheckboxGroupOption) for obj in value):
raise TypeError('options must be a list of CheckboxGroupOption')
self._underlying.options = value
@property
def min_values(self) -> int:
""":class:`int`: The minimum number of options that must be selected before submitting the modal."""
return self._underlying.min_values
@min_values.setter
def min_values(self, value: int) -> None:
self._underlying.min_values = int(value)
@property
def max_values(self) -> int:
""":class:`int`: The maximum number of options that can be selected before submitting the modal."""
return self._underlying.max_values
@max_values.setter
def max_values(self, value: int) -> None:
self._underlying.max_values = int(value)
def add_option(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
default: bool = False,
) -> None:
"""Adds an option to the checkbox group.
To append a pre-existing :class:`discord.CheckboxGroupOption` use the
:meth:`append_option` method instead.
Parameters
-----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not given, defaults to the label.
Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
default: :class:`bool`
Whether this option is selected by default.
Raises
-------
ValueError
The number of options exceeds 10.
"""
option = CheckboxGroupOption(
label=label,
value=value,
description=description,
default=default,
)
self.append_option(option)
def append_option(self, option: CheckboxGroupOption) -> None:
"""Appends an option to the checkbox group.
Parameters
-----------
option: :class:`discord.CheckboxGroupOption`
The option to append to the checkbox group.
Raises
-------
ValueError
The number of options exceeds 10.
"""
if len(self._underlying.options) >= 10:
raise ValueError('maximum number of options already provided (10)')
self._underlying.options.append(option)
@property
def required(self) -> bool:
""":class:`bool`: Whether the component is required or not."""
return self._underlying.required
@required.setter
def required(self, value: bool) -> None:
self._underlying.required = bool(value)
@property
def width(self) -> int:
return 5
def to_component_dict(self) -> CheckboxGroupComponentPayload:
return self._underlying.to_dict()
def _refresh_component(self, component: CheckboxGroupComponent) -> None:
self._underlying = component
def _handle_submit(
self, interaction: Interaction, data: ModalSubmitCheckboxGroupInteractionDataPayload, resolved: Dict[ResolveKey, Any]
) -> None:
self._values = data.get('values', [])
@classmethod
def from_component(cls, component: CheckboxGroupComponent) -> Self:
self = cls(
id=component.id,
custom_id=component.custom_id,
options=component.options,
required=component.required,
min_values=component.min_values,
max_values=component.max_values,
)
return self
def is_dispatchable(self) -> bool:
return False
class Checkbox(Item[V]):
"""Represents a checkbox component within a modal.
.. versionadded:: 2.7
Parameters
------------
id: Optional[:class:`int`]
The ID of the component. This must be unique across the view.
custom_id: Optional[:class:`str`]
The custom ID of the component.
default: :class:`bool`
Whether this checkbox is selected by default.
"""
__item_repr_attributes__: Tuple[str, ...] = (
'id',
'custom_id',
'default',
)
def __init__(
self,
*,
custom_id: str = MISSING,
default: bool = False,
id: Optional[int] = None,
) -> None:
super().__init__()
self._provided_custom_id = custom_id is not MISSING
custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id
if not isinstance(custom_id, str):
raise TypeError(f'expected custom_id to be str not {custom_id.__class__.__name__}')
self._underlying: CheckboxComponent = CheckboxComponent._raw_construct(
id=id,
custom_id=custom_id,
default=default,
)
self.id = id
self._value: bool = default
@property
def id(self) -> Optional[int]:
"""Optional[:class:`int`]: The ID of this component."""
return self._underlying.id
@id.setter
def id(self, value: Optional[int]) -> None:
self._underlying.id = value
@property
def value(self) -> bool:
""":class:`bool`: ``True`` if this checkbox was selected, otherwise ``False``."""
return self._value
@property
def custom_id(self) -> str:
""":class:`str`: The ID of the component that gets received during an interaction."""
return self._underlying.custom_id
@custom_id.setter
def custom_id(self, value: str) -> None:
if not isinstance(value, str):
raise TypeError('custom_id must be a str')
self._underlying.custom_id = value
self._provided_custom_id = True
@property
def type(self) -> Literal[ComponentType.checkbox]:
""":class:`.ComponentType`: The type of this component."""
return ComponentType.checkbox
@property
def default(self) -> bool:
""":class:`bool`: Whether this checkbox is selected by default."""
return self._underlying.default
@default.setter
def default(self, value: bool) -> None:
self._underlying.default = bool(value)
@property
def width(self) -> int:
return 5
def to_component_dict(self) -> CheckboxComponentPayload:
return self._underlying.to_dict()
def _refresh_component(self, component: CheckboxComponent) -> None:
self._underlying = component
def _handle_submit(
self, interaction: Interaction, data: ModalSubmitCheckboxInteractionDataPayload, resolved: Dict[ResolveKey, Any]
) -> None:
self._value = data.get('value', False)
@classmethod
def from_component(cls, component: CheckboxComponent) -> Self:
self = cls(
id=component.id,
custom_id=component.custom_id,
default=component.default,
)
return self
def is_dispatchable(self) -> bool:
return False

3
discord/ui/item.py

@ -87,6 +87,9 @@ class Item(Generic[V]):
- :class:`discord.ui.TextDisplay` - :class:`discord.ui.TextDisplay`
- :class:`discord.ui.Thumbnail` - :class:`discord.ui.Thumbnail`
- :class:`discord.ui.Label` - :class:`discord.ui.Label`
- :class:`discord.ui.RadioGroup`
- :class:`discord.ui.CheckboxGroup`
- :class:`discord.ui.Checkbox`
.. versionadded:: 2.0 .. versionadded:: 2.0
""" """

246
discord/ui/radio.py

@ -0,0 +1,246 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple, TypeVar, Dict
import os
from ..utils import MISSING
from ..components import RadioGroupComponent, RadioGroupOption
from ..enums import ComponentType
from .item import Item
if TYPE_CHECKING:
from typing_extensions import Self
from ..interactions import Interaction
from ..types.interactions import (
ModalSubmitRadioGroupInteractionData as ModalSubmitRadioGroupInteractionDataPayload,
)
from ..types.components import RadioGroupComponent as RadioGroupComponentPayload
from .view import BaseView
from ..app_commands.namespace import ResolveKey
# fmt: off
__all__ = (
'RadioGroup',
)
# fmt: on
V = TypeVar('V', bound='BaseView', covariant=True)
class RadioGroup(Item[V]):
"""Represents a radio group component within a modal.
.. versionadded:: 2.7
Parameters
------------
id: Optional[:class:`int`]
The ID of the component. This must be unique across the view.
custom_id: Optional[:class:`str`]
The custom ID of the component.
options: List[:class:`discord.RadioGroupOption`]
A list of options that can be selected in this radio group.
Can contain between 2 and 10 items.
required: :class:`bool`
Whether this component is required to be filled before submitting the modal.
Defaults to ``True``.
"""
__item_repr_attributes__: Tuple[str, ...] = (
'id',
'custom_id',
'options',
'required',
)
def __init__(
self,
*,
custom_id: str = MISSING,
required: bool = True,
options: List[RadioGroupOption] = MISSING,
id: Optional[int] = None,
) -> None:
super().__init__()
self._provided_custom_id = custom_id is not MISSING
custom_id = os.urandom(16).hex() if custom_id is MISSING else custom_id
if not isinstance(custom_id, str):
raise TypeError(f'expected custom_id to be str not {custom_id.__class__.__name__}')
self._underlying: RadioGroupComponent = RadioGroupComponent._raw_construct(
id=id,
custom_id=custom_id,
required=required,
options=options or [],
)
self.id = id
self._value: Optional[str] = None
@property
def id(self) -> Optional[int]:
"""Optional[:class:`int`]: The ID of this component."""
return self._underlying.id
@id.setter
def id(self, value: Optional[int]) -> None:
self._underlying.id = value
@property
def value(self) -> Optional[str]:
"""Optional[:class:`str`]: The value have been selected by the user, if any."""
return self._value
@property
def custom_id(self) -> str:
""":class:`str`: The ID of the component that gets received during an interaction."""
return self._underlying.custom_id
@custom_id.setter
def custom_id(self, value: str) -> None:
if not isinstance(value, str):
raise TypeError('custom_id must be a str')
self._underlying.custom_id = value
self._provided_custom_id = True
@property
def type(self) -> Literal[ComponentType.radio_group]:
""":class:`.ComponentType`: The type of this component."""
return ComponentType.radio_group
@property
def options(self) -> List[RadioGroupOption]:
"""List[:class:`discord.RadioGroupOption`]: A list of options that can be selected in this radio group."""
return self._underlying.options
@options.setter
def options(self, value: List[RadioGroupOption]) -> None:
if not isinstance(value, list) or not all(isinstance(obj, RadioGroupOption) for obj in value):
raise TypeError('options must be a list of RadioGroupOption')
self._underlying.options = value
def add_option(
self,
*,
label: str,
value: str = MISSING,
description: Optional[str] = None,
default: bool = False,
) -> None:
"""Adds an option to the group.
To append a pre-existing :class:`discord.RadioGroupOption` use the
:meth:`append_option` method instead.
Parameters
-----------
label: :class:`str`
The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str`
The value of the option. This is not displayed to users.
If not given, defaults to the label.
Can only be up to 100 characters.
description: Optional[:class:`str`]
An additional description of the option, if any.
Can only be up to 100 characters.
default: :class:`bool`
Whether this option is selected by default.
Raises
-------
ValueError
The number of options exceeds 10.
"""
option = RadioGroupOption(
label=label,
value=value,
description=description,
default=default,
)
self.append_option(option)
def append_option(self, option: RadioGroupOption) -> None:
"""Appends an option to the group.
Parameters
-----------
option: :class:`discord.RadioGroupOption`
The option to append to the group.
Raises
-------
ValueError
The number of options exceeds 10.
"""
if len(self._underlying.options) >= 10:
raise ValueError('maximum number of options already provided (10)')
self._underlying.options.append(option)
@property
def required(self) -> bool:
""":class:`bool`: Whether the component is required or not."""
return self._underlying.required
@required.setter
def required(self, value: bool) -> None:
self._underlying.required = bool(value)
@property
def width(self) -> int:
return 5
def to_component_dict(self) -> RadioGroupComponentPayload:
return self._underlying.to_dict()
def _refresh_component(self, component: RadioGroupComponent) -> None:
self._underlying = component
def _handle_submit(
self, interaction: Interaction, data: ModalSubmitRadioGroupInteractionDataPayload, resolved: Dict[ResolveKey, Any]
) -> None:
self._value = data.get('value')
@classmethod
def from_component(cls, component: RadioGroupComponent) -> Self:
self = cls(
id=component.id,
custom_id=component.custom_id,
options=component.options,
required=component.required,
)
return self
def is_dispatchable(self) -> bool:
return False

6
discord/ui/select.py

@ -506,10 +506,8 @@ class Select(BaseSelect[V]):
@options.setter @options.setter
def options(self, value: List[SelectOption]) -> None: def options(self, value: List[SelectOption]) -> None:
if not isinstance(value, list): if not isinstance(value, list) or not all(isinstance(obj, SelectOption) for obj in value):
raise TypeError('options must be a list of SelectOption') raise TypeError('options must be a list of SelectOption')
if not all(isinstance(obj, SelectOption) for obj in value):
raise TypeError('all list items must subclass SelectOption')
self._underlying.options = value self._underlying.options = value
@ -576,7 +574,7 @@ class Select(BaseSelect[V]):
""" """
if len(self._underlying.options) >= 25: if len(self._underlying.options) >= 25:
raise ValueError('maximum number of options already provided') raise ValueError('maximum number of options already provided (25)')
self._underlying.options.append(option) self._underlying.options.append(option)

17
discord/ui/view.py

@ -82,6 +82,7 @@ if TYPE_CHECKING:
import re import re
from ..interactions import Interaction from ..interactions import Interaction
from .._types import ClientT
from ..message import Message from ..message import Message
from ..types.components import ComponentBase as ComponentBasePayload from ..types.components import ComponentBase as ComponentBasePayload
from ..types.interactions import ( from ..types.interactions import (
@ -485,7 +486,7 @@ class BaseView:
""" """
return _utils_get(self.walk_children(), id=id) return _utils_get(self.walk_children(), id=id)
async def interaction_check(self, interaction: Interaction, /) -> bool: async def interaction_check(self, interaction: Interaction[ClientT], /) -> bool:
"""|coro| """|coro|
A callback that is called when an interaction happens within the view A callback that is called when an interaction happens within the view
@ -520,7 +521,7 @@ class BaseView:
""" """
pass pass
async def on_error(self, interaction: Interaction, error: Exception, item: Item[Any], /) -> None: async def on_error(self, interaction: Interaction[ClientT], error: Exception, item: Item[Any], /) -> None:
"""|coro| """|coro|
A callback that is called when an item's callback or :meth:`interaction_check` A callback that is called when an item's callback or :meth:`interaction_check`
@ -539,7 +540,7 @@ class BaseView:
""" """
_log.error('Ignoring exception in view %r for item %r', self, item, exc_info=error) _log.error('Ignoring exception in view %r for item %r', self, item, exc_info=error)
async def _scheduled_task(self, item: Item, interaction: Interaction): async def _scheduled_task(self, item: Item[Any], interaction: Interaction[ClientT]):
try: try:
item._refresh_state(interaction, interaction.data) # type: ignore item._refresh_state(interaction, interaction.data) # type: ignore
@ -574,7 +575,7 @@ class BaseView:
self.__stopped.set_result(True) self.__stopped.set_result(True)
asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}') asyncio.create_task(self.on_timeout(), name=f'discord-ui-view-timeout-{self.id}')
def _dispatch_item(self, item: Item, interaction: Interaction) -> Optional[asyncio.Task[None]]: def _dispatch_item(self, item: Item[Any], interaction: Interaction[ClientT]) -> Optional[asyncio.Task[None]]:
if self.__stopped is None or self.__stopped.done(): if self.__stopped is None or self.__stopped.done():
return None return None
@ -935,7 +936,7 @@ class ViewStore:
self, self,
component_type: int, component_type: int,
factory: Type[DynamicItem[Item[Any]]], factory: Type[DynamicItem[Item[Any]]],
interaction: Interaction, interaction: Interaction[ClientT],
custom_id: str, custom_id: str,
match: re.Match[str], match: re.Match[str],
) -> None: ) -> None:
@ -986,7 +987,7 @@ class ViewStore:
except Exception: except Exception:
_log.exception('Ignoring exception in dynamic item callback for %r', item) _log.exception('Ignoring exception in dynamic item callback for %r', item)
def dispatch_dynamic_items(self, component_type: int, custom_id: str, interaction: Interaction) -> None: def dispatch_dynamic_items(self, component_type: int, custom_id: str, interaction: Interaction[ClientT]) -> None:
for pattern, item in self._dynamic_items.items(): for pattern, item in self._dynamic_items.items():
match = pattern.fullmatch(custom_id) match = pattern.fullmatch(custom_id)
if match is not None: if match is not None:
@ -997,7 +998,7 @@ class ViewStore:
) )
) )
def dispatch_view(self, component_type: int, custom_id: str, interaction: Interaction) -> None: def dispatch_view(self, component_type: int, custom_id: str, interaction: Interaction[ClientT]) -> None:
self.dispatch_dynamic_items(component_type, custom_id, interaction) self.dispatch_dynamic_items(component_type, custom_id, interaction)
interaction_id: Optional[int] = None interaction_id: Optional[int] = None
message_id: Optional[int] = None message_id: Optional[int] = None
@ -1051,7 +1052,7 @@ class ViewStore:
def dispatch_modal( def dispatch_modal(
self, self,
custom_id: str, custom_id: str,
interaction: Interaction, interaction: Interaction[ClientT],
components: List[ModalSubmitComponentInteractionDataPayload], components: List[ModalSubmitComponentInteractionDataPayload],
resolved: ResolvedDataPayload, resolved: ResolvedDataPayload,
) -> None: ) -> None:

38
discord/webhook/async_.py

@ -364,6 +364,7 @@ class AsyncWebhookAdapter:
multipart: Optional[List[Dict[str, Any]]] = None, multipart: Optional[List[Dict[str, Any]]] = None,
files: Optional[Sequence[File]] = None, files: Optional[Sequence[File]] = None,
thread_id: Optional[int] = None, thread_id: Optional[int] = None,
with_components: bool = False,
) -> Response[MessagePayload]: ) -> Response[MessagePayload]:
route = Route( route = Route(
'PATCH', 'PATCH',
@ -372,7 +373,9 @@ class AsyncWebhookAdapter:
webhook_token=token, webhook_token=token,
message_id=message_id, message_id=message_id,
) )
params = None if thread_id is None else {'thread_id': thread_id} params = {'with_components': int(with_components)}
if thread_id:
params['thread_id'] = thread_id
return self.request( return self.request(
route, route,
session=session, session=session,
@ -848,7 +851,15 @@ class WebhookMessage(Message):
See :meth:`.abc.Messageable.send` for more information. See :meth:`.abc.Messageable.send` for more information.
view: Optional[:class:`~discord.ui.View`] view: Optional[:class:`~discord.ui.View`]
The updated view to update this message with. If ``None`` is passed then The updated view to update this message with. If ``None`` is passed then
the view is removed. the view is removed. If the webhook is partial or is not managed by the
library, then you can not send interactable components. Otherwise, you
can send views with any type of components.
.. note::
To update the message to add a :class:`~discord.ui.LayoutView`, you
must explicitly set the ``content``, ``embed``, ``embeds``, and
``attachments`` parameters to either ``None`` or an empty array, as appropriate.
.. versionadded:: 2.0 .. versionadded:: 2.0
@ -1772,7 +1783,7 @@ class Webhook(BaseWebhook):
.. versionadded:: 1.4 .. versionadded:: 1.4
view: Union[:class:`discord.ui.View`, :class:`discord.ui.LayoutView`] view: Union[:class:`discord.ui.View`, :class:`discord.ui.LayoutView`]
The view to send with the message. If the webhook is partial or The view to send with the message. If the webhook is partial or
is not managed by the library, then you can only send URL buttons. is not managed by the library, then you can not send interactable components.
Otherwise, you can send views with any type of components. Otherwise, you can send views with any type of components.
.. versionadded:: 2.0 .. versionadded:: 2.0
@ -1857,12 +1868,10 @@ class Webhook(BaseWebhook):
if view is not MISSING: if view is not MISSING:
if not hasattr(view, '__discord_ui_view__'): if not hasattr(view, '__discord_ui_view__'):
raise TypeError(f'expected view parameter to be of type View not {view.__class__.__name__}') raise TypeError(f'expected view parameter to be of type View or LayoutView, not {view.__class__.__name__}')
if isinstance(self._state, _WebhookState) and view.is_dispatchable(): if isinstance(self._state, _WebhookState) and view.is_dispatchable():
raise ValueError( raise ValueError('Webhook views with interactable components require an associated state with the webhook')
'Webhook views with any component other than URL buttons require an associated state with the webhook'
)
if ephemeral is True and view.timeout is None and view.is_dispatchable(): if ephemeral is True and view.timeout is None and view.is_dispatchable():
view.timeout = 15 * 60.0 view.timeout = 15 * 60.0
@ -2048,8 +2057,9 @@ class Webhook(BaseWebhook):
See :meth:`.abc.Messageable.send` for more information. See :meth:`.abc.Messageable.send` for more information.
view: Optional[Union[:class:`~discord.ui.View`, :class:`~discord.ui.LayoutView`]] view: Optional[Union[:class:`~discord.ui.View`, :class:`~discord.ui.LayoutView`]]
The updated view to update this message with. If ``None`` is passed then The updated view to update this message with. If ``None`` is passed then
the view is removed. The webhook must have state attached, similar to the view is removed. If the webhook is partial or is not managed by the
:meth:`send`. library, then you can not send interactable components. Otherwise, you
can send views with any type of components.
.. note:: .. note::
@ -2085,11 +2095,12 @@ class Webhook(BaseWebhook):
if self.token is None: if self.token is None:
raise ValueError('This webhook does not have a token associated with it') raise ValueError('This webhook does not have a token associated with it')
if view is not MISSING: if view:
if isinstance(self._state, _WebhookState): if not hasattr(view, '__discord_ui_view__'):
raise ValueError('This webhook does not have state associated with it') raise TypeError(f'expected view parameter to be of type View or LayoutView, not {view.__class__.__name__}')
self._state.prevent_view_updates_for(message_id) if isinstance(self._state, _WebhookState) and view.is_dispatchable():
raise ValueError('Webhook views with interactable components require an associated state with the webhook')
previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None)
with handle_message_parameters( with handle_message_parameters(
@ -2117,6 +2128,7 @@ class Webhook(BaseWebhook):
multipart=params.multipart, multipart=params.multipart,
files=params.files, files=params.files,
thread_id=thread_id, thread_id=thread_id,
with_components=bool(view),
) )
message = self._create_message(data, thread=thread) message = self._create_message(data, thread=thread)

37
discord/webhook/sync.py

@ -329,6 +329,7 @@ class WebhookAdapter:
multipart: Optional[List[Dict[str, Any]]] = None, multipart: Optional[List[Dict[str, Any]]] = None,
files: Optional[Sequence[File]] = None, files: Optional[Sequence[File]] = None,
thread_id: Optional[int] = None, thread_id: Optional[int] = None,
with_components: bool = False,
) -> MessagePayload: ) -> MessagePayload:
route = Route( route = Route(
'PATCH', 'PATCH',
@ -337,7 +338,9 @@ class WebhookAdapter:
webhook_token=token, webhook_token=token,
message_id=message_id, message_id=message_id,
) )
params = None if thread_id is None else {'thread_id': thread_id} params = {'with_components': int(with_components)}
if thread_id:
params['thread_id'] = thread_id
return self.request(route, session, payload=payload, multipart=multipart, files=files, params=params) return self.request(route, session, payload=payload, multipart=multipart, files=files, params=params)
def delete_webhook_message( def delete_webhook_message(
@ -415,6 +418,7 @@ class SyncWebhookMessage(Message):
embed: Optional[Embed] = MISSING, embed: Optional[Embed] = MISSING,
attachments: Sequence[Union[Attachment, File]] = MISSING, attachments: Sequence[Union[Attachment, File]] = MISSING,
allowed_mentions: Optional[AllowedMentions] = None, allowed_mentions: Optional[AllowedMentions] = None,
view: Optional[BaseView] = MISSING,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage:
"""Edits the message. """Edits the message.
@ -443,6 +447,19 @@ class SyncWebhookMessage(Message):
allowed_mentions: :class:`AllowedMentions` allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message. Controls the mentions being processed in this message.
See :meth:`.abc.Messageable.send` for more information. See :meth:`.abc.Messageable.send` for more information.
view: Union[:class:`discord.ui.View`, :class:`discord.ui.LayoutView`]
The updated view to update this message with. This can only have non-interactible items, which do not
require a state to be attached to it. If ``None`` is passed then the view is removed.
If you want to edit a webhook message with any component attached to it, check :meth:`WebhookMessage.edit`.
.. note::
To update the message to add a :class:`~discord.ui.LayoutView`, you
must explicitly set the ``content``, ``embed``, ``embeds``, and
``attachments`` parameters to either ``None`` or an empty array, as appropriate.
.. versionadded:: 2.7
Raises Raises
------- -------
@ -451,7 +468,7 @@ class SyncWebhookMessage(Message):
Forbidden Forbidden
Edited a message that is not yours. Edited a message that is not yours.
TypeError TypeError
You specified both ``embed`` and ``embeds`` You specified both ``embed`` and ``embeds``.
ValueError ValueError
The length of ``embeds`` was invalid or The length of ``embeds`` was invalid or
there was no token associated with this webhook. there was no token associated with this webhook.
@ -469,6 +486,7 @@ class SyncWebhookMessage(Message):
attachments=attachments, attachments=attachments,
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
thread=self._state._thread, thread=self._state._thread,
view=view,
) )
def add_files(self, *files: File) -> SyncWebhookMessage: def add_files(self, *files: File) -> SyncWebhookMessage:
@ -1245,6 +1263,12 @@ class SyncWebhook(BaseWebhook):
If you want to edit a webhook message with any component attached to it, check :meth:`WebhookMessage.edit`. If you want to edit a webhook message with any component attached to it, check :meth:`WebhookMessage.edit`.
.. note::
To update the message to add a :class:`~discord.ui.LayoutView`, you
must explicitly set the ``content``, ``embed``, ``embeds``, and
``attachments`` parameters to either ``None`` or an empty array, as appropriate.
.. versionadded:: 2.6 .. versionadded:: 2.6
allowed_mentions: :class:`AllowedMentions` allowed_mentions: :class:`AllowedMentions`
Controls the mentions being processed in this message. Controls the mentions being processed in this message.
@ -1270,6 +1294,13 @@ class SyncWebhook(BaseWebhook):
if self.token is None: if self.token is None:
raise ValueError('This webhook does not have a token associated with it') raise ValueError('This webhook does not have a token associated with it')
if view:
if not hasattr(view, '__discord_ui_view__'):
raise TypeError(f'expected view parameter to be of type View or LayoutView, not {view.__class__.__name__}')
if view.is_dispatchable():
raise ValueError('SyncWebhooks can not send interactable components')
previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None) previous_mentions: Optional[AllowedMentions] = getattr(self._state, 'allowed_mentions', None)
with handle_message_parameters( with handle_message_parameters(
content=content, content=content,
@ -1278,6 +1309,7 @@ class SyncWebhook(BaseWebhook):
embeds=embeds, embeds=embeds,
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions, previous_allowed_mentions=previous_mentions,
view=view,
) as params: ) as params:
thread_id: Optional[int] = None thread_id: Optional[int] = None
if thread is not MISSING: if thread is not MISSING:
@ -1293,6 +1325,7 @@ class SyncWebhook(BaseWebhook):
multipart=params.multipart, multipart=params.multipart,
files=params.files, files=params.files,
thread_id=thread_id, thread_id=thread_id,
with_components=bool(view),
) )
return self._create_message(data, thread=thread) return self._create_message(data, thread=thread)

1
docs/api.rst

@ -5475,6 +5475,7 @@ CategoryChannel
.. autoclass:: CategoryChannel() .. autoclass:: CategoryChannel()
:members: :members:
:inherited-members: :inherited-members:
:exclude-members: category
DMChannel DMChannel
~~~~~~~~~ ~~~~~~~~~

93
docs/interactions/api.rst

@ -202,6 +202,33 @@ FileUploadComponent
:members: :members:
:inherited-members: :inherited-members:
RadioGroupComponent
~~~~~~~~~~~~~~~~~~~
.. attributetable:: RadioGroupComponent
.. autoclass:: RadioGroupComponent()
:members:
:inherited-members:
CheckboxComponent
~~~~~~~~~~~~~~~~~
.. attributetable:: CheckboxComponent
.. autoclass:: CheckboxComponent()
:members:
:inherited-members:
CheckboxGroupComponent
~~~~~~~~~~~~~~~~~~~~~~
.. attributetable:: CheckboxGroupComponent
.. autoclass:: CheckboxGroupComponent()
:members:
:inherited-members:
AppCommand AppCommand
~~~~~~~~~~~ ~~~~~~~~~~~
@ -330,6 +357,21 @@ MediaGalleryItem
.. autoclass:: MediaGalleryItem .. autoclass:: MediaGalleryItem
:members: :members:
RadioGroupOption
~~~~~~~~~~~~~~~~
.. attributetable:: RadioGroupOption
.. autoclass:: RadioGroupOption()
:members:
CheckboxGroupOption
~~~~~~~~~~~~~~~~~~~
.. attributetable:: CheckboxGroupOption
.. autoclass:: CheckboxGroupOption()
:members:
Enumerations Enumerations
------------- -------------
@ -494,6 +536,24 @@ Enumerations
Represents a file upload component, usually in a modal. Represents a file upload component, usually in a modal.
.. versionadded:: 2.7 .. versionadded:: 2.7
.. attribute:: radio_group
Represents a radio group component.
.. versionadded:: 2.7
.. attribute:: checkbox_group
Represents a checkbox group component.
.. versionadded:: 2.7
.. attribute:: checkbox
Represents a checkbox component.
.. versionadded:: 2.7
.. class:: ButtonStyle .. class:: ButtonStyle
@ -882,6 +942,39 @@ FileUpload
:inherited-members: :inherited-members:
:exclude-members: callback, interaction_check :exclude-members: callback, interaction_check
RadioGroup
~~~~~~~~~~~
.. attributetable:: discord.ui.RadioGroup
.. autoclass:: discord.ui.RadioGroup
:members:
:inherited-members:
:exclude-members: callback, interaction_check
Checkbox
~~~~~~~~~
.. attributetable:: discord.ui.Checkbox
.. autoclass:: discord.ui.Checkbox
:members:
:inherited-members:
:exclude-members: callback, interaction_check
CheckboxGroup
~~~~~~~~~~~~~~
.. attributetable:: discord.ui.CheckboxGroup
.. autoclass:: discord.ui.CheckboxGroup
:members:
:inherited-members:
:exclude-members: callback, interaction_check
.. _discord_app_commands: .. _discord_app_commands:
Application Commands Application Commands

13
pyproject.toml

@ -89,13 +89,12 @@ packages = [
] ]
include-package-data = true include-package-data = true
[tool.black]
line-length = 125
skip-string-normalization = true
[tool.ruff] [tool.ruff]
line-length = 125 line-length = 125
[tool.ruff.lint.isort]
combine-as-imports = true
[tool.ruff.format] [tool.ruff.format]
line-ending = "lf" line-ending = "lf"
quote-style = "single" quote-style = "single"
@ -113,12 +112,6 @@ exclude_lines = [
"@overload", "@overload",
] ]
[tool.isort]
profile = "black"
combine_as_imports = true
combine_star = true
line_length = 125
[tool.pyright] [tool.pyright]
include = [ include = [
"discord", "discord",

Loading…
Cancel
Save