From 4feb863e06601af840d5f57aee9591fa6aba74b2 Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Sat, 10 Oct 2026 18:48:16 +0200 Subject: [PATCH 1/8] Update old Union[..] syntax to newer | syntax --- discord/abc.py | 27 ++++---- discord/activity.py | 8 +-- discord/asset.py | 2 +- discord/bot.py | 2 +- discord/channel.py | 40 ++++++------ discord/client.py | 16 ++--- discord/cog.py | 6 +- discord/colour.py | 2 +- discord/commands/context.py | 4 +- discord/commands/core.py | 2 +- discord/commands/options.py | 71 ++++++++++----------- discord/components.py | 6 +- discord/embeds.py | 6 +- discord/errors.py | 4 +- discord/ext/bridge/bot.py | 2 +- discord/ext/bridge/context.py | 4 +- discord/ext/bridge/core.py | 2 +- discord/ext/commands/_types.py | 27 ++++---- discord/ext/commands/bot.py | 2 +- discord/ext/commands/cog.py | 4 +- discord/ext/commands/context.py | 10 +-- discord/ext/commands/core.py | 10 +-- discord/ext/commands/errors.py | 12 ++-- discord/ext/commands/flags.py | 4 +- discord/ext/pages/pagination.py | 34 +++++----- discord/ext/tasks/__init__.py | 6 +- discord/file.py | 4 +- discord/guild.py | 39 ++++++------ discord/interactions.py | 32 +++++----- discord/invite.py | 14 ++--- discord/iterators.py | 19 +++--- discord/member.py | 8 +-- discord/message.py | 31 +++++----- discord/monetization.py | 8 +-- discord/object.py | 4 +- discord/onboarding.py | 2 +- discord/player.py | 6 +- discord/poll.py | 8 +-- discord/raw_models.py | 4 +- discord/reaction.py | 4 +- discord/role.py | 2 +- discord/scheduled_events.py | 8 +-- discord/soundboard.py | 2 +- discord/state.py | 3 +- discord/sticker.py | 2 +- discord/threads.py | 8 +-- discord/types/audit_log.py | 34 +++++----- discord/types/channel.py | 22 +++---- discord/types/components.py | 86 +++++++++++++------------- discord/types/integration.py | 4 +- discord/types/interactions.py | 20 +++--- discord/types/invite.py | 4 +- discord/types/snowflake.py | 4 +- discord/types/sticker.py | 4 +- discord/ui/action_row.py | 10 +-- discord/ui/button.py | 6 +- discord/ui/container.py | 8 +-- discord/ui/core.py | 2 +- discord/ui/label.py | 6 +- discord/ui/modal.py | 10 +-- discord/ui/section.py | 4 +- discord/ui/select.py | 8 +-- discord/ui/view.py | 4 +- discord/utils.py | 26 ++++---- discord/voice/client.py | 2 +- discord/welcome_screen.py | 2 +- discord/widget.py | 2 +- examples/app_commands/slash_options.py | 4 +- 68 files changed, 393 insertions(+), 400 deletions(-) diff --git a/discord/abc.py b/discord/abc.py index ee50b5f9f6..1205bd4ede 100644 --- a/discord/abc.py +++ b/discord/abc.py @@ -35,7 +35,6 @@ Protocol, TypeAlias, TypeVar, - Union, overload, runtime_checkable, ) @@ -105,7 +104,7 @@ | PartialMessageable ) MessageableChannel: TypeAlias = PartialMessageableChannel | GroupChannel - SnowflakeTime = Union["Snowflake", datetime] + SnowflakeTime = "Snowflake" | datetime from .voice import VoiceClient, VoiceProtocol @@ -615,7 +614,7 @@ def overwrites_for(self, obj: Role | User) -> PermissionOverwrite: Parameters ---------- - obj: Union[:class:`~discord.Role`, :class:`~discord.abc.User`] + obj: :class:`~discord.Role` | :class:`~discord.abc.User` The role or user denoting whose overwrite to get. @@ -650,7 +649,7 @@ def overwrites(self) -> dict[Role | Member, PermissionOverwrite]: Returns ------- - Dict[Union[:class:`~discord.Role`, :class:`~discord.Member`], :class:`~discord.PermissionOverwrite`] + Dict[:class:`~discord.Role` | :class:`~discord.Member`, :class:`~discord.PermissionOverwrite`] The channel's permission overwrites. """ ret = {} @@ -721,7 +720,7 @@ def permissions_for(self, obj: Member | Role, /) -> Permissions: Parameters ---------- - obj: Union[:class:`~discord.Member`, :class:`~discord.Role`] + obj: :class:`~discord.Member` | :class:`~discord.Role` The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed. @@ -926,7 +925,7 @@ async def set_permissions( Parameters ----------- - target: Union[:class:`~discord.Member`, :class:`~discord.Role`] + target: :class:`~discord.Member` | :class:`~discord.Role` The member or role to overwrite permissions for. overwrite: Optional[:class:`~discord.PermissionOverwrite`] The permissions to allow and deny to the target, or ``None`` to @@ -1271,7 +1270,7 @@ async def create_invite( .. versionadded:: 2.0 - roles: Optional[List[Union[:class:`.Role`, :class:`.Object`]]] + roles: Optional[List[:class:.Role | :class:.Object]] The roles to give a user when joining through this invite. You must have the :attr:`~Permissions.manage_roles` permission to do this and roles cannot be higher than your own. @@ -1510,7 +1509,7 @@ async def send( The file to upload. files: List[:class:`~discord.File`] A list of files to upload. Must be a maximum of 10. - nonce: Union[:class:`str`, :class:`int`] + nonce: :class:`str` | :class:`int` The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. enforce_nonce: Optional[:class:`bool`] @@ -1531,7 +1530,7 @@ async def send( .. versionadded:: 1.4 - reference: Union[:class:`~discord.Message`, :class:`~discord.MessageReference`, :class:`~discord.PartialMessage`] + reference: :class:~discord.Message | :class:~discord.MessageReference | :class:~discord.PartialMessage A reference to the :class:`~discord.Message` being replied to or forwarded. This can be created using :meth:`~discord.Message.to_reference`. When replying, you can control whether this mentions the author of the referenced message using the @@ -1550,7 +1549,7 @@ async def send( A list of embeds to upload. Must be a maximum of 10. .. versionadded:: 2.0 - stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] + stickers: Sequence[:class:~discord.GuildSticker | :class:~discord.StickerItem] A list of stickers to upload. Must be a maximum of 3. .. versionadded:: 2.0 @@ -1819,7 +1818,7 @@ def pins( limit: Optional[:class:`int`] The number of pinned messages to retrieve. If ``None``, retrieves every pinned message in the channel. - before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`~discord.abc.Snowflake` | :class:`datetime.datetime`] Retrieve messages pinned before this datetime. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. @@ -1938,15 +1937,15 @@ def history( The number of messages to retrieve. If ``None``, retrieves every message in the channel. Note, however, that this would make it a slow operation. - before: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`~discord.abc.Snowflake` | :class:`datetime.datetime`] Retrieve messages before this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. - after: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`~discord.abc.Snowflake` | :class:`datetime.datetime`] Retrieve messages after this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. - around: Optional[Union[:class:`~discord.abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`~discord.abc.Snowflake` | :class:`datetime.datetime`] Retrieve messages around this date or message. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. diff --git a/discord/activity.py b/discord/activity.py index 81128a5fb0..f4072fdedb 100644 --- a/discord/activity.py +++ b/discord/activity.py @@ -26,7 +26,7 @@ from __future__ import annotations import datetime -from typing import TYPE_CHECKING, Any, Union, overload +from typing import TYPE_CHECKING, Any, overload from .asset import Asset from .colour import Colour @@ -180,12 +180,12 @@ class Activity(BaseActivity): - ``small_image``: A string representing the ID for the small image asset. - ``small_text``: A string representing the text when hovering over the small image asset. - party: Dict[:class:`str`, Union[:class:`str`, List[:class:`int`]]] + party: Dict[:class:`str`, :class:`str` | List[:class:`int`]] A dictionary representing the activity party. It contains the following optional keys: - ``id``: A string representing the party ID. - ``size``: A list of up to two integer elements denoting (current_size, maximum_size). - buttons: Union[List[Dict[:class:`str`, :class:`str`]], List[:class:`str`]] + buttons: List[Dict[:class:`str`, :class:`str`]] | List[:class:`str`] A list of dictionaries representing custom buttons shown in a rich presence. Each dictionary contains the following keys: @@ -839,7 +839,7 @@ def __repr__(self) -> str: return f"" -ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify] +ActivityTypes = Activity | Game | CustomActivity | Streaming | Spotify @overload diff --git a/discord/asset.py b/discord/asset.py index 659d6dd5eb..25cc9f468b 100644 --- a/discord/asset.py +++ b/discord/asset.py @@ -89,7 +89,7 @@ async def save( Parameters ---------- - fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] + fp: :class:`io.BufferedIOBase` | :class:`os.PathLike` The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. diff --git a/discord/bot.py b/discord/bot.py index 0910f5d46e..b74a06d6e0 100644 --- a/discord/bot.py +++ b/discord/bot.py @@ -1589,7 +1589,7 @@ async def is_owner(self, user: User | Member) -> bool: Parameters ---------- - user: Union[:class:`.abc.User`, :class:`.member.Member`] + user: :class:`.abc.User` | :class:`.member.Member` The user to check for. Returns diff --git a/discord/channel.py b/discord/channel.py index dab70c4a92..7ccf6b45af 100644 --- a/discord/channel.py +++ b/discord/channel.py @@ -444,11 +444,11 @@ async def purge( check: Callable[[:class:`Message`], :class:`bool`] The function used to check if a message should be deleted. It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``around`` in :meth:`history`. oldest_first: Optional[:class:`bool`] Same as ``oldest_first`` in :meth:`history`. @@ -675,7 +675,7 @@ def archived_threads( The number of threads to retrieve. If ``None``, retrieves every archived thread in the channel. Note, however, that this would make it a slow operation. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Retrieve archived channels before the given date or ID. private: :class:`bool` Whether to retrieve private archived threads. @@ -856,7 +856,7 @@ async def edit(self, *, reason=None, **options): is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. default_auto_archive_duration: :class:`int` The new default auto archive duration in minutes for threads created in this channel. @@ -1157,7 +1157,7 @@ async def edit(self, *, reason=None, **options): A value of `0` disables slowmode. The maximum value possible is `21600`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. default_auto_archive_duration: :class:`int` The new default auto archive duration in minutes for threads created in this channel. @@ -1255,11 +1255,11 @@ async def create_thread( The file to upload. files: List[:class:`~discord.File`] A list of files to upload. Must be a maximum of 10. - stickers: Sequence[Union[:class:`~discord.GuildSticker`, :class:`~discord.StickerItem`]] + stickers: Sequence[:class:`~discord.GuildSticker` | :class:`~discord.StickerItem`] A list of stickers to upload. Must be a maximum of 3. delete_message_after: :class:`int` The time to wait before deleting the thread. - nonce: Union[:class:`str`, :class:`int`] + nonce: :class:`str` | :class:`int` The nonce to use for sending this message. If the message was successfully sent, then the message will have a nonce with this value. allowed_mentions: :class:`~discord.AllowedMentions` @@ -1535,7 +1535,7 @@ async def edit(self, *, reason=None, **options): A value of `0` disables slowmode. The maximum value possible is `21600`. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. default_auto_archive_duration: :class:`int` The new default auto archive duration in minutes for threads created in this channel. @@ -1947,11 +1947,11 @@ async def purge( check: Callable[[:class:`Message`], :class:`bool`] The function used to check if a message should be deleted. It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``around`` in :meth:`history`. oldest_first: Optional[:class:`bool`] Same as ``oldest_first`` in :meth:`history`. @@ -2133,7 +2133,7 @@ async def edit(self, *, reason=None, **options): category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. rtc_region: Optional[:class:`VoiceRegion`] The new region for the voice channel's voice communication. @@ -2187,7 +2187,7 @@ async def create_activity_invite( Parameters ---------- - activity: Union[:class:`discord.EmbeddedActivity`, :class:`int`] + activity: :class:`discord.EmbeddedActivity` | :class:`int` The activity to create an invite for which can be an application id as well. max_age: :class:`int` How long the invite should last in seconds. If it's 0 then the invite @@ -2241,7 +2241,7 @@ async def set_status( Parameters ---------- - status: Union[:class:`str`, None] + status: :class:`str` | None The new status. reason: Optional[:class:`str`] The reason for setting the status. Shows up on the audit log. @@ -2535,11 +2535,11 @@ async def purge( check: Callable[[:class:`Message`], :class:`bool`] The function used to check if a message should be deleted. It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``around`` in :meth:`history`. oldest_first: Optional[:class:`bool`] Same as ``oldest_first`` in :meth:`history`. @@ -2814,7 +2814,7 @@ async def edit(self, *, reason=None, **options): category. reason: Optional[:class:`str`] The reason for editing this channel. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. rtc_region: Optional[:class:`VoiceRegion`] The new region for the stage channel's voice communication. @@ -2980,7 +2980,7 @@ async def edit(self, *, reason=None, **options): The new category's position. reason: Optional[:class:`str`] The reason for editing this category. Shows up on the audit log. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to channel permissions. Useful for creating secret channels. Returns diff --git a/discord/client.py b/discord/client.py index de9f17ad70..92c2cf48b0 100644 --- a/discord/client.py +++ b/discord/client.py @@ -997,7 +997,7 @@ def get_channel(self, id: int, /) -> GuildChannel | Thread | PrivateChannel | No Returns ------- - Optional[Union[:class:`.abc.GuildChannel`, :class:`.Thread`, :class:`.abc.PrivateChannel`]] + Optional[:class:`.abc.GuildChannel` | :class:`.Thread` | :class:`.abc.PrivateChannel`] The returned channel or ``None`` if not found. """ return self._connection.get_channel(id) @@ -1599,11 +1599,11 @@ def fetch_guilds( If ``None``, it retrieves every guild you have access to. Note, however, that this would make it a slow operation. Defaults to ``100``. - before: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] + before: :class:`.abc.Snowflake` | :class:`datetime.datetime` Retrieves guilds before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. - after: Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`] + after: :class:`.abc.Snowflake` | :class:`datetime.datetime` Retrieve guilds after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. @@ -1649,7 +1649,7 @@ async def fetch_template(self, code: Template | str) -> Template: Parameters ---------- - code: Union[:class:`.Template`, :class:`str`] + code: :class:`.Template` | :class:`str` The Discord Template Code or URL (must be a discord.new URL). Returns @@ -1759,7 +1759,7 @@ async def fetch_invite( Parameters ---------- - url: Union[:class:`.Invite`, :class:`str`] + url: :class:`.Invite` | :class:`str` The Discord invite ID or URL (must be a discord.gg URL). with_counts: :class:`bool` Whether to include count information in the invite. This fills the @@ -1810,7 +1810,7 @@ async def delete_invite(self, invite: Invite | str) -> None: Parameters ---------- - invite: Union[:class:`.Invite`, :class:`str`] + invite: :class:`.Invite` | :class:`str` The invite to revoke. Raises @@ -1923,7 +1923,7 @@ async def fetch_channel( Returns ------- - Union[:class:`.abc.GuildChannel`, :class:`.abc.PrivateChannel`, :class:`.Thread`] + :class:`.abc.GuildChannel` | :class:`.abc.PrivateChannel` | :class:`.Thread` The channel from the ID. Raises @@ -1985,7 +1985,7 @@ async def fetch_sticker(self, sticker_id: int, /) -> StandardSticker | GuildStic Returns ------- - Union[:class:`.StandardSticker`, :class:`.GuildSticker`] + :class:`.StandardSticker` | :class:`.GuildSticker` The sticker you requested. Raises diff --git a/discord/cog.py b/discord/cog.py index d514e1febf..85fba2753b 100644 --- a/discord/cog.py +++ b/discord/cog.py @@ -374,7 +374,7 @@ def walk_commands(self) -> Generator[ApplicationCommand]: Yields ------ - Union[:class:`.Command`, :class:`.Group`] + :class:`.Command` | :class:`.Group` A command or group from the cog. """ for command in self.__cog_commands__: @@ -897,7 +897,7 @@ def load_extension( Returns ------- - Optional[Union[Dict[:class:`str`, Union[:exc:`errors.ExtensionError`, :class:`bool`]], List[:class:`str`]]] + Optional[Dict[:class:`str`, :exc:`errors.ExtensionError` | :class:`bool`] | List[:class:`str`]] If the store parameter is set to ``True``, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension @@ -1020,7 +1020,7 @@ def load_extensions( Returns ------- - Optional[Union[Dict[:class:`str`, Union[:exc:`errors.ExtensionError`, :class:`bool`]], List[:class:`str`]]] + Optional[Dict[:class:`str`, :exc:`errors.ExtensionError` | :class:`bool`] | List[:class:`str`]] If the store parameter is set to ``True``, a dictionary will be returned that contains keys to represent the loaded extension names. The values bound to each key can either be an exception that occurred when loading that extension diff --git a/discord/colour.py b/discord/colour.py index 420ab9096f..3d46d44186 100644 --- a/discord/colour.py +++ b/discord/colour.py @@ -167,7 +167,7 @@ def random( Parameters ---------- - seed: Optional[Union[:class:`int`, :class:`str`, :class:`float`, :class:`bytes`, :class:`bytearray`]] + seed: Optional[:class:`int` | :class:`str` | :class:`float` | :class:`bytes` | :class:`bytearray`] The seed to initialize the RNG with. If ``None`` is passed the default RNG is used. .. versionadded:: 1.7 diff --git a/discord/commands/context.py b/discord/commands/context.py index e1bc5a808a..e3c4d1a7df 100644 --- a/discord/commands/context.py +++ b/discord/commands/context.py @@ -144,7 +144,7 @@ def command(self, value: ApplicationCommand | None) -> None: @property def channel(self) -> InteractionChannel | None: - """Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]: + """:class:`abc.GuildChannel` | :class:`PartialMessageable` | :class:`Thread`: Returns the channel associated with this context's command. Shorthand for :attr:`.Interaction.channel`. """ return self.interaction.channel @@ -190,7 +190,7 @@ def app_permissions(self) -> Permissions: @property def me(self) -> Member | ClientUser | None: - """Union[:class:`.Member`, :class:`.ClientUser`]: + """:class:`.Member` | :class:`.ClientUser`: Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message message contexts, or when :meth:`Intents.guilds` is absent. """ diff --git a/discord/commands/core.py b/discord/commands/core.py index 6c4e0e73b2..13ec3fd2fc 100644 --- a/discord/commands/core.py +++ b/discord/commands/core.py @@ -1400,7 +1400,7 @@ def add_command(self, command: SlashCommand | SlashCommandGroup) -> None: Parameters ---------- - command: Union[:class:`.SlashCommand`, :class:`.SlashCommandGroup`] + command: :class:`.SlashCommand` | :class:`.SlashCommandGroup` The command to add. """ if command.cog is None and self.cog is not None: diff --git a/discord/commands/options.py b/discord/commands/options.py index a7d7d682ce..7a3ecdec4b 100644 --- a/discord/commands/options.py +++ b/discord/commands/options.py @@ -70,42 +70,43 @@ from ..role import Role from ..user import User - InputType = Union[ - type[str], - type[bool], - type[int], - type[float], - type[GuildChannel], - type[Thread], - type[Member], - type[User], - type[Attachment], - type[Role], - type[Mentionable], - SlashCommandOptionType, - Converter, - type[Converter], - type[Enum], - type[DiscordEnum], - ] - - AutocompleteReturnType = Union[ - Iterable["OptionChoice"], Iterable[str], Iterable[int], Iterable[float] - ] + InputType = ( + type[str] + | type[bool] + | type[int] + | type[float] + | type[GuildChannel] + | type[Thread] + | type[Member] + | type[User] + | type[Attachment] + | type[Role] + | type[Mentionable] + | SlashCommandOptionType + | Converter + | type[Converter] + | type[Enum] + | type[DiscordEnum] + ) + + AutocompleteReturnType = ( + Iterable["OptionChoice"] | Iterable[str] | Iterable[int] | Iterable[float] + ) + T = TypeVar("T", bound=AutocompleteReturnType) - MaybeAwaitable = Union[T, Awaitable[T]] - AutocompleteFunction = Union[ - Callable[[AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]], - Callable[[Cog, AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]], - Callable[ + MaybeAwaitable = T | Awaitable[T] + AutocompleteFunction = ( + Callable[[AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]] + | Callable[[Cog, AutocompleteContext], MaybeAwaitable[AutocompleteReturnType]] + | Callable[ [AutocompleteContext, Any], # pyright: ignore [reportExplicitAny] MaybeAwaitable[AutocompleteReturnType], - ], - Callable[ + ] + | Callable[ [Cog, AutocompleteContext, Any], # pyright: ignore [reportExplicitAny] MaybeAwaitable[AutocompleteReturnType], - ], - ] + ] + ) __all__ = ( @@ -154,7 +155,7 @@ class Option: Attributes ---------- - input_type: Union[Type[:class:`str`], Type[:class:`bool`], Type[:class:`int`], Type[:class:`float`], Type[:class:`.abc.GuildChannel`], Type[:class:`Thread`], Type[:class:`Member`], Type[:class:`User`], Type[:class:`Attachment`], Type[:class:`Role`], Type[:class:`.abc.Mentionable`], :class:`SlashCommandOptionType`, Type[:class:`.ext.commands.Converter`], Type[:class:`enums.Enum`], Type[:class:`Enum`]] + input_type: Type[:class:`str`] | Type[:class:`bool`] | Type[:class:`int`] | Type[:class:`float`] | Type[:class:`.abc.GuildChannel`] | Type[:class:`Thread`] | Type[:class:`Member`] | Type[:class:`User`] | Type[:class:`Attachment`] | Type[:class:`Role`] | Type[:class:`.abc.Mentionable`] | :class:`SlashCommandOptionType` | Type[:class:`.ext.commands.Converter`] | Type[:class:`enums.Enum`] | Type[:class:`Enum`] The type of input that is expected for this option. This can be a :class:`SlashCommandOptionType`, an associated class, a channel type, a :class:`Converter`, a converter class or an :class:`enum.Enum`. If a :class:`enum.Enum` is used and it has up to 25 values, :attr:`choices` will be automatically filled. If the :class:`enum.Enum` has more than 25 values, :attr:`autocomplete` will be implemented with :func:`discord.utils.basic_autocomplete` instead. @@ -164,7 +165,7 @@ class Option: description: Optional[:class:`str`] The description of this option. Must be 100 characters or fewer. If :attr:`input_type` is a :class:`enum.Enum` and :attr:`description` is not specified, :attr:`input_type`'s docstring will be used. - choices: Optional[List[Union[:class:`Any`, :class:`OptionChoice`]]] + choices: Optional[List[:class:`Any` | :class:`OptionChoice`]] The list of available choices for this option. Can be a list of values or :class:`OptionChoice` objects (which represent a name:value pair). If provided, the input from the user must match one of the choices in the list. @@ -325,7 +326,7 @@ def __init__( minmax_typehint = Optional[int] elif self.input_type == SlashCommandOptionType.number: minmax_types = (int, float, type(None)) - minmax_typehint = Optional[Union[int, float]] + minmax_typehint = Optional[int | float] else: minmax_types = (type(None),) minmax_typehint = type(None) @@ -506,7 +507,7 @@ class OptionChoice: ---------- name: :class:`str` The name of the choice. Shown in the UI when selecting an option. - value: Optional[Union[:class:`str`, :class:`int`, :class:`float`]] + value: Optional[:class:`str` | :class:`int` | :class:`float`] The value of the choice. If not provided, will use the value of ``name``. name_localizations: Dict[:class:`str`, :class:`str`] The name localizations for this choice. The values of this should be ``"locale": "name"``. diff --git a/discord/components.py b/discord/components.py index 53aa06de6e..54f3fc13c3 100644 --- a/discord/components.py +++ b/discord/components.py @@ -217,7 +217,7 @@ def get_component(self, id: str | int) -> Component | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The custom_id or id of the component to get. Returns @@ -861,7 +861,7 @@ def get_component(self, id: str | int) -> Component | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The custom_id or id of the component to get. Returns @@ -1297,7 +1297,7 @@ def get_component(self, id: str | int) -> Component | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The custom_id or id of the component to get. Returns diff --git a/discord/embeds.py b/discord/embeds.py index 57f4c89302..935bce29d7 100644 --- a/discord/embeds.py +++ b/discord/embeds.py @@ -273,7 +273,7 @@ def to_dict(self) -> dict[str, str | bool | None]: Returns ------- - Dict[:class:`str`, Union[:class:`str`, :class:`bool`]] + Dict[:class:`str`, :class:`str` | :class:`bool`] A dictionary of :class:`str` embed field keys bound to the respective value. """ return { @@ -327,7 +327,7 @@ class Embed: The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone. - colour: Union[:class:`Colour`, :class:`int`] + colour: :class:`Colour` | :class:`int` The colour code of the embed. Aliased to ``color`` as well. This can be set during initialisation. """ @@ -1025,7 +1025,7 @@ def to_dict(self) -> EmbedData: Returns ------- - Dict[:class:`str`, Union[:class:`str`, :class:`int`, :class:`bool`]] + Dict[:class:`str`, :class:`str` | :class:`int` | :class:`bool`] A dictionary of :class:`str` embed keys bound to the respective value. """ diff --git a/discord/errors.py b/discord/errors.py index 5e94e0279c..569eb2be79 100644 --- a/discord/errors.py +++ b/discord/errors.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, Union +from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from aiohttp import ClientResponse, ClientWebSocketResponse @@ -33,7 +33,7 @@ try: from requests import Response - _ResponseType = Union[ClientResponse, Response] + _ResponseType = ClientResponse | Response except ModuleNotFoundError: _ResponseType = ClientResponse diff --git a/discord/ext/bridge/bot.py b/discord/ext/bridge/bot.py index 9e2c619fa6..45aa9dbc4f 100644 --- a/discord/ext/bridge/bot.py +++ b/discord/ext/bridge/bot.py @@ -69,7 +69,7 @@ def walk_bridge_commands( Yields ------ - Union[:class:`.BridgeCommand`, :class:`.BridgeCommandGroup`] + :class:`.BridgeCommand` | :class:`.BridgeCommandGroup` A bridge command or bridge group of the bot. """ for cmd in self._bridge_commands: diff --git a/discord/ext/bridge/context.py b/discord/ext/bridge/context.py index 8e7f9414f6..4868319f2f 100644 --- a/discord/ext/bridge/context.py +++ b/discord/ext/bridge/context.py @@ -26,7 +26,7 @@ from __future__ import annotations from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any, Union, overload +from typing import TYPE_CHECKING, Any, overload from discord.commands import ApplicationContext from discord.interactions import Interaction, InteractionMessage @@ -196,7 +196,7 @@ async def delete( await self._original_response_message.delete(delay=delay, reason=reason) -Context = Union[BridgeExtContext, BridgeApplicationContext] +Context = BridgeExtContext | BridgeApplicationContext """ A Union class for either :class:`BridgeExtContext` or :class:`BridgeApplicationContext`. Can be used as a type hint for Context for bridge commands. diff --git a/discord/ext/bridge/core.py b/discord/ext/bridge/core.py index 4bf6b2cfac..152e549a6c 100644 --- a/discord/ext/bridge/core.py +++ b/discord/ext/bridge/core.py @@ -252,7 +252,7 @@ def add_to(self, bot: ExtBot) -> None: Parameters ---------- - bot: Union[:class:`.Bot`, :class:`.AutoShardedBot`] + bot: :class:`.Bot` | :class:`.AutoShardedBot` The bot to add the command to. """ bot.add_application_command(self.slash_variant) diff --git a/discord/ext/commands/_types.py b/discord/ext/commands/_types.py index 99d9a5bc95..83cae7ab72 100644 --- a/discord/ext/commands/_types.py +++ b/discord/ext/commands/_types.py @@ -26,7 +26,7 @@ from __future__ import annotations from collections.abc import Callable, Coroutine -from typing import TYPE_CHECKING, Any, TypeVar, Union +from typing import TYPE_CHECKING, Any, TypeVar if TYPE_CHECKING: from .cog import Cog @@ -36,17 +36,18 @@ T = TypeVar("T") Coro = Coroutine[Any, Any, T] -MaybeCoro = Union[T, Coro[T]] +MaybeCoro = T | Coro[T] CoroFunc = Callable[..., Coro[Any]] -Check = Union[ - Callable[["Cog", "Context[Any]"], MaybeCoro[bool]], - Callable[["Context[Any]"], MaybeCoro[bool]], -] -Hook = Union[ - Callable[["Cog", "Context[Any]"], Coro[Any]], Callable[["Context[Any]"], Coro[Any]] -] -Error = Union[ - Callable[["Cog", "Context[Any]", "CommandError"], Coro[Any]], - Callable[["Context[Any]", "CommandError"], Coro[Any]], -] +Check = ( + Callable[["Cog", "Context[Any]"], MaybeCoro[bool]] + | Callable[["Context[Any]"], MaybeCoro[bool]] +) +Hook = ( + Callable[["Cog", "Context[Any]"], Coro[Any]] | Callable[["Context[Any]"], Coro[Any]] +) + +Error = ( + Callable[["Cog", "Context[Any]", "CommandError"], Coro[Any]] + | Callable[["Context[Any]", "CommandError"], Coro[Any]], +) diff --git a/discord/ext/commands/bot.py b/discord/ext/commands/bot.py index 0b050a7b8f..c8892cfe7a 100644 --- a/discord/ext/commands/bot.py +++ b/discord/ext/commands/bot.py @@ -223,7 +223,7 @@ async def get_prefix(self, message: Message) -> list[str] | str: Returns ------- - Union[List[:class:`str`], :class:`str`] + List[:class:`str`] | :class:`str` A list of prefixes or a single prefix that the bot is listening for. """ diff --git a/discord/ext/commands/cog.py b/discord/ext/commands/cog.py index ac93818475..427a43866d 100644 --- a/discord/ext/commands/cog.py +++ b/discord/ext/commands/cog.py @@ -56,7 +56,7 @@ def walk_commands(self) -> Generator[Command]: Yields ------ - Union[:class:`.Command`, :class:`.Group`] + :class:`.Command` | :class:`.Group` A command or group from the cog. """ from .core import GroupMixin @@ -76,7 +76,7 @@ def get_commands(self) -> list[ApplicationCommand | Command]: r""" Returns -------- - List[Union[:class:`~discord.ApplicationCommand`, :class:`.Command`]] + List[:class:`~discord.ApplicationCommand` | :class:`.Command`] A :class:`list` of commands that are defined inside this cog. .. note:: diff --git a/discord/ext/commands/context.py b/discord/ext/commands/context.py index 780db189de..7223afd357 100644 --- a/discord/ext/commands/context.py +++ b/discord/ext/commands/context.py @@ -27,7 +27,7 @@ import inspect import re -from typing import TYPE_CHECKING, Any, Generic, TypeVar, Union +from typing import TYPE_CHECKING, Any, Generic, TypeVar import discord.abc import discord.utils @@ -54,7 +54,7 @@ T = TypeVar("T") -BotT = TypeVar("BotT", bound="Union[Bot, AutoShardedBot]") +BotT = TypeVar("BotT", bound="Bot | AutoShardedBot") CogT = TypeVar("CogT", bound="Cog") if TYPE_CHECKING: @@ -299,14 +299,14 @@ def channel(self) -> MessageableChannel: @property def author(self) -> User | Member: - """Union[:class:`~discord.User`, :class:`.Member`]: + """:class:`~discord.User` | :class:`.Member`: Returns the author associated with this context's command. Shorthand for :attr:`.Message.author` """ return self.message.author @property def me(self) -> Member | ClientUser: - """Union[:class:`.Member`, :class:`.ClientUser`]: + """:class:`.Member` | :class:`.ClientUser`: Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message message contexts, or when :meth:`Intents.guilds` is absent. """ @@ -345,7 +345,7 @@ async def send_help(self, *args: Any) -> Any: Parameters ---------- - entity: Optional[Union[:class:`Command`, :class:`Cog`, :class:`str`]] + entity: Optional[:class:`Command` | :class:`Cog` | :class:`str`] The entity to show help for. Returns diff --git a/discord/ext/commands/core.py b/discord/ext/commands/core.py index dad32f30a1..5ce6171a0b 100644 --- a/discord/ext/commands/core.py +++ b/discord/ext/commands/core.py @@ -234,7 +234,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]): The short help text for the command. usage: Optional[:class:`str`] A replacement for arguments in the default help text. - aliases: Union[List[:class:`str`], Tuple[:class:`str`]] + aliases: List[:class:`str`] | Tuple[:class:`str`] The list of aliases the command can be invoked under. enabled: :class:`bool` A boolean that indicates if the command is currently enabled. @@ -1335,7 +1335,7 @@ def walk_commands(self) -> Generator[Command[CogT, Any, Any]]: Yields ------ - Union[:class:`.Command`, :class:`.Group`] + :class:`.Command` | :class:`.Group` A command or group from the internal list of commands. """ for command in self.commands: @@ -1953,7 +1953,7 @@ def has_role(item: int | str) -> Callable[[T], T]: Parameters ---------- - item: Union[:class:`int`, :class:`str`] + item: :class:`int` | :class:`str` The name or ID of the role to check. """ @@ -1991,7 +1991,7 @@ def has_any_role(*items: int | str) -> Callable[[T], T]: Parameters ---------- - items: List[Union[:class:`str`, :class:`int`]] + items: List[:class:`str` | :class:`int`] An argument list of names or IDs to check that the member has roles wise. Example @@ -2337,7 +2337,7 @@ def cooldown( The number of times a command can be used before triggering a cooldown. per: :class:`float` The amount of seconds to wait for a cooldown when it's been triggered. - type: Union[:class:`.BucketType`, Callable[[:class:`.Message`], Any]] + type: :class:`.BucketType` | Callable[[:class:`.Message`], Any] The type of cooldown to have. If callable, should return a key for the mapping. .. versionchanged:: 1.7 diff --git a/discord/ext/commands/errors.py b/discord/ext/commands/errors.py index 8263af7150..ce8455e5fd 100644 --- a/discord/ext/commands/errors.py +++ b/discord/ext/commands/errors.py @@ -354,7 +354,7 @@ class ChannelNotReadable(BadArgument): Attributes ---------- - argument: Union[:class:`.abc.GuildChannel`, :class:`.Thread`] + argument: :class:`.abc.GuildChannel` | :class:`.Thread` The channel supplied by the caller that was not readable """ @@ -608,7 +608,7 @@ class MissingRole(CheckFailure): Attributes ---------- - missing_role: Union[:class:`str`, :class:`int`] + missing_role: :class:`str` | :class:`int` The required role that is missing. This is the parameter passed to :func:`~.commands.has_role`. """ @@ -628,7 +628,7 @@ class BotMissingRole(CheckFailure): Attributes ---------- - missing_role: Union[:class:`str`, :class:`int`] + missing_role: :class:`str` | :class:`int` The required role that is missing. This is the parameter passed to :func:`~.commands.has_role`. """ @@ -649,7 +649,7 @@ class MissingAnyRole(CheckFailure): Attributes ---------- - missing_roles: List[Union[:class:`str`, :class:`int`]] + missing_roles: List[:class:`str` | :class:`int`] The roles that the invoker is missing. These are the parameters passed to :func:`~.commands.has_any_role`. """ @@ -678,7 +678,7 @@ class BotMissingAnyRole(CheckFailure): Attributes ---------- - missing_roles: List[Union[:class:`str`, :class:`int`]] + missing_roles: List[:class:`str` | :class:`int`] The roles that the bot's member is missing. These are the parameters passed to :func:`~.commands.has_any_role`. """ @@ -706,7 +706,7 @@ class NSFWChannelRequired(CheckFailure): Parameters ---------- - channel: Union[:class:`.abc.GuildChannel`, :class:`.Thread`] + channel: :class:`.abc.GuildChannel` | :class:`.Thread` The channel that does not have NSFW enabled. """ diff --git a/discord/ext/commands/flags.py b/discord/ext/commands/flags.py index 2606565857..674accdcf0 100644 --- a/discord/ext/commands/flags.py +++ b/discord/ext/commands/flags.py @@ -217,7 +217,7 @@ def get_flags( # List[str] -> (max_args=-1) # Tuple[int, ...] -> (max_args=1) # Dict[K, V] -> (max_args=-1, override=True) - # Union[str, int] -> (max_args=1) + # str | int -> (max_args=1) # Optional[str] -> (default=None, max_args=1) try: @@ -478,7 +478,7 @@ async def convert_flag(ctx, argument: str, flag: Flag, annotation: Any = None) - return await convert_flag(ctx, argument, flag, annotation) elif origin is Union and annotation.__args__[-1] is type(None): # typing.Optional[x] - annotation = Union[annotation.__args__[:-1]] + annotation = annotation.__args__[:-1] return await run_converters(ctx, annotation, argument, param) elif origin is dict: # typing.Dict[K, V] -> typing.Tuple[K, V] diff --git a/discord/ext/pages/pagination.py b/discord/ext/pages/pagination.py index 5509f7a177..cc960f4d19 100644 --- a/discord/ext/pages/pagination.py +++ b/discord/ext/pages/pagination.py @@ -56,7 +56,7 @@ class PaginatorButton(discord.ui.Button): label: :class:`str` The label shown on the button. Defaults to a capitalized version of ``button_type`` (e.g. "Next", "Prev", etc.) - emoji: Union[:class:`str`, :class:`discord.GuildEmoji`, :class:`discord.AppEmoji`, :class:`discord.PartialEmoji`] + emoji: :class:`str` | :class:`discord.GuildEmoji` | :class:`discord.AppEmoji` | :class:`discord.PartialEmoji` The emoji shown on the button in front of the label. disabled: :class:`bool` Whether to initially show the button as disabled. @@ -141,7 +141,7 @@ class Page: ---------- content: :class:`str` The content of the page. Corresponds to the :class:`discord.Message.content` attribute. - embeds: Optional[List[Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]] + embeds: Optional[List[List[:class:`discord.Embed`] | :class:`discord.Embed`]] The embeds of the page. Corresponds to the :class:`discord.Message.embeds` attribute. files: Optional[List[:class:`discord.File`]] A list of local files to be shown with the page. @@ -241,14 +241,14 @@ class PageGroup: Parameters ---------- - pages: Union[List[:class:`str`], List[:class:`Page`], List[Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]] + pages: List[:class:`str`] | List[:class:`Page`] | List[List[:class:`discord.Embed`] | :class:`discord.Embed`] The list of :class:`Page` objects, strings, embeds, or list of embeds to include in the page group. label: :class:`str` The label shown on the corresponding PaginatorMenu dropdown option. Also used as the SelectOption value. description: Optional[:class:`str`] The description shown on the corresponding PaginatorMenu dropdown option. - emoji: Union[:class:`str`, :class:`discord.GuildEmoji`, :class:`discord.AppEmoji`, :class:`discord.PartialEmoji`] + emoji: :class:`str` | :class:`discord.GuildEmoji` | :class:`discord.AppEmoji` | :class:`discord.PartialEmoji` The emoji shown on the corresponding PaginatorMenu dropdown option. default: Optional[:class:`bool`] Whether the page group should be the default page group initially shown when the paginator response is sent. @@ -325,7 +325,7 @@ class Paginator(discord.ui.View): Parameters ---------- - pages: Union[List[:class:`PageGroup`], List[:class:`Page`], List[:class:`str`], List[Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]] + pages: List[:class:`PageGroup`] | List[:class:`Page`] | List[:class:`str`] | List[List[:class:`discord.Embed`] | :class:`discord.Embed`] The list of :class:`PageGroup` objects, :class:`Page` objects, strings, embeds, or list of embeds to paginate. If a list of :class:`PageGroup` objects is provided and `show_menu` is ``False``, only the first page group will be displayed. @@ -374,11 +374,11 @@ class Paginator(discord.ui.View): A zero-indexed value showing the current page number. page_count: :class:`int` A zero-indexed value showing the total number of pages. - buttons: Dict[:class:`str`, Dict[:class:`str`, Union[:class:`~PaginatorButton`, :class:`bool`]]] + buttons: Dict[:class:`str`, Dict[:class:`str`, :class:`~PaginatorButton` | :class:`bool`]] A dictionary containing the :class:`~PaginatorButton` objects included in this paginator. - user: Optional[Union[:class:`~discord.User`, :class:`~discord.Member`]] + user: Optional[:class:`~discord.User` | :class:`~discord.Member`] The user or member that invoked the paginator. - message: Union[:class:`~discord.Message`, :class:`~discord.WebhookMessage`] + message: :class:`~discord.Message` | :class:`~discord.WebhookMessage` The message the paginator is attached to. """ @@ -487,7 +487,7 @@ async def update( Parameters ---------- - pages: Optional[Union[List[:class:`PageGroup`], List[:class:`Page`], List[:class:`str`], List[Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]]] + pages: Optional[List[:class:`PageGroup`] | List[:class:`Page`] | List[:class:`str`] | List[List[:class:`discord.Embed`] | :class:`discord.Embed`]] The list of :class:`PageGroup` objects, :class:`Page` objects, strings, embeds, or list of embeds to paginate. show_disabled: :class:`bool` @@ -624,7 +624,7 @@ async def disable( ---------- include_custom: :class:`bool` Whether to disable components added via custom views. - page: Optional[Union[:class:`str`, Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]] + page: Optional[:class:`str` | List[:class:`discord.Embed`] | :class:`discord.Embed`] The page content to show after disabling the paginator. """ page = self.get_page_content(page) @@ -655,7 +655,7 @@ async def cancel( ---------- include_custom: :class:`bool` Whether to remove components added via custom views. - page: Optional[Union[:class:`str`, Union[List[:class:`discord.Embed`], :class:`discord.Embed`]]] + page: Optional[:class:`str` | List[:class:`discord.Embed`] | :class:`discord.Embed`] The page content to show after canceling the paginator. """ items = self.children.copy() @@ -842,7 +842,7 @@ def update_buttons(self) -> dict: Returns ------- - Dict[:class:`str`, Dict[:class:`str`, Union[:class:`~PaginatorButton`, :class:`bool`]]] + Dict[:class:`str`, Dict[:class:`str`, :class:`~PaginatorButton` | :class:`bool`]] The dictionary of buttons that were updated. """ for key, button in self.buttons.items(): @@ -976,13 +976,13 @@ async def send( Parameters ---------- - ctx: Union[:class:`~discord.ext.commands.Context`] + ctx: :class:`~discord.ext.commands.Context` A command's invocation context. target: Optional[:class:`~discord.abc.Messageable`] A target where the paginated message should be sent, if different from the original :class:`Context` target_message: Optional[:class:`str`] An optional message shown when the paginator message is sent elsewhere. - reference: Optional[Union[:class:`discord.Message`, :class:`discord.MessageReference`, :class:`discord.PartialMessage`]] + reference: Optional[:class:`discord.Message` | :class:`discord.MessageReference` | :class:`discord.PartialMessage`] A reference to the :class:`~discord.Message` to which you are replying with the paginator. This can be created using :meth:`~discord.Message.to_reference` or passed directly as a :class:`~discord.Message`. You can control whether this mentions the author of the referenced message @@ -1104,7 +1104,7 @@ async def edit( are used instead. delete_after: Optional[:class:`float`] If set, deletes the paginator after the specified time. - user: Optional[Union[:class:`~discord.User`, :class:`~discord.Member`]] + user: Optional[:class:`~discord.User` | :class:`~discord.Member`] If set, changes the user that this paginator belongs to. Returns @@ -1162,7 +1162,7 @@ async def respond( Parameters ---------- - interaction: Union[:class:`discord.Interaction`, :class:`BridgeContext`] + interaction: :class:`discord.Interaction` | :class:`BridgeContext` The interaction or BridgeContext which invoked the paginator. If passing a BridgeContext object, you cannot make this an ephemeral paginator. ephemeral: :class:`bool` @@ -1182,7 +1182,7 @@ async def respond( Returns ------- - Union[:class:`~discord.Message`, :class:`~discord.WebhookMessage`] + :class:`~discord.Message` | :class:`~discord.WebhookMessage` The :class:`~discord.Message` or :class:`~discord.WebhookMessage` that was sent with the paginator. """ diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py index c1d1e72274..5d51287ea7 100644 --- a/discord/ext/tasks/__init__.py +++ b/discord/ext/tasks/__init__.py @@ -730,7 +730,7 @@ def change_interval( The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. - time: Union[:class:`datetime.time`, Sequence[:class:`datetime.time`]] + time: :class:`datetime.time` | Sequence[:class:`datetime.time`] The exact times to run this loop at. Either a non-empty list or a single value of :class:`datetime.time` should be passed. This cannot be used in conjunction with the relative time parameters. @@ -804,7 +804,7 @@ def loop( The number of minutes between every iteration. hours: :class:`float` The number of hours between every iteration. - time: Union[:class:`datetime.time`, Sequence[:class:`datetime.time`]] + time: :class:`datetime.time` | Sequence[:class:`datetime.time`] The exact times to run this loop at. Either a non-empty list or a single value of :class:`datetime.time` should be passed. Timezones are supported. If no timezone is given for the times, it is assumed to represent UTC time. @@ -827,7 +827,7 @@ def loop( loop: :class:`asyncio.AbstractEventLoop` The loop to use to register the task, if not given the default event loop is used via :func:`asyncio.get_event_loop()` if it exists or one is created via :func:`asyncio.new_event_loop()`. - overlap: Union[:class:`bool`, :class:`int`] + overlap: :class:`bool` | :class:`int` Controls whether overlapping executions of the task loop are allowed. Set to False (default) to run iterations one at a time, True for unlimited overlap, or an int to cap the number of concurrent runs. diff --git a/discord/file.py b/discord/file.py index f1f99ddc11..a92b704db3 100644 --- a/discord/file.py +++ b/discord/file.py @@ -46,7 +46,7 @@ class File: Attributes ----------- - fp: Union[:class:`os.PathLike`, :class:`io.BufferedIOBase`] + fp: :class:`os.PathLike` | :class:`io.BufferedIOBase` A file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open. @@ -161,7 +161,7 @@ class VoiceMessage(File): Attributes ---------- - fp: Union[:class:`os.PathLike`, :class:`io.BufferedIOBase`] + fp: :class:`os.PathLike` | :class:`io.BufferedIOBase` A audio file-like object opened in binary mode and read mode or a filename representing a file in the hard drive to open. diff --git a/discord/guild.py b/discord/guild.py index e55f5c955e..5b2210e26d 100644 --- a/discord/guild.py +++ b/discord/guild.py @@ -36,7 +36,6 @@ NamedTuple, Optional, TypeVar, - Union, cast, overload, ) @@ -127,10 +126,10 @@ from .voice import VoiceClient from .webhook import Webhook - VocalGuildChannel = Union[VoiceChannel, StageChannel] - GuildChannel = Union[ - VoiceChannel, StageChannel, TextChannel, ForumChannel, CategoryChannel - ] + VocalGuildChannel = VoiceChannel | StageChannel + GuildChannel = ( + VoiceChannel | StageChannel | TextChannel | ForumChannel | CategoryChannel + ) ByCategoryItem = tuple[Optional[CategoryChannel], list[GuildChannel]] T = TypeVar("T") @@ -168,7 +167,7 @@ def __getitem__(self, key: int | abc.Snowflake) -> int: Parameters ---------- - key: Union[:class:`int`, :class:`~discord.abc.Snowflake`] + key: :class:`int` | :class:`~discord.abc.Snowflake` The role ID or a Snowflake object (e.g., a :class:`Role`). Returns @@ -191,7 +190,7 @@ def get(self, key: int | abc.Snowflake, default: T = None) -> int | T: Parameters ---------- - key: Union[:class:`int`, :class:`~discord.abc.Snowflake`] + key: :class:`int` | :class:`~discord.abc.Snowflake` The role ID or a Snowflake object (e.g., a :class:`Role`). default: Any The value to return if the role ID is not found. @@ -211,7 +210,7 @@ def __contains__(self, key: int | abc.Snowflake) -> bool: Parameters ---------- - key: Union[:class:`int`, :class:`~discord.abc.Snowflake`] + key: :class:`int` | :class:`~discord.abc.Snowflake` The role ID or a Snowflake object (e.g., a :class:`Role`). Returns @@ -741,7 +740,7 @@ async def create_sound( Only MP3 sound files that are less than 5.2 seconds long are supported. volume: :class:`float` The volume of the sound. Defaults to 1.0. - emoji: Optional[Union[:class:`PartialEmoji`, :class:`GuildEmoji`, :class:`str`]] + emoji: Optional[:class:`PartialEmoji` | :class:`GuildEmoji` | :class:`str`] The emoji of the sound. reason: Optional[:class:`str`] The reason for creating this sound. Shows up on the audit log. @@ -980,7 +979,7 @@ def get_channel_or_thread(self, channel_id: int, /) -> Thread | GuildChannel | N Returns ------- - Optional[Union[:class:`Thread`, :class:`.abc.GuildChannel`]] + Optional[:class:`Thread` | :class:`.abc.GuildChannel`] The returned channel or thread or ``None`` if not found. """ return self._channels.get(channel_id) or self._threads.get(channel_id) @@ -1498,7 +1497,7 @@ async def create_text_channel( ---------- name: :class:`str` The channel's name. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to the channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. @@ -1618,7 +1617,7 @@ async def create_voice_channel( ---------- name: :class:`str` The channel's name. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to the channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. @@ -1732,7 +1731,7 @@ async def create_stage_channel( The channel's name. topic: :class:`str` The new channel's topic. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to the channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. @@ -1868,7 +1867,7 @@ async def create_forum_channel( ---------- name: :class:`str` The channel's name. - overwrites: Dict[Union[:class:`Role`, :class:`Member`, :class:`~discord.abc.Snowflake`], :class:`PermissionOverwrite`] + overwrites: Dict[:class:`Role` | :class:`Member` | :class:`~discord.abc.Snowflake`, :class:`PermissionOverwrite`] The overwrites to apply to the channel. Useful for creating secret channels. category: Optional[:class:`CategoryChannel`] The category to place the newly created channel under. @@ -2454,7 +2453,7 @@ def fetch_members( limit: Optional[:class:`int`] The number of members to retrieve. Defaults to 1000. Pass ``None`` to fetch all members. Note that this is potentially slow. - after: Optional[Union[:class:`.abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`.abc.Snowflake` | :class:`datetime.datetime`] Retrieve members after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. @@ -2595,7 +2594,7 @@ async def fetch_channel(self, channel_id: int, /) -> GuildChannel | Thread: Returns ------- - Union[:class:`.abc.GuildChannel`, :class:`.Thread`] + :class:`.abc.GuildChannel` | :class:`.Thread` The channel from the ID. Raises @@ -3422,7 +3421,7 @@ async def create_role( The role name. Defaults to 'new role'. permissions: :class:`Permissions` The permissions to have. Defaults to no permissions. - colour: Union[:class:`Colour`, :class:`int`] + colour: :class:`Colour` | :class:`int` The colour for the role. Defaults to :meth:`Colour.default`. This is aliased to ``color`` as well. hoist: :class:`bool` @@ -3815,11 +3814,11 @@ def audit_logs( ---------- limit: Optional[:class:`int`] The number of entries to retrieve. If ``None`` retrieve all entries. - before: Union[:class:`abc.Snowflake`, :class:`datetime.datetime`] + before: :class:`abc.Snowflake` | :class:`datetime.datetime` Retrieve entries before this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. - after: Union[:class:`abc.Snowflake`, :class:`datetime.datetime`] + after: :class:`abc.Snowflake` | :class:`datetime.datetime` Retrieve entries after this date or entry. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. @@ -4057,7 +4056,7 @@ async def change_voice_state( Parameters ---------- - channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] + channel: Optional[:class:`VoiceChannel` | :class:`StageChannel`] Channel the client wants to join. Use ``None`` to disconnect. self_mute: :class:`bool` Indicates if the client should be self-muted. diff --git a/discord/interactions.py b/discord/interactions.py index f6af21d733..380a71618a 100644 --- a/discord/interactions.py +++ b/discord/interactions.py @@ -28,7 +28,7 @@ import asyncio import datetime from collections.abc import Coroutine -from typing import TYPE_CHECKING, Any, Union, overload +from typing import TYPE_CHECKING, Any, overload from typing_extensions import deprecated @@ -95,17 +95,17 @@ from .ui.modal import BaseModal from .ui.view import BaseView - InteractionChannel = Union[ - VoiceChannel, - StageChannel, - TextChannel, - ForumChannel, - CategoryChannel, - Thread, - DMChannel, - GroupChannel, - PartialMessageable, - ] + InteractionChannel = ( + VoiceChannel + | StageChannel + | TextChannel + | ForumChannel + | CategoryChannel + | Thread + | DMChannel + | GroupChannel + | PartialMessageable + ) MISSING: Any = utils.MISSING @@ -126,13 +126,13 @@ class Interaction: The interaction type. guild_id: Optional[:class:`int`] The guild ID the interaction was sent from. - channel: Optional[Union[:class:`abc.GuildChannel`, :class:`abc.PrivateChannel`, :class:`Thread`, :class:`PartialMessageable`]] + channel: Optional[:class:`abc.GuildChannel` | :class:`abc.PrivateChannel` | :class:`Thread` | :class:`PartialMessageable`] The channel the interaction was sent from. channel_id: Optional[:class:`int`] The ID of the channel the interaction was sent from. application_id: :class:`int` The application ID that the interaction was for. - user: Optional[Union[:class:`User`, :class:`Member`]] + user: Optional[:class:`User` | :class:`Member`] The user or member that sent the interaction. Will be `None` in PING interactions. message: Optional[:class:`Message`] The message that sent this interaction. @@ -812,7 +812,7 @@ async def respond(self, *args, **kwargs) -> Interaction | WebhookMessage: Returns ------- - Union[:class:`discord.Interaction`, :class:`discord.WebhookMessage`]: + :class:`discord.Interaction` | :class:`discord.WebhookMessage`: The response, its type depending on whether it's an interaction response or a followup. """ try: @@ -831,7 +831,7 @@ async def edit(self, *args, **kwargs) -> InteractionMessage | None: Returns ------- - Union[:class:`discord.InteractionMessage`, :class:`discord.WebhookMessage`]: + :class:`discord.InteractionMessage` | :class:`discord.WebhookMessage`: The response, its type depending on whether it's an interaction response or a followup. """ try: diff --git a/discord/invite.py b/discord/invite.py index 05178794f7..6812d37be5 100755 --- a/discord/invite.py +++ b/discord/invite.py @@ -28,7 +28,7 @@ import datetime import io import os -from typing import TYPE_CHECKING, TypeVar, Union +from typing import TYPE_CHECKING, TypeVar from typing_extensions import deprecated, override @@ -73,8 +73,8 @@ from .types.snowflake import Snowflake from .user import User - InviteGuildType = Union[Guild, "PartialInviteGuild", Object] - InviteChannelType = Union[GuildChannel, "PartialInviteChannel", Object] + InviteGuildType = Guild | "PartialInviteGuild" | Object + InviteChannelType = GuildChannel | "PartialInviteChannel" | Object class PartialInviteChannel: @@ -344,7 +344,7 @@ async def save( Parameters ---------- - fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] + fp: :class:`io.BufferedIOBase` | :class:`os.PathLike` The file-like object to save this file to or the filename to use. If a filename is passed then a file is created with that filename and used instead. @@ -458,7 +458,7 @@ class Invite(Hashable): A value of ``0`` indicates that it doesn't expire. code: :class:`str` The URL fragment used for the invite. - guild: Optional[Union[:class:`Guild`, :class:`Object`, :class:`PartialInviteGuild`]] + guild: Optional[:class:`Guild` | :class:`Object` | :class:`PartialInviteGuild`] The guild the invite is for. Can be ``None`` if it's from a group direct message. revoked: :class:`bool` Indicates if the invite has been revoked. @@ -485,7 +485,7 @@ class Invite(Hashable): .. versionadded:: 2.0 - channel: Union[:class:`abc.GuildChannel`, :class:`Object`, :class:`PartialInviteChannel`] + channel: :class:`abc.GuildChannel` | :class:`Object` | :class:`PartialInviteChannel` The channel the invite is for. target_type: :class:`InviteTarget` The type of target for the voice channel invite. @@ -503,7 +503,7 @@ class Invite(Hashable): .. versionadded:: 2.0 scheduled_event: Optional[:class:`ScheduledEvent`] The scheduled event linked with the invite. - roles: List[Union[:class:`Role`, :class:`Object`]] + roles: List[:class:`Role` | :class:`Object`] The roles that will be assigned to a user that joins via this invite. When using `Client.fetch_invite`, these may be partial role objects and have nullish attributes. diff --git a/discord/iterators.py b/discord/iterators.py index 50fdc6d2a3..13fe75b2e1 100644 --- a/discord/iterators.py +++ b/discord/iterators.py @@ -32,7 +32,6 @@ TYPE_CHECKING, Any, TypeVar, - Union, ) from typing_extensions import deprecated, override @@ -75,7 +74,7 @@ T = TypeVar("T") OT = TypeVar("OT") -_Func = Callable[[T], Union[OT, Awaitable[OT]]] +_Func = Callable[[T], OT | Awaitable[OT]] OLDEST_OBJECT = Object(id=0) @@ -188,7 +187,7 @@ async def next(self) -> T: return item -class ReactionIterator(_AsyncIterator[Union["User", "Member"]]): +class ReactionIterator(_AsyncIterator["User" | "Member"]): def __init__(self, message, emoji, limit=100, after=None, type=None): self.message = message self.limit = limit @@ -244,7 +243,7 @@ async def fill_users(self): await self.users.put(User(state=self.state, data=element)) -class VoteIterator(_AsyncIterator[Union["User", "Member"]]): +class VoteIterator(_AsyncIterator["User" | "Member"]): def __init__(self, message, answer, limit=100, after=None): self.message = message self.limit = limit @@ -321,11 +320,11 @@ class HistoryIterator(_AsyncIterator["Message"]): Messageable class to retrieve message history from. limit: :class:`int` Maximum number of messages to retrieve - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Message before which all messages must be. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Message after which all messages must be. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Message around which all messages must be. Limit max 101. Note that if limit is an even number, this will return at most limit+1 messages. oldest_first: Optional[:class:`bool`] @@ -585,9 +584,9 @@ class GuildIterator(_AsyncIterator["Guild"]): The client to retrieve the guilds from. limit: :class:`int` Maximum number of guilds to retrieve. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Object before which all guilds must be. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Object after which all guilds must be. with_counts: :class:`bool` Whether to include member count information in guilds. This fills the @@ -889,7 +888,7 @@ def create_thread(self, data: ThreadPayload) -> Thread: return Thread(guild=self.guild, state=self.guild._state, data=data) -class ScheduledEventSubscribersIterator(_AsyncIterator[Union["User", "Member"]]): +class ScheduledEventSubscribersIterator(_AsyncIterator["User" | "Member"]): def __init__( self, event: ScheduledEvent, diff --git a/discord/member.py b/discord/member.py index a65370a806..f342254132 100644 --- a/discord/member.py +++ b/discord/member.py @@ -112,7 +112,7 @@ class VoiceState: afk: :class:`bool` Indicates if the user is currently in the AFK channel in the guild. - channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] + channel: Optional[:class:`VoiceChannel` | :class:`StageChannel`] The voice channel that the user is currently connected to. ``None`` if the user is not currently in a voice channel. """ @@ -265,7 +265,7 @@ class Member(discord.abc.Messageable, _UserTag): joined_at: Optional[:class:`datetime.datetime`] An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be ``None``. - activities: Tuple[Union[:class:`BaseActivity`, :class:`Spotify`]] + activities: Tuple[:class:`BaseActivity` | :class:`Spotify`] The activities that the user is currently doing. .. note:: @@ -943,7 +943,7 @@ async def edit( roles: List[:class:`Role`] The member's new list of roles. This *replaces* the roles. - voice_channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] + voice_channel: Optional[:class:`VoiceChannel` | :class:`StageChannel`] The voice channel to move the member to. Pass ``None`` to kick them from voice. reason: Optional[:class:`str`] @@ -1204,7 +1204,7 @@ async def move_to( Parameters ---------- - channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] + channel: Optional[:class:`VoiceChannel` | :class:`StageChannel`] The new voice channel to move the member to. Pass ``None`` to kick them from voice. reason: Optional[:class:`str`] diff --git a/discord/message.py b/discord/message.py index e1633aa97e..ab2c065b43 100644 --- a/discord/message.py +++ b/discord/message.py @@ -35,7 +35,6 @@ Any, ClassVar, TypeVar, - Union, overload, ) from urllib.parse import parse_qs, urlparse @@ -95,7 +94,7 @@ from .user import User MR = TypeVar("MR", bound="MessageReference") - EmojiInputType = Union[GuildEmoji, AppEmoji, PartialEmoji, str] + EmojiInputType = GuildEmoji | AppEmoji | PartialEmoji | str __all__ = ( "Attachment", @@ -299,7 +298,7 @@ async def save( Parameters ---------- - fp: Union[:class:`io.BufferedIOBase`, :class:`os.PathLike`] + fp: :class:`io.BufferedIOBase` | :class:`os.PathLike` The file-like object to save this attachment to or the filename to use. If a filename is passed then a file is created with that filename and used instead. @@ -561,7 +560,7 @@ class MessageReference: .. versionadded:: 1.7 - resolved: Optional[Union[:class:`Message`, :class:`DeletedReferencedMessage`]] + resolved: Optional[:class:`Message` | :class:`DeletedReferencedMessage`] The message that this reference resolved to. If this is ``None`` then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. @@ -733,11 +732,11 @@ class ForwardedMessage: type: :class:`MessageType` The type of the original message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for :attr:`system_content`. - original_message: Optional[Union[:class:`Message`, :class:`PartialMessage`]] + original_message: Optional[:class:`Message` | :class:`PartialMessage`] The original message that was forwarded, if available. - channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`] + channel: :class:`TextChannel` | :class:`Thread` | :class:`DMChannel` | :class:`GroupChannel` | :class:`PartialMessageable` The :class:`TextChannel` or :class:`Thread` that the original message was sent from. - guild: Optional[Union[:class:`Guild`, :class:`Object`]] + guild: Optional[:class:`Guild` | :class:`Object`] The guild that the original message belonged to, if applicable. content: :class:`str` The contents of the original message. @@ -931,17 +930,17 @@ class Message(Hashable): type: :class:`MessageType` The type of message. In most cases this should not be checked, but it is helpful in cases where it might be a system message for :attr:`system_content`. - author: Union[:class:`Member`, :class:`abc.User`] + author: :class:`Member` | :class:`abc.User` A :class:`Member` that sent the message. If :attr:`channel` is a private channel or the user has the left the guild, then it is a :class:`User` instead. content: :class:`str` The actual contents of the message. - nonce: Optional[Union[:class:`str`, :class:`int`]] + nonce: Optional[:class:`str` | :class:`int`] The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord's servers and is only used ephemerally. embeds: List[:class:`Embed`] A list of embeds the message has. - channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`] + channel: :class:`TextChannel` | :class:`Thread` | :class:`DMChannel` | :class:`GroupChannel` | :class:`PartialMessageable` The :class:`TextChannel` or :class:`Thread` that the message was sent from. Could be a :class:`DMChannel` or :class:`GroupChannel` if it's a private message. reference: Optional[:class:`~discord.MessageReference`] @@ -2015,7 +2014,7 @@ async def add_reaction(self, emoji: EmojiInputType) -> None: Parameters ---------- - emoji: Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] + emoji: :class:`GuildEmoji` | :class:`AppEmoji` | :class:`Reaction` | :class:`PartialEmoji` | :class:`str` The emoji to react with. Raises @@ -2050,7 +2049,7 @@ async def remove_reaction( Parameters ---------- - emoji: Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] + emoji: :class:`GuildEmoji` | :class:`AppEmoji` | :class:`Reaction` | :class:`PartialEmoji` | :class:`str` The emoji to remove. member: :class:`abc.Snowflake` The member for which to remove the reaction. @@ -2089,7 +2088,7 @@ async def clear_reaction(self, emoji: EmojiInputType | Reaction) -> None: Parameters ---------- - emoji: Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`Reaction`, :class:`PartialEmoji`, :class:`str`] + emoji: :class:`GuildEmoji` | :class:`AppEmoji` | :class:`Reaction` | :class:`PartialEmoji` | :class:`str` The emoji to clear. Raises @@ -2223,7 +2222,7 @@ async def forward_to( Parameters ---------- - channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`GroupChannel`, :class:`PartialMessageable`] + channel: :class:`TextChannel` | :class:`Thread` | :class:`DMChannel` | :class:`GroupChannel` | :class:`PartialMessageable` The channel to forward this to. Returns @@ -2325,7 +2324,7 @@ def get_component(self, id: str | int) -> Component | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The id or custom_id the item to get Returns @@ -2379,7 +2378,7 @@ class PartialMessage(Hashable): Attributes ---------- - channel: Union[:class:`TextChannel`, :class:`Thread`, :class:`DMChannel`, :class:`VoiceChannel`, :class:`StageChannel`, :class:`PartialMessageable`] + channel: :class:`TextChannel` | :class:`Thread` | :class:`DMChannel` | :class:`VoiceChannel` | :class:`StageChannel` | :class:`PartialMessageable` The channel associated with this partial message. id: :class:`int` The message ID. diff --git a/discord/monetization.py b/discord/monetization.py index 9244c2dcdf..7595d53087 100644 --- a/discord/monetization.py +++ b/discord/monetization.py @@ -189,17 +189,17 @@ class Entitlement(Hashable): The ID of the SKU this entitlement is for. application_id: :class:`int` The ID of the application this entitlement belongs to. - user_id: Union[:class:`int`, :class:`MISSING`] + user_id: :class:`int` | :class:`MISSING` The ID of the user that owns this entitlement. type: :class:`EntitlementType` The type of entitlement. deleted: :class:`bool` Whether the entitlement has been deleted. - starts_at: Union[:class:`datetime.datetime`, :class:`MISSING`] + starts_at: :class:`datetime.datetime` | :class:`MISSING` When the entitlement starts. - ends_at: Union[:class:`datetime.datetime`, :class:`MISSING`] + ends_at: :class:`datetime.datetime` | :class:`MISSING` When the entitlement expires. - guild_id: Union[:class:`int`, :class:`MISSING`] + guild_id: :class:`int` | :class:`MISSING` The ID of the guild that owns this entitlement. consumed: :class:`bool` Whether or not this entitlement has been consumed. diff --git a/discord/object.py b/discord/object.py index fd684069d8..fe5bfd86be 100644 --- a/discord/object.py +++ b/discord/object.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, SupportsInt, Union +from typing import TYPE_CHECKING, SupportsInt from . import utils from .mixins import Hashable @@ -35,7 +35,7 @@ from .abc import Snowflake - SupportsIntCast = Union[SupportsInt, str, bytes, bytearray] + SupportsIntCast = SupportsInt | str | bytes | bytearray __all__ = ("Object",) diff --git a/discord/onboarding.py b/discord/onboarding.py index 4e4fa7e993..a7a5145e96 100644 --- a/discord/onboarding.py +++ b/discord/onboarding.py @@ -63,7 +63,7 @@ class PromptOption: The channels assigned to the user when they select this option. roles: List[:class:`Snowflake`] The roles assigned to the user when they select this option. - emoji: Union[:class:`GuildEmoji`, :class:`PartialEmoji`] + emoji: :class:`GuildEmoji` | :class:`PartialEmoji` The emoji displayed with the option. title: :class:`str` The option's title. diff --git a/discord/player.py b/discord/player.py index 007bd7e8d7..9afd274d1b 100644 --- a/discord/player.py +++ b/discord/player.py @@ -322,7 +322,7 @@ class FFmpegPCMAudio(FFmpegAudio): Parameters ---------- - source: Union[:class:`str`, :class:`io.BufferedIOBase`] + source: :class:`str` | :class:`io.BufferedIOBase` The input that ffmpeg will take and convert to PCM bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. @@ -427,7 +427,7 @@ class FFmpegOpusAudio(FFmpegAudio): Parameters ---------- - source: Union[:class:`str`, :class:`io.BufferedIOBase`] + source: :class:`str` | :class:`io.BufferedIOBase` The input that ffmpeg will take and convert to Opus bytes. If ``pipe`` is ``True`` then this is a file-like object that is passed to the stdin of ffmpeg. @@ -564,7 +564,7 @@ def custom_probe(source, executable): ------------ source Identical to the ``source`` parameter for the constructor. - method: Optional[Union[:class:`str`, Callable[:class:`str`, :class:`str`]]] + method: Optional[:class:`str` | Callable[:class:`str`, :class:`str`]] The probing method used to determine bitrate and codec information. As a string, valid values are ``native`` to use ffprobe (or avprobe) and ``fallback`` to use ffmpeg (or avconv). As a callable, it must take two string arguments, ``source`` and diff --git a/discord/poll.py b/discord/poll.py index fd9ce2344d..20c803b66b 100644 --- a/discord/poll.py +++ b/discord/poll.py @@ -62,7 +62,7 @@ class PollMedia: text: :class:`str` The question/answer text. May have up to 300 characters for questions and 55 characters for answers. - emoji: Optional[Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`PartialEmoji`, :class:`str`]] + emoji: Optional[:class:`GuildEmoji` | :class:`AppEmoji` | :class:`PartialEmoji` | :class:`str`] The answer's emoji. """ @@ -204,7 +204,7 @@ def voters( Yields ------ - Union[:class:`User`, :class:`Member`] + :class:`User` | :class:`Member` The member (if retrievable) or the user that has voted with this answer. The case where it can be a :class:`Member` is in a guild message context. Sometimes it can be a :class:`User` @@ -324,7 +324,7 @@ class Poll: Attributes ---------- - question: Union[:class:`PollMedia`, :class:`str`] + question: :class:`PollMedia` | :class:`str` The poll's question media, or a ``str`` representing the question text. Question text can be up to 300 characters. answers: Optional[List[:class:`PollAnswer`]] A list of the poll's answers. A maximum of 10 answers can be set. @@ -464,7 +464,7 @@ def add_answer( ---------- text: :class:`str` The answer text. Maximum 55 characters. - emoji: Optional[Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`PartialEmoji`, :class:`str`]] + emoji: Optional[:class:`GuildEmoji` | :class:`AppEmoji` | :class:`PartialEmoji` | :class:`str`] The answer's emoji. Raises diff --git a/discord/raw_models.py b/discord/raw_models.py index 291a44fadc..7989a611a1 100644 --- a/discord/raw_models.py +++ b/discord/raw_models.py @@ -606,7 +606,7 @@ class AutoModActionExecutionEvent: The member that triggered the action, if cached. channel_id: Optional[:class:`int`] The ID of the channel in which the member's content was posted. - channel: Optional[Union[:class:`TextChannel`, :class:`Thread`, :class:`VoiceChannel`, :class:`StageChannel`]] + channel: Optional[:class:`TextChannel` | :class:`Thread` | :class:`VoiceChannel` | :class:`StageChannel`] The channel in which the member's content was posted, if cached. message_id: Optional[:class:`int`] The ID of the message that triggered the action. This is only available if the @@ -900,7 +900,7 @@ class RawVoiceStateUpdateEvent(_PayloadLike): anymore or have been accepted to. afk: :class:`bool` Whether the user is connected on the guild's AFK channel. - channel: Optional[Union[:class:`VoiceChannel`, :class:`StageChannel`]] + channel: Optional[:class:`VoiceChannel` | :class:`StageChannel`] The voice channel that the user is currently connected to. ``None`` if the user is not currently in a voice channel. diff --git a/discord/reaction.py b/discord/reaction.py index 418b0e3060..d130a1b29e 100644 --- a/discord/reaction.py +++ b/discord/reaction.py @@ -70,7 +70,7 @@ class Reaction: Attributes ---------- - emoji: Union[:class:`GuildEmoji`, :class:`AppEmoji`, :class:`PartialEmoji`, :class:`str`] + emoji: :class:`GuildEmoji` | :class:`AppEmoji` | :class:`PartialEmoji` | :class:`str` The reaction emoji. May be a custom emoji, or a unicode emoji. count: :class:`int` The combined total of normal and super reactions for this emoji. @@ -234,7 +234,7 @@ def users( Yields ------ - Union[:class:`User`, :class:`Member`] + :class:`User` | :class:`Member` The member (if retrievable) or the user that has reacted to this message. The case where it can be a :class:`Member` is in a guild message context. Sometimes it can be a :class:`User` diff --git a/discord/role.py b/discord/role.py index e7d24a6f83..ac4603ae9f 100644 --- a/discord/role.py +++ b/discord/role.py @@ -822,7 +822,7 @@ async def edit( The new role name to change to. permissions: :class:`Permissions` The new permissions to change to. - colour: Union[:class:`Colour`, :class:`int`] + colour: :class:`Colour` | :class:`int` The new colour to change to. (aliased to color as well) hoist: :class:`bool` Indicates if the role should be shown separately in the member list. diff --git a/discord/scheduled_events.py b/discord/scheduled_events.py index 32c169fc29..7cf95af552 100644 --- a/discord/scheduled_events.py +++ b/discord/scheduled_events.py @@ -75,7 +75,7 @@ class ScheduledEventLocation: Attributes ---------- - value: Union[:class:`str`, :class:`StageChannel`, :class:`VoiceChannel`, :class:`Object`] + value: :class:`str` | :class:`StageChannel` | :class:`VoiceChannel` | :class:`Object` The actual location of the scheduled event. type: :class:`ScheduledEventLocationType` The type of location. @@ -534,18 +534,18 @@ def subscribers( Whether to fetch :class:`Member` objects instead of user objects. There may still be :class:`User` objects if the user is outside the guild. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Retrieves users before this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Retrieves users after this date or object. If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time. Yields ------ - Union[:class:`User`, :class:`Member`] + :class:`User` | :class:`Member` The subscribed :class:`Member`. If ``as_member`` is set to ``False`` or the user is outside the guild, it will be a :class:`User` object. diff --git a/discord/soundboard.py b/discord/soundboard.py index 7ef8def8e3..35e2740b77 100644 --- a/discord/soundboard.py +++ b/discord/soundboard.py @@ -206,7 +206,7 @@ def edit( The new name of the sound. volume: Optional[:class:`float`] The new volume of the sound. - emoji: Optional[Union[:class:`PartialEmoji`, :class:`str`]] + emoji: Optional[:class:`PartialEmoji` | :class:`str`] The new emoji of the sound. reason: Optional[:class:`str`] The reason for editing the sound. Shows up in the audit log. diff --git a/discord/state.py b/discord/state.py index df4fc51056..8a3939c4d7 100644 --- a/discord/state.py +++ b/discord/state.py @@ -37,7 +37,6 @@ TYPE_CHECKING, Any, TypeVar, - Union, ) from . import utils @@ -91,7 +90,7 @@ T = TypeVar("T") CS = TypeVar("CS", bound="ConnectionState") - Channel = Union[GuildChannel, VocalGuildChannel, PrivateChannel, PartialMessageable] + Channel = GuildChannel | VocalGuildChannel | PrivateChannel | PartialMessageable class ChunkRequest: diff --git a/discord/sticker.py b/discord/sticker.py index 78b4b8c1f4..28f5892e5a 100644 --- a/discord/sticker.py +++ b/discord/sticker.py @@ -232,7 +232,7 @@ async def fetch(self) -> Sticker | StandardSticker | GuildSticker: Returns ------- - Union[:class:`StandardSticker`, :class:`GuildSticker`] + :class:`StandardSticker` | :class:`GuildSticker` The retrieved sticker. Raises diff --git a/discord/threads.py b/discord/threads.py index 7d73331c1f..017231dde0 100644 --- a/discord/threads.py +++ b/discord/threads.py @@ -441,7 +441,7 @@ def permissions_for(self, obj: Member | Role, /) -> Permissions: Parameters ---------- - obj: Union[:class:`~discord.Member`, :class:`~discord.Role`] + obj: :class:`~discord.Member` | :class:`~discord.Role` The object to resolve permissions for. This could be either a member or a role. If it's a role then member overwrites are not computed. @@ -549,11 +549,11 @@ async def purge( check: Callable[[:class:`Message`], :class:`bool`] The function used to check if a message should be deleted. It must take a :class:`Message` as its sole parameter. - before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + before: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``before`` in :meth:`history`. - after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + after: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``after`` in :meth:`history`. - around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]] + around: Optional[:class:`abc.Snowflake` | :class:`datetime.datetime`] Same as ``around`` in :meth:`history`. oldest_first: Optional[:class:`bool`] Same as ``oldest_first`` in :meth:`history`. diff --git a/discord/types/audit_log.py b/discord/types/audit_log.py index 0575457e7a..09bacaed63 100644 --- a/discord/types/audit_log.py +++ b/discord/types/audit_log.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -242,22 +242,22 @@ class _AuditLogChange_Overwrites(TypedDict): old_value: list[PermissionOverwrite] -AuditLogChange = Union[ - _AuditLogChange_Str, - _AuditLogChange_AssetHash, - _AuditLogChange_Snowflake, - _AuditLogChange_Int, - _AuditLogChange_Bool, - _AuditLogChange_ListRole, - _AuditLogChange_MFALevel, - _AuditLogChange_VerificationLevel, - _AuditLogChange_ExplicitContentFilter, - _AuditLogChange_DefaultMessageNotificationLevel, - _AuditLogChange_ChannelType, - _AuditLogChange_IntegrationExpireBehaviour, - _AuditLogChange_VideoQualityMode, - _AuditLogChange_Overwrites, -] +AuditLogChange = ( + _AuditLogChange_Str + | _AuditLogChange_AssetHash + | _AuditLogChange_Snowflake + | _AuditLogChange_Int + | _AuditLogChange_Bool + | _AuditLogChange_ListRole + | _AuditLogChange_MFALevel + | _AuditLogChange_VerificationLevel + | _AuditLogChange_ExplicitContentFilter + | _AuditLogChange_DefaultMessageNotificationLevel + | _AuditLogChange_ChannelType + | _AuditLogChange_IntegrationExpireBehaviour + | _AuditLogChange_VideoQualityMode + | _AuditLogChange_Overwrites +) class AuditEntryInfo(TypedDict): diff --git a/discord/types/channel.py b/discord/types/channel.py index d4661cf8c4..ae361c40c0 100644 --- a/discord/types/channel.py +++ b/discord/types/channel.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -146,15 +146,15 @@ class ThreadChannel(_BaseChannel): total_message_sent: int -GuildChannel = Union[ - TextChannel, - NewsChannel, - VoiceChannel, - CategoryChannel, - StageChannel, - ThreadChannel, - ForumChannel, -] +GuildChannel = ( + TextChannel + | NewsChannel + | VoiceChannel + | CategoryChannel + | StageChannel + | ThreadChannel + | ForumChannel +) class DMChannel(TypedDict): @@ -170,7 +170,7 @@ class GroupDMChannel(_BaseChannel): owner_id: Snowflake -Channel = Union[GuildChannel, DMChannel, GroupDMChannel] +Channel = GuildChannel | DMChannel | GroupDMChannel PrivacyLevel = Literal[1, 2] diff --git a/discord/types/components.py b/discord/types/components.py index af567b6566..6a83fb5740 100644 --- a/discord/types/components.py +++ b/discord/types/components.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -212,45 +212,45 @@ class CheckboxComponent(BaseComponent): default: NotRequired[bool] -Component = Union[ - ActionRow, - ButtonComponent, - SelectMenu, - InputText, - TextDisplayComponent, - SectionComponent, - ThumbnailComponent, - MediaGalleryComponent, - FileComponent, - SeparatorComponent, - ContainerComponent, - LabelComponent, - FileUploadComponent, - RadioGroupComponent, - CheckboxGroupComponent, - CheckboxComponent, -] - -AllowedActionRowComponents = Union[ButtonComponent, InputText, SelectMenu] - -AllowedSectionAccessories = Union[ThumbnailComponent, ButtonComponent] - -AllowedSectionComponents = Union[TextDisplayComponent] - -AllowedContainerComponents = Union[ - ActionRow, - TextDisplayComponent, - MediaGalleryComponent, - FileComponent, - SeparatorComponent, - SectionComponent, -] - -AllowedLabelComponents = Union[ - SelectMenu, - InputText, - FileUploadComponent, - RadioGroupComponent, - CheckboxComponent, - CheckboxGroupComponent, -] +Component = ( + ActionRow + | ButtonComponent + | SelectMenu + | InputText + | TextDisplayComponent + | SectionComponent + | ThumbnailComponent + | MediaGalleryComponent + | FileComponent + | SeparatorComponent + | ContainerComponent + | LabelComponent + | FileUploadComponent + | RadioGroupComponent + | CheckboxGroupComponent + | CheckboxComponent +) + +AllowedActionRowComponents = ButtonComponent | InputText | SelectMenu + +AllowedSectionAccessories = ThumbnailComponent | ButtonComponent + +AllowedSectionComponents = TextDisplayComponent + +AllowedContainerComponents = ( + ActionRow + | TextDisplayComponent + | MediaGalleryComponent + | FileComponent + | SeparatorComponent + | SectionComponent +) + +AllowedLabelComponents = ( + SelectMenu + | InputText + | FileUploadComponent + | RadioGroupComponent + | CheckboxComponent + | CheckboxGroupComponent +) diff --git a/discord/types/integration.py b/discord/types/integration.py index 1a6c8b70f1..22dd7e66e7 100644 --- a/discord/types/integration.py +++ b/discord/types/integration.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -80,4 +80,4 @@ class BotIntegration(BaseIntegration): application: IntegrationApplication -Integration = Union[BaseIntegration, StreamIntegration, BotIntegration] +Integration = BaseIntegration | StreamIntegration | BotIntegration diff --git a/discord/types/interactions.py b/discord/types/interactions.py index da1c345f64..e29515e74f 100644 --- a/discord/types/interactions.py +++ b/discord/types/interactions.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Literal, Union +from typing import TYPE_CHECKING, Literal from ..permissions import Permissions from .channel import ChannelType @@ -161,14 +161,14 @@ class _ApplicationCommandInteractionDataOptionNumber( value: float -ApplicationCommandInteractionDataOption = Union[ - _ApplicationCommandInteractionDataOptionString, - _ApplicationCommandInteractionDataOptionInteger, - _ApplicationCommandInteractionDataOptionSubcommand, - _ApplicationCommandInteractionDataOptionBoolean, - _ApplicationCommandInteractionDataOptionSnowflake, - _ApplicationCommandInteractionDataOptionNumber, -] +ApplicationCommandInteractionDataOption = ( + _ApplicationCommandInteractionDataOptionString + | _ApplicationCommandInteractionDataOptionInteger + | _ApplicationCommandInteractionDataOptionSubcommand + | _ApplicationCommandInteractionDataOptionBoolean + | _ApplicationCommandInteractionDataOptionSnowflake + | _ApplicationCommandInteractionDataOptionNumber +) class ApplicationCommandResolvedPartialChannel(TypedDict): @@ -201,7 +201,7 @@ class ComponentInteractionData(TypedDict): component_type: ComponentType -InteractionData = Union[ApplicationCommandInteractionData, ComponentInteractionData] +InteractionData = ApplicationCommandInteractionData | ComponentInteractionData class Interaction(TypedDict): diff --git a/discord/types/invite.py b/discord/types/invite.py index 6d2b511b69..9654379a5d 100644 --- a/discord/types/invite.py +++ b/discord/types/invite.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -92,7 +92,7 @@ class GatewayInviteDelete(TypedDict): code: str -GatewayInvite = Union[GatewayInviteCreate, GatewayInviteDelete] +GatewayInvite = GatewayInviteCreate | GatewayInviteDelete class InviteTargetUsersJobStatus(TypedDict): diff --git a/discord/types/snowflake.py b/discord/types/snowflake.py index 3b89d29323..279792e290 100644 --- a/discord/types/snowflake.py +++ b/discord/types/snowflake.py @@ -23,7 +23,5 @@ DEALINGS IN THE SOFTWARE. """ -from typing import Union - -Snowflake = Union[str, int] +Snowflake = str | int SnowflakeList = list[Snowflake] diff --git a/discord/types/sticker.py b/discord/types/sticker.py index 95945462e6..de100c71e7 100644 --- a/discord/types/sticker.py +++ b/discord/types/sticker.py @@ -25,7 +25,7 @@ from __future__ import annotations -from typing import Literal, Union +from typing import Literal from typing_extensions import NotRequired, TypedDict @@ -62,7 +62,7 @@ class GuildSticker(BaseSticker): guild_id: Snowflake -Sticker = Union[BaseSticker, StandardSticker, GuildSticker] +Sticker = BaseSticker | StandardSticker | GuildSticker class StickerPack(TypedDict): diff --git a/discord/ui/action_row.py b/discord/ui/action_row.py index 730a1b2905..c9505fb1ab 100644 --- a/discord/ui/action_row.py +++ b/discord/ui/action_row.py @@ -166,7 +166,7 @@ def remove_item(self, item: ViewItem | str | int) -> Self: Parameters ---------- - item: Union[:class:`ViewItem`, :class:`int`, :class:`str`] + item: :class:`ViewItem` | :class:`int` | :class:`str` The item, ``id``, or item ``custom_id`` to remove from the action row. """ @@ -185,7 +185,7 @@ def get_item(self, id: str | int) -> ViewItem | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The id or custom_id of the item to get. Returns @@ -229,9 +229,9 @@ def add_button( Whether the button is disabled or not. label: Optional[:class:`str`] The label of the button, if any. Maximum of 80 chars. - emoji: Optional[Union[:class:`.PartialEmoji`, :class:`GuildEmoji`, :class:`AppEmoji`, :class:`str`]] + emoji: Optional[:class:`.PartialEmoji` | :class:`GuildEmoji` | :class:`AppEmoji` | :class:`str`] The emoji of the button, if any. - sku_id: Optional[Union[:class:`int`]] + sku_id: Optional[:class:`int`] The ID of the SKU this button refers to. id: Optional[:class:`int`] The button's ID. @@ -344,7 +344,7 @@ def add_select( Whether the select is disabled or not. Defaults to ``False``. id: Optional[:class:`int`] The select menu's ID. - default_values: Optional[Sequence[Union[:class:`discord.SelectDefaultValue`, :class:`discord.abc.Snowflake`]]] + default_values: Optional[Sequence[:class:`discord.SelectDefaultValue` | :class:`discord.abc.Snowflake`]] The default values of this select. Only applicable if :attr:`.select_type` is not :attr:`discord.ComponentType.string_select`. These can be either :class:`discord.SelectDefaultValue` instances or models, which will be converted into :class:`discord.SelectDefaultValue` diff --git a/discord/ui/button.py b/discord/ui/button.py index a8ad878c38..7dcfef7bc6 100644 --- a/discord/ui/button.py +++ b/discord/ui/button.py @@ -67,9 +67,9 @@ class Button(ViewItem[V]): Whether the button is disabled or not. label: Optional[:class:`str`] The label of the button, if any. Maximum of 80 chars. - emoji: Optional[Union[:class:`.PartialEmoji`, :class:`GuildEmoji`, :class:`AppEmoji`, :class:`str`]] + emoji: Optional[:class:`.PartialEmoji` | :class:`GuildEmoji` | :class:`AppEmoji` | :class:`str`] The emoji of the button, if available. - sku_id: Optional[Union[:class:`int`]] + sku_id: Optional[:class:`int`] The ID of the SKU this button refers to. row: Optional[:class:`int`] The relative row this button belongs to. A Discord component can only have 5 @@ -385,7 +385,7 @@ def button( The style of the button. Defaults to :attr:`.ButtonStyle.grey`. disabled: :class:`bool` Whether the button is disabled or not. Defaults to ``False``. - emoji: Optional[Union[:class:`str`, :class:`GuildEmoji`, :class:`AppEmoji`, :class:`.PartialEmoji`]] + emoji: Optional[:class:`str` | :class:`GuildEmoji` | :class:`AppEmoji` | :class:`.PartialEmoji`] The emoji of the button. This can be in string form or a :class:`.PartialEmoji` or a full :class:`GuildEmoji` or :class:`AppEmoji`. row: Optional[:class:`int`] diff --git a/discord/ui/container.py b/discord/ui/container.py index e35c05f7d6..180e149958 100644 --- a/discord/ui/container.py +++ b/discord/ui/container.py @@ -73,7 +73,7 @@ class Container(ViewItem[V]): ---------- *items: :class:`ViewItem` The initial items in this container. - colour: Union[:class:`Colour`, :class:`int`] + colour: :class:`Colour` | :class:`int` The accent colour of the container. Aliased to ``color`` as well. spoiler: Optional[:class:`bool`] Whether this container has the spoiler overlay. @@ -180,7 +180,7 @@ def remove_item(self, item: ViewItem | str | int) -> Self: Parameters ---------- - item: Union[:class:`ViewItem`, :class:`int`, :class:`str`] + item: :class:`ViewItem` | :class:`int` | :class:`str` The item, ``id``, or item ``custom_id`` to remove from the container. """ @@ -203,7 +203,7 @@ def get_item(self, id: str | int) -> ViewItem | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The id or custom_id of the item to get. Returns @@ -233,7 +233,7 @@ def add_row( Parameters ---------- - *items: Union[:class:`Button`, :class:`Select`] + *items: :class:`Button` | :class:`Select` The items this action row contains. id: Optional[:class:`int`] The action row's ID. diff --git a/discord/ui/core.py b/discord/ui/core.py index f7acaaf114..cc79d2cd49 100644 --- a/discord/ui/core.py +++ b/discord/ui/core.py @@ -122,7 +122,7 @@ def get_item(self, custom_id: str | int) -> Item | None: Parameters ---------- - custom_id: Union[:class:`str`, :class:`int`] + custom_id: :class:`str` | :class:`int` The id of the item to get Returns diff --git a/discord/ui/label.py b/discord/ui/label.py index cbec8ff1bb..da35e7f18e 100644 --- a/discord/ui/label.py +++ b/discord/ui/label.py @@ -147,7 +147,7 @@ def set_item(self, item: ModalItem) -> Self: Parameters ---------- - item: Union[:class:`ModalItem`] + item: :class:`ModalItem` The item to set. Raises @@ -174,7 +174,7 @@ def get_item(self, id: str | int) -> ModalItem | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The id or custom_id of the item to match. Returns @@ -334,7 +334,7 @@ def set_select( Whether the select is required or not. Defaults to ``True``. id: Optional[:class:`int`] The select menu's ID. - default_values: Optional[Sequence[Union[:class:`discord.SelectDefaultValue`, :class:`discord.abc.Snowflake`]]] + default_values: Optional[Sequence[:class:`discord.SelectDefaultValue` | :class:`discord.abc.Snowflake`]] The default values of this select. Only applicable if :attr:`.select_type` is not :attr:`discord.ComponentType.string_select`. These can be either :class:`discord.SelectDefaultValue` instances or models, which will be converted into :class:`discord.SelectDefaultValue` diff --git a/discord/ui/modal.py b/discord/ui/modal.py index 8b35ecd889..2001700f0b 100644 --- a/discord/ui/modal.py +++ b/discord/ui/modal.py @@ -180,7 +180,7 @@ def add_item(self, item: ModalItem) -> Self: Parameters ---------- - item: Union[:class:`ModalItem`] + item: :class:`ModalItem` The item to add to the modal """ @@ -270,7 +270,7 @@ class Modal(BaseModal): Parameters ---------- - children: Union[:class:`InputText`] + children: :class:`InputText` The initial items that are displayed in the modal. Only supports :class:`discord.ui.InputText`; for newer modal features, see :class:`DesignerModal`. title: :class:`str` The title of the modal. @@ -354,7 +354,7 @@ def remove_item(self, item: InputText) -> Self: Parameters ---------- - item: Union[class:`InputText`] + item: class:`InputText` The item to remove from the modal. """ @@ -387,7 +387,7 @@ class DesignerModal(BaseModal): Parameters ---------- - children: Union[:class:`ModalItem`] + children: :class:`ModalItem` The initial items that are displayed in the modal.. title: :class:`str` The title of the modal. @@ -437,7 +437,7 @@ def add_item(self, item: ModalItem) -> Self: Parameters ---------- - item: Union[:class:`ModalItem`] + item: :class:`ModalItem` The item to add to the modal """ diff --git a/discord/ui/section.py b/discord/ui/section.py index f0a5f95ac0..8529595575 100644 --- a/discord/ui/section.py +++ b/discord/ui/section.py @@ -171,7 +171,7 @@ def remove_item(self, item: ViewItem | str | int) -> Self: Parameters ---------- - item: Union[:class:`ViewItem`, :class:`int`, :class:`str`] + item: :class:`ViewItem` | :class:`int` | :class:`str` The item, item ``id``, or item ``custom_id`` to remove from the section. """ @@ -193,7 +193,7 @@ def get_item(self, id: int | str) -> ViewItem | None: Parameters ---------- - id: Union[:class:`str`, :class:`int`] + id: :class:`str` | :class:`int` The id or custom_id of the item to get. Returns diff --git a/discord/ui/select.py b/discord/ui/select.py index cd7e17dc7e..5643af35ff 100644 --- a/discord/ui/select.py +++ b/discord/ui/select.py @@ -136,7 +136,7 @@ class Select(ViewItem[V], ModalItem[M], Generic[V, M, ST]): Whether the select is required or not. Only useable when added to :class:`Label` for modals. Defaults to ``True`` in modals. .. versionadded:: 2.7 - default_values: Optional[Sequence[Union[:class:`discord.SelectDefaultValue`, :class:`discord.abc.Snowflake`]]] + default_values: Optional[Sequence[:class:`discord.SelectDefaultValue` | :class:`discord.abc.Snowflake`]] The default values of this select. Only applicable if :attr:`.select_type` is not :attr:`discord.ComponentType.string_select`. These can be either :class:`discord.SelectDefaultValue` instances or models, which will be converted into :class:`discord.SelectDefaultValue` @@ -552,7 +552,7 @@ def append_default_value( Parameters ---------- - value: Union[:class:`discord.SelectDefaultValue`, :class:`discord.abc.Snowflake`] + value: :class:`discord.SelectDefaultValue` | :class:`discord.abc.Snowflake` The default value to append to this select. These can be either :class:`discord.SelectDefaultValue` instances or models, which will be converted into :class:`discord.SelectDefaultvalue` @@ -632,7 +632,7 @@ def add_option( description: Optional[:class:`str`] An additional description of the option, if any. Can only be up to 100 characters. - emoji: Optional[Union[:class:`str`, :class:`GuildEmoji`, :class:`AppEmoji`, :class:`.PartialEmoji`]] + emoji: Optional[:class:`str` | :class:`GuildEmoji` | :class:`AppEmoji` | :class:`.PartialEmoji`] The emoji of the option, if available. This can either be a string representing the custom or unicode emoji or an instance of :class:`.PartialEmoji`, :class:`GuildEmoji`, or :class:`AppEmoji`. default: :class:`bool` @@ -972,7 +972,7 @@ def select( Whether the select is disabled or not. Defaults to ``False``. id: Optional[:class:`int`] The select menu's ID. - default_values: Optional[Sequence[Union[:class:`discord.SelectDefaultValue`, :class:`discord.abc.Snowflake`]]] + default_values: Optional[Sequence[:class:`discord.SelectDefaultValue` | :class:`discord.abc.Snowflake`]] The default values of this select. Only applicable if :attr:`.select_type` is not :attr:`discord.ComponentType.string_select`. This can be either :class:`discord.SelectDefaultValue` instances or models, which will be converted into :class:`discord.SelectDefaultValue` diff --git a/discord/ui/view.py b/discord/ui/view.py index fdc478b868..ddea9ee750 100644 --- a/discord/ui/view.py +++ b/discord/ui/view.py @@ -275,7 +275,7 @@ def remove_item(self, item: ViewItem[V] | int | str) -> Self: Parameters ---------- - item: Union[:class:`ViewItem`, :class:`int`, :class:`str`] + item: :class:`ViewItem` | :class:`int` | :class:`str` The item, item ``id``, or item ``custom_id`` to remove from the view. Returns @@ -741,7 +741,7 @@ def remove_item(self, item: ViewItem[V] | int | str) -> Self: Parameters ---------- - item: Union[:class:`ViewItem`, :class:`int`, :class:`str`] + item: :class:`ViewItem` | :class:`int` | :class:`str` The item, item ``id``, or item ``custom_id`` to remove from the view. """ diff --git a/discord/utils.py b/discord/utils.py index 4da6449fde..84765568ca 100644 --- a/discord/utils.py +++ b/discord/utils.py @@ -178,7 +178,7 @@ class _RequestLike(Protocol): T = TypeVar("T") T_co = TypeVar("T_co", covariant=True) -_Iter = Union[Iterator[T], AsyncIterator[T]] +_Iter = Iterator[T] | AsyncIterator[T] class CachedSlotProperty(Generic[T, T_co]): @@ -408,7 +408,7 @@ def oauth_url( Parameters ---------- - client_id: Union[:class:`int`, :class:`str`] + client_id: :class:`int` | :class:`str` The client ID for your bot. permissions: :class:`~discord.Permissions` The permissions you're requesting. If not given then you won't be requesting any @@ -1001,7 +1001,7 @@ def resolve_invite(invite: Invite | str) -> str: Parameters ---------- - invite: Union[:class:`~discord.Invite`, :class:`str`] + invite: :class:`~discord.Invite` | :class:`str` The invite. Returns @@ -1028,7 +1028,7 @@ def resolve_template(code: Template | str) -> str: Parameters ---------- - code: Union[:class:`~discord.Template`, :class:`str`] + code: :class:`~discord.Template` | :class:`str` The code. Returns @@ -1274,14 +1274,14 @@ def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[list[T]]: Parameters ---------- - iterator: Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`] + iterator: :class:`collections.abc.Iterator` | :class:`collections.abc.AsyncIterator` The iterator to chunk, can be sync or async. max_size: :class:`int` The maximum chunk size. Returns ------- - Union[:class:`collections.abc.Iterator`, :class:`collections.abc.AsyncIterator`] + :class:`collections.abc.Iterator` | :class:`collections.abc.AsyncIterator` A new iterator which yields chunks of a given size. """ if max_size <= 0: @@ -1412,7 +1412,7 @@ def format_dt( Parameters ---------- - dt: Union[:class:`datetime.datetime`, :class:`datetime.time`] + dt: :class:`datetime.datetime` | :class:`datetime.time` The datetime to format. style: :class:`str` The style to format the datetime with. @@ -1449,11 +1449,11 @@ def generate_snowflake(dt: datetime.datetime | None = None) -> int: return int(dt.timestamp() * 1000 - DISCORD_EPOCH) << 22 | 0x3FFFFF -V = Union[Iterable[OptionChoice], Iterable[str], Iterable[int], Iterable[float]] +V = Iterable[OptionChoice] | Iterable[str] | Iterable[int] | Iterable[float] AV = Awaitable[V] -Values = Union[V, Callable[[AutocompleteContext], Union[V, AV]], AV] +Values = V | Callable[[AutocompleteContext], V | AV] | AV AutocompleteFunc = Callable[[AutocompleteContext], AV] -FilterFunc = Callable[[AutocompleteContext, Any], Union[bool, Awaitable[bool]]] +FilterFunc = Callable[[AutocompleteContext, Any], bool | Awaitable[bool]] def basic_autocomplete( @@ -1467,10 +1467,10 @@ def basic_autocomplete( Parameters ---------- - values: Union[Union[Iterable[:class:`.OptionChoice`], Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]], Callable[[:class:`.AutocompleteContext`], Union[Union[Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]], Awaitable[Union[Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]]]]], Awaitable[Union[Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]]]] + values: Iterable[:class:`.OptionChoice`] | Iterable[:class:`str`] | Iterable[:class:`int`] | Iterable[:class:`float`] | Callable[[:class:`.AutocompleteContext`], Iterable[:class:`str`] | Iterable[:class:`int`] | Iterable[:class:`float`] | Awaitable[Iterable[:class:`str`] | Iterable[:class:`int`] | Iterable[:class:`float`]]] | Awaitable[Iterable[:class:`str`] | Iterable[:class:`int`] | Iterable[:class:`float`]] Possible values for the option. Accepts an iterable of :class:`str`, a callable (sync or async) that takes a single argument of :class:`.AutocompleteContext`, or a coroutine. Must resolve to an iterable of :class:`str`. - filter: Optional[Callable[[:class:`.AutocompleteContext`, Any], Union[:class:`bool`, Awaitable[:class:`bool`]]]] + filter: Optional[Callable[[:class:`.AutocompleteContext`, Any], :class:`bool` | Awaitable[:class:`bool`]]] An optional callable (sync or async) used to filter the autocomplete options. It accepts two arguments: the :class:`.AutocompleteContext` and an item from ``values`` iteration treated as callback parameters. If ``None`` is provided, a default filter is used that includes items whose string representation starts with the user's input value, case-insensitive. @@ -1478,7 +1478,7 @@ def basic_autocomplete( Returns ------- - Callable[[:class:`.AutocompleteContext`], Awaitable[Union[Iterable[:class:`.OptionChoice`], Iterable[:class:`str`], Iterable[:class:`int`], Iterable[:class:`float`]]]] + Callable[[:class:`.AutocompleteContext`], Awaitable[Iterable[:class:`.OptionChoice`] | Iterable[:class:`str`] | Iterable[:class:`int`] | Iterable[:class:`float`]]] A wrapped callback for the autocomplete. Examples diff --git a/discord/voice/client.py b/discord/voice/client.py index 64d879ac95..ee5668812e 100644 --- a/discord/voice/client.py +++ b/discord/voice/client.py @@ -85,7 +85,7 @@ class VoiceClient(VoiceProtocol): Attributes ---------- - channel: Union[:class:`VoiceChannel`, :class:`StageChannel`] + channel: :class:`VoiceChannel` | :class:`StageChannel` The channel we are connected to. Warning diff --git a/discord/welcome_screen.py b/discord/welcome_screen.py index cb0d1eea0a..bd8a2ab21b 100644 --- a/discord/welcome_screen.py +++ b/discord/welcome_screen.py @@ -58,7 +58,7 @@ class WelcomeScreenChannel: The channel that is being referenced. description: :class:`str` The description of the channel that is shown on the welcome screen. - emoji: Union[:class:`GuildEmoji`, :class:`PartialEmoji`, :class:`str`] + emoji: :class:`GuildEmoji` | :class:`PartialEmoji` | :class:`str` The emoji of the channel that is shown on welcome screen. """ diff --git a/discord/widget.py b/discord/widget.py index b6bcf0f013..6522d4a49e 100644 --- a/discord/widget.py +++ b/discord/widget.py @@ -142,7 +142,7 @@ class WidgetMember(BaseUser): The member's nickname. avatar: Optional[:class:`str`] The member's avatar hash. - activity: Optional[Union[:class:`BaseActivity`, :class:`Spotify`]] + activity: Optional[:class:`BaseActivity` | :class:`Spotify`] The member's activity. deafened: Optional[:class:`bool`] Whether the member is currently deafened. diff --git a/examples/app_commands/slash_options.py b/examples/app_commands/slash_options.py index be625738b1..a3372ca461 100644 --- a/examples/app_commands/slash_options.py +++ b/examples/app_commands/slash_options.py @@ -1,5 +1,3 @@ -from typing import Union - import discord from discord import option @@ -41,7 +39,7 @@ async def hello( @bot.slash_command(name="channel") @option( "channel", - Union[discord.TextChannel, discord.VoiceChannel], + discord.TextChannel | discord.VoiceChannel, # You can specify allowed channel types by passing a union of them like this. description="Select a channel", ) From 51380691e2f9ae0885044ddd69c5cb95a68ca09a Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Sat, 10 Oct 2026 18:56:44 +0200 Subject: [PATCH 2/8] Revert changes in iterators.py as it seems to break badly --- discord/iterators.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/discord/iterators.py b/discord/iterators.py index 13fe75b2e1..7d58419834 100644 --- a/discord/iterators.py +++ b/discord/iterators.py @@ -187,7 +187,7 @@ async def next(self) -> T: return item -class ReactionIterator(_AsyncIterator["User" | "Member"]): +class ReactionIterator(_AsyncIterator[Union["User", "Member"]]): def __init__(self, message, emoji, limit=100, after=None, type=None): self.message = message self.limit = limit @@ -243,7 +243,7 @@ async def fill_users(self): await self.users.put(User(state=self.state, data=element)) -class VoteIterator(_AsyncIterator["User" | "Member"]): +class VoteIterator(_AsyncIterator[Union["User", "Member"]]): def __init__(self, message, answer, limit=100, after=None): self.message = message self.limit = limit @@ -888,7 +888,7 @@ def create_thread(self, data: ThreadPayload) -> Thread: return Thread(guild=self.guild, state=self.guild._state, data=data) -class ScheduledEventSubscribersIterator(_AsyncIterator["User" | "Member"]): +class ScheduledEventSubscribersIterator(_AsyncIterator[Union["User", "Member"]]): def __init__( self, event: ScheduledEvent, From 4453f2952d8646552982e03429c596a541f6b6ac Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Sat, 10 Oct 2026 18:58:59 +0200 Subject: [PATCH 3/8] Revert changes in iterators.py as it seems to break badly part 2 --- discord/iterators.py | 1 + 1 file changed, 1 insertion(+) diff --git a/discord/iterators.py b/discord/iterators.py index 7d58419834..b8f0a8e639 100644 --- a/discord/iterators.py +++ b/discord/iterators.py @@ -32,6 +32,7 @@ TYPE_CHECKING, Any, TypeVar, + Union, ) from typing_extensions import deprecated, override From 51bb94492be6359ee546188d9aa3b7727dd48c84 Mon Sep 17 00:00:00 2001 From: ToothyDev <55001472+ToothyDev@users.noreply.github.com> Date: Sat, 10 Oct 2026 19:34:56 +0200 Subject: [PATCH 4/8] Apply batched suggestions from code review Co-authored-by: Michael Signed-off-by: ToothyDev <55001472+ToothyDev@users.noreply.github.com> --- discord/abc.py | 6 +++--- discord/ext/commands/_types.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/discord/abc.py b/discord/abc.py index 1205bd4ede..84624f03ec 100644 --- a/discord/abc.py +++ b/discord/abc.py @@ -1270,7 +1270,7 @@ async def create_invite( .. versionadded:: 2.0 - roles: Optional[List[:class:.Role | :class:.Object]] + roles: Optional[List[:class:`.Role` | :class:`.Object`]] The roles to give a user when joining through this invite. You must have the :attr:`~Permissions.manage_roles` permission to do this and roles cannot be higher than your own. @@ -1530,7 +1530,7 @@ async def send( .. versionadded:: 1.4 - reference: :class:~discord.Message | :class:~discord.MessageReference | :class:~discord.PartialMessage + reference: :class:`~discord.Message` | :class:`~discord.MessageReference` | :class:`~discord.PartialMessage` A reference to the :class:`~discord.Message` being replied to or forwarded. This can be created using :meth:`~discord.Message.to_reference`. When replying, you can control whether this mentions the author of the referenced message using the @@ -1549,7 +1549,7 @@ async def send( A list of embeds to upload. Must be a maximum of 10. .. versionadded:: 2.0 - stickers: Sequence[:class:~discord.GuildSticker | :class:~discord.StickerItem] + stickers: Sequence[:class:`~discord.GuildSticker` | :class:`~discord.StickerItem`] A list of stickers to upload. Must be a maximum of 3. .. versionadded:: 2.0 diff --git a/discord/ext/commands/_types.py b/discord/ext/commands/_types.py index 83cae7ab72..1272dfd9fe 100644 --- a/discord/ext/commands/_types.py +++ b/discord/ext/commands/_types.py @@ -49,5 +49,5 @@ Error = ( Callable[["Cog", "Context[Any]", "CommandError"], Coro[Any]] - | Callable[["Context[Any]", "CommandError"], Coro[Any]], + | Callable[["Context[Any]", "CommandError"], Coro[Any]] ) From 6e29b66c1203cab51649f5e30e47f6aed1ad5e88 Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Sat, 10 Oct 2026 21:39:31 +0200 Subject: [PATCH 5/8] Undo accidental change --- discord/ext/commands/flags.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord/ext/commands/flags.py b/discord/ext/commands/flags.py index 674accdcf0..a829377244 100644 --- a/discord/ext/commands/flags.py +++ b/discord/ext/commands/flags.py @@ -478,7 +478,7 @@ async def convert_flag(ctx, argument: str, flag: Flag, annotation: Any = None) - return await convert_flag(ctx, argument, flag, annotation) elif origin is Union and annotation.__args__[-1] is type(None): # typing.Optional[x] - annotation = annotation.__args__[:-1] + annotation = Union[annotation.__args__[:-1]] return await run_converters(ctx, annotation, argument, param) elif origin is dict: # typing.Dict[K, V] -> typing.Tuple[K, V] From c8c54001568a6c121d9d8337f1b0fbf43c36bfb3 Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Mon, 12 Oct 2026 12:40:19 +0200 Subject: [PATCH 6/8] Apply change requests --- discord/ui/modal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/discord/ui/modal.py b/discord/ui/modal.py index 2001700f0b..5cb9cdf640 100644 --- a/discord/ui/modal.py +++ b/discord/ui/modal.py @@ -354,7 +354,7 @@ def remove_item(self, item: InputText) -> Self: Parameters ---------- - item: class:`InputText` + item: :class:`InputText` The item to remove from the modal. """ From 00d193f6ac363df52136972f8389fd14d60d6155 Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Mon, 12 Oct 2026 12:47:03 +0200 Subject: [PATCH 7/8] Remove duplicated return types in docstrings --- discord/client.py | 2 +- discord/commands/context.py | 14 ++++++-------- discord/ext/commands/context.py | 7 ++----- discord/interactions.py | 8 ++++---- discord/monetization.py | 2 +- discord/role.py | 2 +- discord/soundboard.py | 6 +++--- 7 files changed, 18 insertions(+), 23 deletions(-) diff --git a/discord/client.py b/discord/client.py index 92c2cf48b0..6bd5ef67ee 100644 --- a/discord/client.py +++ b/discord/client.py @@ -2229,7 +2229,7 @@ def entitlements( @property def store_url(self) -> str: - """:class:`str`: The URL that leads to the application's store page for monetization. + """The URL that leads to the application's store page for monetization. .. versionadded:: 2.6 """ diff --git a/discord/commands/context.py b/discord/commands/context.py index e3c4d1a7df..da0289d66c 100644 --- a/discord/commands/context.py +++ b/discord/commands/context.py @@ -144,9 +144,7 @@ def command(self, value: ApplicationCommand | None) -> None: @property def channel(self) -> InteractionChannel | None: - """:class:`abc.GuildChannel` | :class:`PartialMessageable` | :class:`Thread`: - Returns the channel associated with this context's command. Shorthand for :attr:`.Interaction.channel`. - """ + """Returns the channel associated with this context's command. Shorthand for :attr:`.Interaction.channel`.""" return self.interaction.channel @property @@ -190,7 +188,7 @@ def app_permissions(self) -> Permissions: @property def me(self) -> Member | ClientUser | None: - """:class:`.Member` | :class:`.ClientUser`: + """ Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message message contexts, or when :meth:`Intents.guilds` is absent. """ @@ -390,7 +388,7 @@ def cog(self) -> Cog | None: return self.command.cog def is_guild_authorised(self) -> bool: - """:class:`bool`: Checks if the invoked command is guild-installed. + """Checks if the invoked command is guild-installed. This is a shortcut for :meth:`Interaction.is_guild_authorised`. There is an alias for this called :meth:`.is_guild_authorized`. @@ -400,7 +398,7 @@ def is_guild_authorised(self) -> bool: return self.interaction.is_guild_authorised() def is_user_authorised(self) -> bool: - """:class:`bool`: Checks if the invoked command is user-installed. + """Checks if the invoked command is user-installed. This is a shortcut for :meth:`Interaction.is_user_authorised`. There is an alias for this called :meth:`.is_user_authorized`. @@ -410,14 +408,14 @@ def is_user_authorised(self) -> bool: return self.interaction.is_user_authorised() def is_guild_authorized(self) -> bool: - """:class:`bool`: An alias for :meth:`.is_guild_authorised`. + """An alias for :meth:`.is_guild_authorised`. .. versionadded:: 2.7 """ return self.is_guild_authorised() def is_user_authorized(self) -> bool: - """:class:`bool`: An alias for :meth:`.is_user_authorised`. + """An alias for :meth:`.is_user_authorised`. .. versionadded:: 2.7 """ diff --git a/discord/ext/commands/context.py b/discord/ext/commands/context.py index 7223afd357..ae06eafb79 100644 --- a/discord/ext/commands/context.py +++ b/discord/ext/commands/context.py @@ -299,15 +299,12 @@ def channel(self) -> MessageableChannel: @property def author(self) -> User | Member: - """:class:`~discord.User` | :class:`.Member`: - Returns the author associated with this context's command. Shorthand for :attr:`.Message.author` - """ + """Returns the author associated with this context's command. Shorthand for :attr:`.Message.author`""" return self.message.author @property def me(self) -> Member | ClientUser: - """:class:`.Member` | :class:`.ClientUser`: - Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message + """Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message message contexts, or when :meth:`Intents.guilds` is absent. """ # bot.user will never be None at this point. diff --git a/discord/interactions.py b/discord/interactions.py index 380a71618a..9c7506b495 100644 --- a/discord/interactions.py +++ b/discord/interactions.py @@ -417,7 +417,7 @@ def followup(self) -> Webhook: return Webhook.from_interaction(interaction=self) def is_guild_authorised(self) -> bool: - """:class:`bool`: Checks if the interaction is guild authorised. + """Checks if the interaction is guild authorised. There is an alias for this called :meth:`.is_guild_authorized`. @@ -428,7 +428,7 @@ def is_guild_authorised(self) -> bool: return False def is_user_authorised(self) -> bool: - """:class:`bool`: Checks if the interaction is user authorised. + """Checks if the interaction is user authorised. There is an alias for this called :meth:`.is_user_authorized`. @@ -441,7 +441,7 @@ def is_user_authorised(self) -> bool: return False def is_guild_authorized(self) -> bool: - """:class:`bool`: Checks if the interaction is guild authorized. + """Checks if the interaction is guild authorized. There is an alias for this called :meth:`.is_guild_authorised`. @@ -450,7 +450,7 @@ def is_guild_authorized(self) -> bool: return self.is_guild_authorised() def is_user_authorized(self) -> bool: - """:class:`bool`: Checks if the interaction is user authorized. + """Checks if the interaction is user authorized. There is an alias for this called :meth:`.is_user_authorised`. diff --git a/discord/monetization.py b/discord/monetization.py index 7595d53087..717d2f69e7 100644 --- a/discord/monetization.py +++ b/discord/monetization.py @@ -104,7 +104,7 @@ def __eq__(self, other: object) -> bool: @property def url(self) -> str: - """:class:`str`: Returns the URL for the SKU.""" + """Returns the URL for the SKU.""" return f"https://discord.com/application-directory/{self.application_id}/store/{self.id}" def fetch_subscriptions( diff --git a/discord/role.py b/discord/role.py index ac4603ae9f..3503ab6ff5 100644 --- a/discord/role.py +++ b/discord/role.py @@ -172,7 +172,7 @@ def __init__(self, data: RoleTagPayload): @cached_slot_property("_type") def type(self) -> RoleType: - """:class:`RoleType`: The type of the role. + """The type of the role. Role tags are a fairly complex topic, since it's usually hard to determine which role tag combination represents which role type. In order to make your life easier, pycord provides a :attr:`RoleTags.type` attribute that attempts to determine the role type based on the role tags. Its value is not provided by Discord but is rather computed based on the role tags. diff --git a/discord/soundboard.py b/discord/soundboard.py index 35e2740b77..4012ef2b22 100644 --- a/discord/soundboard.py +++ b/discord/soundboard.py @@ -112,7 +112,7 @@ def __ne__( @property def file(self) -> Asset: - """:class:`Asset`: Returns the sound's file.""" + """Returns the sound's file.""" return Asset._from_soundboard_sound(self._state, sound_id=self.id) def __repr__(self) -> str: @@ -174,7 +174,7 @@ def _from_data( @cached_slot_property("_cs_guild") def guild(self) -> Guild | None: - """:class:`Guild` | :class:`None` The guild the sound belongs to. Could be :class:`None` if the sound is a default sound.""" + """The guild the sound belongs to. Could be :class:`None` if the sound is a default sound.""" return self._state._get_guild(self.guild_id) if self.guild_id else None @override @@ -185,7 +185,7 @@ def __eq__( @property def is_default_sound(self) -> bool: - """:class:`bool`: Whether the sound is a default sound.""" + """Whether the sound is a default sound.""" return self.guild_id is None def edit( From 11f753543450b716e80fcf3f00d4bb6ef899f4ca Mon Sep 17 00:00:00 2001 From: ToothyDev Date: Tue, 20 Oct 2026 16:57:58 +0200 Subject: [PATCH 8/8] can't accept this sorry --- discord/commands/context.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/discord/commands/context.py b/discord/commands/context.py index da0289d66c..565fd5ee21 100644 --- a/discord/commands/context.py +++ b/discord/commands/context.py @@ -188,8 +188,7 @@ def app_permissions(self) -> Permissions: @property def me(self) -> Member | ClientUser | None: - """ - Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message + """Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message message contexts, or when :meth:`Intents.guilds` is absent. """ return (