Browse Source

Reformat entire project with ruff instead of black

pull/10266/head
Rapptz 1 week ago
parent
commit
44a44e938f
  1. 6
      .github/workflows/lint.yml
  2. 2
      discord/__init__.py
  3. 4
      discord/__main__.py
  4. 46
      discord/abc.py
  5. 6
      discord/activity.py
  6. 5
      discord/app_commands/checks.py
  7. 38
      discord/app_commands/commands.py
  8. 6
      discord/app_commands/namespace.py
  9. 18
      discord/app_commands/translator.py
  10. 39
      discord/app_commands/tree.py
  11. 2
      discord/appinfo.py
  12. 8
      discord/asset.py
  13. 8
      discord/audit_logs.py
  14. 26
      discord/automod.py
  15. 9
      discord/backoff.py
  16. 55
      discord/channel.py
  17. 200
      discord/client.py
  18. 3
      discord/embeds.py
  19. 2
      discord/enums.py
  20. 2
      discord/errors.py
  21. 11
      discord/ext/commands/_types.py
  22. 19
      discord/ext/commands/bot.py
  23. 1
      discord/ext/commands/cog.py
  24. 43
      discord/ext/commands/context.py
  25. 6
      discord/ext/commands/converter.py
  26. 4
      discord/ext/commands/cooldowns.py
  27. 63
      discord/ext/commands/core.py
  28. 2
      discord/ext/commands/errors.py
  29. 2
      discord/ext/commands/flags.py
  30. 2
      discord/ext/commands/help.py
  31. 3
      discord/ext/commands/parameters.py
  32. 32
      discord/ext/commands/view.py
  33. 6
      discord/flags.py
  34. 4
      discord/gateway.py
  35. 52
      discord/guild.py
  36. 30
      discord/http.py
  37. 17
      discord/interactions.py
  38. 2
      discord/invite.py
  39. 52
      discord/message.py
  40. 12
      discord/opus.py
  41. 10
      discord/permissions.py
  42. 15
      discord/player.py
  43. 2
      discord/poll.py
  44. 1
      discord/presences.py
  45. 2
      discord/primary_guild.py
  46. 18
      discord/role.py
  47. 15
      discord/scheduled_event.py
  48. 2
      discord/shard.py
  49. 1
      discord/sku.py
  50. 4
      discord/soundboard.py
  51. 11
      discord/state.py
  52. 3
      discord/types/automod.py
  53. 2
      discord/types/command.py
  54. 6
      discord/types/guild.py
  55. 3
      discord/types/invite.py
  56. 9
      discord/types/scheduled_event.py
  57. 3
      discord/types/webhook.py
  58. 16
      discord/ui/action_row.py
  59. 1
      discord/ui/media_gallery.py
  60. 2
      discord/ui/modal.py
  61. 1
      discord/ui/section.py
  62. 20
      discord/ui/select.py
  63. 1
      discord/ui/separator.py
  64. 8
      discord/ui/view.py
  65. 4
      discord/user.py
  66. 84
      discord/utils.py
  67. 6
      discord/voice_client.py
  68. 2
      discord/voice_state.py
  69. 20
      discord/webhook/async_.py
  70. 18
      discord/webhook/sync.py
  71. 4
      discord/widget.py
  72. 2
      examples/advanced_startup.py
  73. 1
      examples/app_commands/basic.py
  74. 2
      examples/app_commands/transformers.py
  75. 4
      examples/basic_bot.py
  76. 10
      examples/basic_voice.py
  77. 2
      examples/converters.py
  78. 2
      examples/custom_context.py
  79. 2
      examples/modals/basic.py
  80. 2
      examples/modals/label.py
  81. 3
      examples/secret.py
  82. 1
      examples/views/counter.py
  83. 2
      examples/views/dropdown.py
  84. 1
      examples/views/dynamic_counter.py
  85. 1
      examples/views/ephemeral.py
  86. 28
      examples/views/settings.py
  87. 1
      examples/views/tic_tac_toe.py
  88. 9
      pyproject.toml

6
.github/workflows/lint.yml

@ -27,7 +27,7 @@ jobs:
- name: Install dependencies - name: Install dependencies
id: install-deps id: install-deps
run: | run: |
python -m pip install --upgrade pip setuptools wheel black==22.6 requests python -m pip install --upgrade pip setuptools wheel ruff==0.12 requests
pip install -U -r requirements.txt pip install -U -r requirements.txt
- name: Setup node.js - name: Setup node.js
@ -42,7 +42,7 @@ jobs:
warnings: false warnings: false
no-comments: ${{ matrix.python-version != '3.x' }} no-comments: ${{ matrix.python-version != '3.x' }}
- name: Run black - name: Run ruff
if: ${{ always() && steps.install-deps.outcome == 'success' }} if: ${{ always() && steps.install-deps.outcome == 'success' }}
run: | run: |
black --check discord examples ruff format --check discord examples

2
discord/__init__.py

@ -81,7 +81,7 @@ class VersionInfo(NamedTuple):
major: int major: int
minor: int minor: int
micro: int micro: int
releaselevel: Literal["alpha", "beta", "candidate", "final"] releaselevel: Literal['alpha', 'beta', 'candidate', 'final']
serial: int serial: int

4
discord/__main__.py

@ -133,7 +133,7 @@ async def setup(bot):
await bot.add_cog({name}(bot)) await bot.add_cog({name}(bot))
''' '''
_cog_extras = ''' _cog_extras = """
async def cog_load(self): async def cog_load(self):
# loading logic goes here # loading logic goes here
pass pass
@ -170,7 +170,7 @@ _cog_extras = '''
# called after a command is called here # called after a command is called here
pass pass
''' """
# certain file names and directory names are forbidden # certain file names and directory names are forbidden

46
discord/abc.py

@ -116,7 +116,7 @@ if TYPE_CHECKING:
PartialMessageableChannel = Union[TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable] PartialMessageableChannel = Union[TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable]
MessageableChannel = Union[PartialMessageableChannel, GroupChannel] MessageableChannel = Union[PartialMessageableChannel, GroupChannel]
SnowflakeTime = Union["Snowflake", datetime] SnowflakeTime = Union['Snowflake', datetime]
class PinnedMessage(Message): class PinnedMessage(Message):
pinned_at: datetime pinned_at: datetime
@ -140,7 +140,7 @@ class _PinsIterator:
def __await__(self) -> Generator[Any, None, List[PinnedMessage]]: def __await__(self) -> Generator[Any, None, List[PinnedMessage]]:
warnings.warn( warnings.warn(
"`await <channel>.pins()` is deprecated; use `async for message in <channel>.pins()` instead.", '`await <channel>.pins()` is deprecated; use `async for message in <channel>.pins()` instead.',
DeprecationWarning, DeprecationWarning,
stacklevel=2, stacklevel=2,
) )
@ -423,8 +423,7 @@ class GuildChannel:
if TYPE_CHECKING: if TYPE_CHECKING:
def __init__(self, *, state: ConnectionState, guild: Guild, data: GuildChannelPayload): def __init__(self, *, state: ConnectionState, guild: Guild, data: GuildChannelPayload): ...
...
def __str__(self) -> str: def __str__(self) -> str:
return self.name return self.name
@ -794,7 +793,6 @@ class GuildChannel:
default = self.guild.default_role default = self.guild.default_role
if default is None: if default is None:
if self._state.self_id == obj.id: if self._state.self_id == obj.id:
return Permissions._user_installed_permissions(in_guild=True) return Permissions._user_installed_permissions(in_guild=True)
else: else:
@ -907,8 +905,7 @@ class GuildChannel:
*, *,
overwrite: Optional[Union[PermissionOverwrite, _Undefined]] = ..., overwrite: Optional[Union[PermissionOverwrite, _Undefined]] = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> None: ) -> None: ...
...
@overload @overload
async def set_permissions( async def set_permissions(
@ -917,8 +914,7 @@ class GuildChannel:
*, *,
reason: Optional[str] = ..., reason: Optional[str] = ...,
**permissions: Unpack[_PermissionOverwriteKwargs], **permissions: Unpack[_PermissionOverwriteKwargs],
) -> None: ) -> None: ...
...
async def set_permissions( async def set_permissions(
self, self,
@ -1109,8 +1105,7 @@ class GuildChannel:
category: Optional[Snowflake] = MISSING, category: Optional[Snowflake] = MISSING,
sync_permissions: bool = MISSING, sync_permissions: bool = MISSING,
reason: Optional[str] = MISSING, reason: Optional[str] = MISSING,
) -> None: ) -> None: ...
...
@overload @overload
async def move( async def move(
@ -1121,8 +1116,7 @@ class GuildChannel:
category: Optional[Snowflake] = MISSING, category: Optional[Snowflake] = MISSING,
sync_permissions: bool = MISSING, sync_permissions: bool = MISSING,
reason: str = MISSING, reason: str = MISSING,
) -> None: ) -> None: ...
...
@overload @overload
async def move( async def move(
@ -1133,8 +1127,7 @@ class GuildChannel:
category: Optional[Snowflake] = MISSING, category: Optional[Snowflake] = MISSING,
sync_permissions: bool = MISSING, sync_permissions: bool = MISSING,
reason: str = MISSING, reason: str = MISSING,
) -> None: ) -> None: ...
...
@overload @overload
async def move( async def move(
@ -1145,8 +1138,7 @@ class GuildChannel:
category: Optional[Snowflake] = MISSING, category: Optional[Snowflake] = MISSING,
sync_permissions: bool = MISSING, sync_permissions: bool = MISSING,
reason: str = MISSING, reason: str = MISSING,
) -> None: ) -> None: ...
...
async def move(self, **kwargs: Any) -> None: async def move(self, **kwargs: Any) -> None:
"""|coro| """|coro|
@ -1428,8 +1420,7 @@ class Messageable:
view: LayoutView, view: LayoutView,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -1444,8 +1435,7 @@ class Messageable:
view: LayoutView, view: LayoutView,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -1465,8 +1455,7 @@ class Messageable:
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -1486,8 +1475,7 @@ class Messageable:
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -1507,8 +1495,7 @@ class Messageable:
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -1528,8 +1515,7 @@ class Messageable:
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
async def send( async def send(
self, self,
@ -2029,7 +2015,7 @@ class Messageable:
if limit is None: if limit is None:
raise ValueError('history does not support around with limit=None') raise ValueError('history does not support around with limit=None')
if limit > 101: if limit > 101:
raise ValueError("history max limit 101 when specifying around parameter") raise ValueError('history max limit 101 when specifying around parameter')
# Strange Discord quirk # Strange Discord quirk
limit = 100 if limit == 101 else limit limit = 100 if limit == 101 else limit

6
discord/activity.py

@ -861,13 +861,11 @@ ActivityTypes = Union[Activity, Game, CustomActivity, Streaming, Spotify]
@overload @overload
def create_activity(data: ActivityPayload, state: ConnectionState) -> ActivityTypes: def create_activity(data: ActivityPayload, state: ConnectionState) -> ActivityTypes: ...
...
@overload @overload
def create_activity(data: None, state: ConnectionState) -> None: def create_activity(data: None, state: ConnectionState) -> None: ...
...
def create_activity(data: Optional[ActivityPayload], state: ConnectionState) -> Optional[ActivityTypes]: def create_activity(data: Optional[ActivityPayload], state: ConnectionState) -> Optional[ActivityTypes]:

5
discord/app_commands/checks.py

@ -327,7 +327,7 @@ def has_permissions(**perms: Unpack[_PermissionsKwargs]) -> Callable[[T], T]:
invalid = perms.keys() - Permissions.VALID_FLAGS.keys() invalid = perms.keys() - Permissions.VALID_FLAGS.keys()
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(interaction: Interaction) -> bool: def predicate(interaction: Interaction) -> bool:
permissions = interaction.permissions permissions = interaction.permissions
@ -354,7 +354,7 @@ def bot_has_permissions(**perms: Unpack[_PermissionsKwargs]) -> Callable[[T], T]
invalid = set(perms) - set(Permissions.VALID_FLAGS) invalid = set(perms) - set(Permissions.VALID_FLAGS)
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(interaction: Interaction) -> bool: def predicate(interaction: Interaction) -> bool:
permissions = interaction.app_permissions permissions = interaction.app_permissions
@ -371,7 +371,6 @@ def bot_has_permissions(**perms: Unpack[_PermissionsKwargs]) -> Callable[[T], T]
def _create_cooldown_decorator( def _create_cooldown_decorator(
key: CooldownFunction[Hashable], factory: CooldownFunction[Optional[Cooldown]] key: CooldownFunction[Hashable], factory: CooldownFunction[Optional[Cooldown]]
) -> Callable[[T], T]: ) -> Callable[[T], T]:
mapping: Dict[Any, Cooldown] = {} mapping: Dict[Any, Cooldown] = {}
async def get_bucket( async def get_bucket(

38
discord/app_commands/commands.py

@ -219,7 +219,7 @@ def validate_context_menu_name(name: str) -> str:
def validate_auto_complete_callback( def validate_auto_complete_callback(
callback: AutocompleteCallback[GroupT, ChoiceT] callback: AutocompleteCallback[GroupT, ChoiceT],
) -> AutocompleteCallback[GroupT, ChoiceT]: ) -> AutocompleteCallback[GroupT, ChoiceT]:
# This function needs to ensure the following is true: # This function needs to ensure the following is true:
# If self.foo is passed then don't pass command.binding to the callback # If self.foo is passed then don't pass command.binding to the callback
@ -1491,9 +1491,9 @@ class Group:
__discord_app_commands_installation_types__: Optional[AppInstallationType] = MISSING __discord_app_commands_installation_types__: Optional[AppInstallationType] = MISSING
__discord_app_commands_default_permissions__: Optional[Permissions] = MISSING __discord_app_commands_default_permissions__: Optional[Permissions] = MISSING
__discord_app_commands_has_module__: bool = False __discord_app_commands_has_module__: bool = False
__discord_app_commands_error_handler__: Optional[ __discord_app_commands_error_handler__: Optional[Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]]] = (
Callable[[Interaction, AppCommandError], Coroutine[Any, Any, None]] None
] = None )
def __init_subclass__( def __init_subclass__(
cls, cls,
@ -2484,13 +2484,11 @@ def check(predicate: Check) -> Callable[[T], T]:
@overload @overload
def guild_only(func: None = ...) -> Callable[[T], T]: def guild_only(func: None = ...) -> Callable[[T], T]: ...
...
@overload @overload
def guild_only(func: T) -> T: def guild_only(func: T) -> T: ...
...
def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@ -2541,13 +2539,11 @@ def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@overload @overload
def private_channel_only(func: None = ...) -> Callable[[T], T]: def private_channel_only(func: None = ...) -> Callable[[T], T]: ...
...
@overload @overload
def private_channel_only(func: T) -> T: def private_channel_only(func: T) -> T: ...
...
def private_channel_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: def private_channel_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@ -2598,13 +2594,11 @@ def private_channel_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]
@overload @overload
def dm_only(func: None = ...) -> Callable[[T], T]: def dm_only(func: None = ...) -> Callable[[T], T]: ...
...
@overload @overload
def dm_only(func: T) -> T: def dm_only(func: T) -> T: ...
...
def dm_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: def dm_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@ -2697,13 +2691,11 @@ def allowed_contexts(guilds: bool = MISSING, dms: bool = MISSING, private_channe
@overload @overload
def guild_install(func: None = ...) -> Callable[[T], T]: def guild_install(func: None = ...) -> Callable[[T], T]: ...
...
@overload @overload
def guild_install(func: T) -> T: def guild_install(func: T) -> T: ...
...
def guild_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: def guild_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@ -2748,13 +2740,11 @@ def guild_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
@overload @overload
def user_install(func: None = ...) -> Callable[[T], T]: def user_install(func: None = ...) -> Callable[[T], T]: ...
...
@overload @overload
def user_install(func: T) -> T: def user_install(func: T) -> T: ...
...
def user_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]: def user_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:

6
discord/app_commands/namespace.py

@ -181,7 +181,7 @@ class Namespace:
guild_id = interaction.guild_id guild_id = interaction.guild_id
guild = interaction.guild guild = interaction.guild
type = AppCommandOptionType.user.value type = AppCommandOptionType.user.value
for (user_id, user_data) in resolved.get('users', {}).items(): for user_id, user_data in resolved.get('users', {}).items():
try: try:
member_data = members[user_id] member_data = members[user_id]
except KeyError: except KeyError:
@ -203,7 +203,7 @@ class Namespace:
) )
type = AppCommandOptionType.channel.value type = AppCommandOptionType.channel.value
for (channel_id, channel_data) in resolved.get('channels', {}).items(): for channel_id, channel_data in resolved.get('channels', {}).items():
key = ResolveKey(id=channel_id, type=type) key = ResolveKey(id=channel_id, type=type)
if channel_data['type'] in (10, 11, 12): if channel_data['type'] in (10, 11, 12):
# The guild ID can't be none in this case # The guild ID can't be none in this case
@ -220,7 +220,7 @@ class Namespace:
} }
) )
for (message_id, message_data) in resolved.get('messages', {}).items(): for message_id, message_data in resolved.get('messages', {}).items():
channel_id = int(message_data['channel_id']) channel_id = int(message_data['channel_id'])
if guild is None: if guild is None:
channel = PartialMessageable(state=state, guild_id=guild_id, id=channel_id) channel = PartialMessageable(state=state, guild_id=guild_id, id=channel_id)

18
discord/app_commands/translator.py

@ -76,38 +76,32 @@ class TranslationContext(Generic[_L, _D]):
@overload @overload
def __init__( def __init__(
self, location: Literal[TranslationContextLocation.command_name], data: Union[Command[Any, ..., Any], ContextMenu] self, location: Literal[TranslationContextLocation.command_name], data: Union[Command[Any, ..., Any], ContextMenu]
) -> None: ) -> None: ...
...
@overload @overload
def __init__( def __init__(
self, location: Literal[TranslationContextLocation.command_description], data: Command[Any, ..., Any] self, location: Literal[TranslationContextLocation.command_description], data: Command[Any, ..., Any]
) -> None: ) -> None: ...
...
@overload @overload
def __init__( def __init__(
self, self,
location: Literal[TranslationContextLocation.group_name, TranslationContextLocation.group_description], location: Literal[TranslationContextLocation.group_name, TranslationContextLocation.group_description],
data: Group, data: Group,
) -> None: ) -> None: ...
...
@overload @overload
def __init__( def __init__(
self, self,
location: Literal[TranslationContextLocation.parameter_name, TranslationContextLocation.parameter_description], location: Literal[TranslationContextLocation.parameter_name, TranslationContextLocation.parameter_description],
data: Parameter, data: Parameter,
) -> None: ) -> None: ...
...
@overload @overload
def __init__(self, location: Literal[TranslationContextLocation.choice_name], data: Choice[Any]) -> None: def __init__(self, location: Literal[TranslationContextLocation.choice_name], data: Choice[Any]) -> None: ...
...
@overload @overload
def __init__(self, location: Literal[TranslationContextLocation.other], data: Any) -> None: def __init__(self, location: Literal[TranslationContextLocation.other], data: Any) -> None: ...
...
def __init__(self, location: _L, data: _D) -> None: # type: ignore # pyright doesn't like the overloads def __init__(self, location: _L, data: _D) -> None: # type: ignore # pyright doesn't like the overloads
self.location: _L = location self.location: _L = location

39
discord/app_commands/tree.py

@ -419,8 +419,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.message, AppCommandType.user], type: Literal[AppCommandType.message, AppCommandType.user],
) -> Optional[ContextMenu]: ) -> Optional[ContextMenu]: ...
...
@overload @overload
def remove_command( def remove_command(
@ -430,8 +429,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.chat_input] = ..., type: Literal[AppCommandType.chat_input] = ...,
) -> Optional[Union[Command[Any, ..., Any], Group]]: ) -> Optional[Union[Command[Any, ..., Any], Group]]: ...
...
@overload @overload
def remove_command( def remove_command(
@ -441,8 +439,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: AppCommandType, type: AppCommandType,
) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: ...
...
def remove_command( def remove_command(
self, self,
@ -539,8 +536,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.message, AppCommandType.user], type: Literal[AppCommandType.message, AppCommandType.user],
) -> Optional[ContextMenu]: ) -> Optional[ContextMenu]: ...
...
@overload @overload
def get_command( def get_command(
@ -550,8 +546,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.chat_input] = ..., type: Literal[AppCommandType.chat_input] = ...,
) -> Optional[Union[Command[Any, ..., Any], Group]]: ) -> Optional[Union[Command[Any, ..., Any], Group]]: ...
...
@overload @overload
def get_command( def get_command(
@ -561,8 +556,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: AppCommandType, type: AppCommandType,
) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: ) -> Optional[Union[Command[Any, ..., Any], ContextMenu, Group]]: ...
...
def get_command( def get_command(
self, self,
@ -613,8 +607,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.message, AppCommandType.user], type: Literal[AppCommandType.message, AppCommandType.user],
) -> List[ContextMenu]: ) -> List[ContextMenu]: ...
...
@overload @overload
def get_commands( def get_commands(
@ -622,8 +615,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.chat_input], type: Literal[AppCommandType.chat_input],
) -> List[Union[Command[Any, ..., Any], Group]]: ) -> List[Union[Command[Any, ..., Any], Group]]: ...
...
@overload @overload
def get_commands( def get_commands(
@ -631,8 +623,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: AppCommandType, type: AppCommandType,
) -> Union[List[Union[Command[Any, ..., Any], Group]], List[ContextMenu]]: ) -> Union[List[Union[Command[Any, ..., Any], Group]], List[ContextMenu]]: ...
...
@overload @overload
def get_commands( def get_commands(
@ -640,8 +631,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Optional[AppCommandType] = ..., type: Optional[AppCommandType] = ...,
) -> List[Union[Command[Any, ..., Any], Group, ContextMenu]]: ) -> List[Union[Command[Any, ..., Any], Group, ContextMenu]]: ...
...
def get_commands( def get_commands(
self, self,
@ -693,8 +683,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.message, AppCommandType.user], type: Literal[AppCommandType.message, AppCommandType.user],
) -> Generator[ContextMenu, None, None]: ) -> Generator[ContextMenu, None, None]: ...
...
@overload @overload
def walk_commands( def walk_commands(
@ -702,8 +691,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: Literal[AppCommandType.chat_input] = ..., type: Literal[AppCommandType.chat_input] = ...,
) -> Generator[Union[Command[Any, ..., Any], Group], None, None]: ) -> Generator[Union[Command[Any, ..., Any], Group], None, None]: ...
...
@overload @overload
def walk_commands( def walk_commands(
@ -711,8 +699,7 @@ class CommandTree(Generic[ClientT]):
*, *,
guild: Optional[Snowflake] = ..., guild: Optional[Snowflake] = ...,
type: AppCommandType, type: AppCommandType,
) -> Union[Generator[Union[Command[Any, ..., Any], Group], None, None], Generator[ContextMenu, None, None]]: ) -> Union[Generator[Union[Command[Any, ..., Any], Group], None, None], Generator[ContextMenu, None, None]]: ...
...
def walk_commands( def walk_commands(
self, self,

2
discord/appinfo.py

@ -406,7 +406,7 @@ class AppInfo:
if install_params_scopes is None: if install_params_scopes is None:
install_params = None install_params = None
else: else:
if "bot" not in install_params_scopes and install_params_permissions is not MISSING: if 'bot' not in install_params_scopes and install_params_permissions is not MISSING:
raise ValueError("'bot' must be in install_params_scopes if install_params_permissions is set") raise ValueError("'bot' must be in install_params_scopes if install_params_permissions is set")
install_params['scopes'] = install_params_scopes install_params['scopes'] = install_params_scopes

8
discord/asset.py

@ -50,8 +50,8 @@ if TYPE_CHECKING:
ValidStaticFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png'] ValidStaticFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png']
ValidAssetFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png', 'gif'] ValidAssetFormatTypes = Literal['webp', 'jpeg', 'jpg', 'png', 'gif']
VALID_STATIC_FORMATS = frozenset({"jpeg", "jpg", "webp", "png"}) VALID_STATIC_FORMATS = frozenset({'jpeg', 'jpg', 'webp', 'png'})
VALID_ASSET_FORMATS = VALID_STATIC_FORMATS | {"gif"} VALID_ASSET_FORMATS = VALID_STATIC_FORMATS | {'gif'}
MISSING = utils.MISSING MISSING = utils.MISSING
@ -241,7 +241,7 @@ class Asset(AssetMixin):
format = 'gif' if animated else 'png' format = 'gif' if animated else 'png'
return cls( return cls(
state, state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024", url=f'{cls.BASE}/guilds/{guild_id}/users/{member_id}/avatars/{avatar}.{format}?size=1024',
key=avatar, key=avatar,
animated=animated, animated=animated,
) )
@ -252,7 +252,7 @@ class Asset(AssetMixin):
format = 'gif' if animated else 'png' format = 'gif' if animated else 'png'
return cls( return cls(
state, state,
url=f"{cls.BASE}/guilds/{guild_id}/users/{member_id}/banners/{banner}.{format}?size=1024", url=f'{cls.BASE}/guilds/{guild_id}/users/{member_id}/banners/{banner}.{format}?size=1024',
key=banner, key=banner,
animated=animated, animated=animated,
) )

8
discord/audit_logs.py

@ -306,14 +306,12 @@ class AuditLogDiff:
if TYPE_CHECKING: if TYPE_CHECKING:
def __getattr__(self, item: str) -> Any: def __getattr__(self, item: str) -> Any: ...
...
def __setattr__(self, key: str, value: Any) -> Any: def __setattr__(self, key: str, value: Any) -> Any: ...
...
Transformer = Callable[["AuditLogEntry", Any], Any] Transformer = Callable[['AuditLogEntry', Any], Any]
class AuditLogChanges: class AuditLogChanges:

26
discord/automod.py

@ -85,32 +85,27 @@ class AutoModRuleAction:
__slots__ = ('type', 'channel_id', 'duration', 'custom_message') __slots__ = ('type', 'channel_id', 'duration', 'custom_message')
@overload @overload
def __init__(self, *, channel_id: int = ...) -> None: def __init__(self, *, channel_id: int = ...) -> None: ...
...
@overload @overload
def __init__(self, *, type: Literal[AutoModRuleActionType.send_alert_message], channel_id: int = ...) -> None: def __init__(self, *, type: Literal[AutoModRuleActionType.send_alert_message], channel_id: int = ...) -> None: ...
...
@overload @overload
def __init__(self, *, duration: datetime.timedelta = ...) -> None: def __init__(self, *, duration: datetime.timedelta = ...) -> None: ...
...
@overload @overload
def __init__(self, *, type: Literal[AutoModRuleActionType.timeout], duration: datetime.timedelta = ...) -> None: def __init__(self, *, type: Literal[AutoModRuleActionType.timeout], duration: datetime.timedelta = ...) -> None: ...
...
@overload @overload
def __init__(self, *, custom_message: str = ...) -> None: def __init__(self, *, custom_message: str = ...) -> None: ...
...
@overload @overload
def __init__(self, *, type: Literal[AutoModRuleActionType.block_message]) -> None: def __init__(self, *, type: Literal[AutoModRuleActionType.block_message]) -> None: ...
...
@overload @overload
def __init__(self, *, type: Literal[AutoModRuleActionType.block_message], custom_message: Optional[str] = ...) -> None: def __init__(
... self, *, type: Literal[AutoModRuleActionType.block_message], custom_message: Optional[str] = ...
) -> None: ...
@overload @overload
def __init__( def __init__(
@ -120,8 +115,7 @@ class AutoModRuleAction:
channel_id: Optional[int] = ..., channel_id: Optional[int] = ...,
duration: Optional[datetime.timedelta] = ..., duration: Optional[datetime.timedelta] = ...,
custom_message: Optional[str] = ..., custom_message: Optional[str] = ...,
) -> None: ) -> None: ...
...
def __init__( def __init__(
self, self,

9
discord/backoff.py

@ -75,16 +75,13 @@ class ExponentialBackoff(Generic[T]):
self._randfunc: Callable[..., Union[int, float]] = rand.randrange if integral else rand.uniform self._randfunc: Callable[..., Union[int, float]] = rand.randrange if integral else rand.uniform
@overload @overload
def delay(self: ExponentialBackoff[Literal[False]]) -> float: def delay(self: ExponentialBackoff[Literal[False]]) -> float: ...
...
@overload @overload
def delay(self: ExponentialBackoff[Literal[True]]) -> int: def delay(self: ExponentialBackoff[Literal[True]]) -> int: ...
...
@overload @overload
def delay(self: ExponentialBackoff[bool]) -> Union[int, float]: def delay(self: ExponentialBackoff[bool]) -> Union[int, float]: ...
...
def delay(self) -> Union[int, float]: def delay(self) -> Union[int, float]:
"""Compute the next delay """Compute the next delay

55
discord/channel.py

@ -207,7 +207,7 @@ class VoiceChannelSoundEffect(BaseSoundboardSound):
super().__init__(state=state, data=data) super().__init__(state=state, data=data)
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<{self.__class__.__name__} id={self.id} volume={self.volume}>" return f'<{self.__class__.__name__} id={self.id} volume={self.volume}>'
@property @property
def created_at(self) -> Optional[datetime.datetime]: def created_at(self) -> Optional[datetime.datetime]:
@ -273,7 +273,7 @@ class VoiceChannelEffect:
('sound', self.sound), ('sound', self.sound),
] ]
inner = ' '.join('%s=%r' % t for t in attrs) inner = ' '.join('%s=%r' % t for t in attrs)
return f"<{self.__class__.__name__} {inner}>" return f'<{self.__class__.__name__} {inner}>'
def is_sound(self) -> bool: def is_sound(self) -> bool:
""":class:`bool`: Whether the effect is a sound or not.""" """:class:`bool`: Whether the effect is a sound or not."""
@ -457,12 +457,10 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
return self._state._get_message(self.last_message_id) if self.last_message_id else None return self._state._get_message(self.last_message_id) if self.last_message_id else None
@overload @overload
async def edit(self) -> Optional[TextChannel]: async def edit(self) -> Optional[TextChannel]: ...
...
@overload @overload
async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: ...
...
@overload @overload
async def edit( async def edit(
@ -480,8 +478,7 @@ class TextChannel(discord.abc.Messageable, discord.abc.GuildChannel, Hashable):
default_thread_slowmode_delay: int = ..., default_thread_slowmode_delay: int = ...,
type: ChannelType = ..., type: ChannelType = ...,
overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ...,
) -> TextChannel: ) -> TextChannel: ...
...
async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[TextChannel]: async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[TextChannel]:
"""|coro| """|coro|
@ -1551,12 +1548,10 @@ class VoiceChannel(VocalGuildChannel):
return ChannelType.voice return ChannelType.voice
@overload @overload
async def edit(self) -> None: async def edit(self) -> None: ...
...
@overload @overload
async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: ...
...
@overload @overload
async def edit( async def edit(
@ -1575,8 +1570,7 @@ class VoiceChannel(VocalGuildChannel):
slowmode_delay: int = ..., slowmode_delay: int = ...,
status: Optional[str] = ..., status: Optional[str] = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> VoiceChannel: ) -> VoiceChannel: ...
...
async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[VoiceChannel]: async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[VoiceChannel]:
"""|coro| """|coro|
@ -1917,12 +1911,10 @@ class StageChannel(VocalGuildChannel):
return StageInstance(guild=self.guild, state=self._state, data=data) return StageInstance(guild=self.guild, state=self._state, data=data)
@overload @overload
async def edit(self) -> None: async def edit(self) -> None: ...
...
@overload @overload
async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: ...
...
@overload @overload
async def edit( async def edit(
@ -1940,8 +1932,7 @@ class StageChannel(VocalGuildChannel):
video_quality_mode: VideoQualityMode = ..., video_quality_mode: VideoQualityMode = ...,
slowmode_delay: int = ..., slowmode_delay: int = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> StageChannel: ) -> StageChannel: ...
...
async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[StageChannel]: async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[StageChannel]:
"""|coro| """|coro|
@ -2107,12 +2098,10 @@ class CategoryChannel(discord.abc.GuildChannel, Hashable):
return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason) return await self._clone_impl({'nsfw': self.nsfw}, name=name, reason=reason)
@overload @overload
async def edit(self) -> None: async def edit(self) -> None: ...
...
@overload @overload
async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: ...
...
@overload @overload
async def edit( async def edit(
@ -2123,8 +2112,7 @@ class CategoryChannel(discord.abc.GuildChannel, Hashable):
nsfw: bool = ..., nsfw: bool = ...,
overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ..., overwrites: Mapping[OverwriteKeyT, PermissionOverwrite] = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> CategoryChannel: ) -> CategoryChannel: ...
...
async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[CategoryChannel]: async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[CategoryChannel]:
"""|coro| """|coro|
@ -2658,12 +2646,10 @@ class ForumChannel(discord.abc.GuildChannel, Hashable):
) )
@overload @overload
async def edit(self) -> None: async def edit(self) -> None: ...
...
@overload @overload
async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: async def edit(self, *, position: int, reason: Optional[str] = ...) -> None: ...
...
@overload @overload
async def edit( async def edit(
@ -2686,8 +2672,7 @@ class ForumChannel(discord.abc.GuildChannel, Hashable):
default_layout: ForumLayoutType = ..., default_layout: ForumLayoutType = ...,
default_sort_order: ForumOrderType = ..., default_sort_order: ForumOrderType = ...,
require_tag: bool = ..., require_tag: bool = ...,
) -> ForumChannel: ) -> ForumChannel: ...
...
async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[ForumChannel]: async def edit(self, *, reason: Optional[str] = None, **options: Any) -> Optional[ForumChannel]:
"""|coro| """|coro|
@ -2895,8 +2880,7 @@ class ForumChannel(discord.abc.GuildChannel, Hashable):
view: LayoutView, view: LayoutView,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ThreadWithMessage: ) -> ThreadWithMessage: ...
...
@overload @overload
async def create_thread( async def create_thread(
@ -2918,8 +2902,7 @@ class ForumChannel(discord.abc.GuildChannel, Hashable):
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ThreadWithMessage: ) -> ThreadWithMessage: ...
...
async def create_thread( async def create_thread(
self, self,

200
discord/client.py

@ -338,7 +338,7 @@ class Client:
if VoiceClient.warn_nacl: if VoiceClient.warn_nacl:
VoiceClient.warn_nacl = False VoiceClient.warn_nacl = False
_log.warning("PyNaCl is not installed, voice will NOT be supported") _log.warning('PyNaCl is not installed, voice will NOT be supported')
async def __aenter__(self) -> Self: async def __aenter__(self) -> Self:
await self._async_setup_hook() await self._async_setup_hook()
@ -774,7 +774,7 @@ class Client:
raise raise
retry = backoff.delay() retry = backoff.delay()
_log.exception("Attempting a reconnect in %.2fs", retry) _log.exception('Attempting a reconnect in %.2fs', retry)
await asyncio.sleep(retry) await asyncio.sleep(retry)
# Always try to RESUME the connection # Always try to RESUME the connection
# If the connection is not RESUME-able then the gateway will invalidate the session. # If the connection is not RESUME-able then the gateway will invalidate the session.
@ -1238,8 +1238,7 @@ class Client:
*, *,
check: Optional[Callable[[RawAppCommandPermissionsUpdateEvent], bool]] = ..., check: Optional[Callable[[RawAppCommandPermissionsUpdateEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawAppCommandPermissionsUpdateEvent: ) -> RawAppCommandPermissionsUpdateEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1249,8 +1248,7 @@ class Client:
*, *,
check: Optional[Callable[[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]], bool]] = ..., check: Optional[Callable[[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]]: ) -> Tuple[Interaction[Self], Union[Command[Any, ..., Any], ContextMenu]]: ...
...
# AutoMod # AutoMod
@ -1262,8 +1260,7 @@ class Client:
*, *,
check: Optional[Callable[[AutoModRule], bool]] = ..., check: Optional[Callable[[AutoModRule], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> AutoModRule: ) -> AutoModRule: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1273,8 +1270,7 @@ class Client:
*, *,
check: Optional[Callable[[AutoModAction], bool]] = ..., check: Optional[Callable[[AutoModAction], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> AutoModAction: ) -> AutoModAction: ...
...
# Channels # Channels
@ -1286,8 +1282,7 @@ class Client:
*, *,
check: Optional[Callable[[GroupChannel, GroupChannel], bool]] = ..., check: Optional[Callable[[GroupChannel, GroupChannel], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[GroupChannel, GroupChannel]: ) -> Tuple[GroupChannel, GroupChannel]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1297,8 +1292,7 @@ class Client:
*, *,
check: Optional[Callable[[PrivateChannel, datetime.datetime], bool]] = ..., check: Optional[Callable[[PrivateChannel, datetime.datetime], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[PrivateChannel, datetime.datetime]: ) -> Tuple[PrivateChannel, datetime.datetime]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1308,8 +1302,7 @@ class Client:
*, *,
check: Optional[Callable[[GuildChannel], bool]] = ..., check: Optional[Callable[[GuildChannel], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> GuildChannel: ) -> GuildChannel: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1319,8 +1312,7 @@ class Client:
*, *,
check: Optional[Callable[[GuildChannel, GuildChannel], bool]] = ..., check: Optional[Callable[[GuildChannel, GuildChannel], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[GuildChannel, GuildChannel]: ) -> Tuple[GuildChannel, GuildChannel]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1335,8 +1327,7 @@ class Client:
] ]
], ],
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Union[GuildChannel, Thread], Optional[datetime.datetime]]: ) -> Tuple[Union[GuildChannel, Thread], Optional[datetime.datetime]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1346,8 +1337,7 @@ class Client:
*, *,
check: Optional[Callable[[Messageable, Union[User, Member], datetime.datetime], bool]] = ..., check: Optional[Callable[[Messageable, Union[User, Member], datetime.datetime], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Messageable, Union[User, Member], datetime.datetime]: ) -> Tuple[Messageable, Union[User, Member], datetime.datetime]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1357,8 +1347,7 @@ class Client:
*, *,
check: Optional[Callable[[RawTypingEvent], bool]] = ..., check: Optional[Callable[[RawTypingEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawTypingEvent: ) -> RawTypingEvent: ...
...
# Debug & Gateway events # Debug & Gateway events
@ -1370,8 +1359,7 @@ class Client:
*, *,
check: Optional[Callable[[], bool]] = ..., check: Optional[Callable[[], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> None: ) -> None: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1381,8 +1369,7 @@ class Client:
*, *,
check: Optional[Callable[[int], bool]] = ..., check: Optional[Callable[[int], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> int: ) -> int: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1392,8 +1379,7 @@ class Client:
*, *,
check: Optional[Callable[[str], bool]] = ..., check: Optional[Callable[[str], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> str: ) -> str: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1403,8 +1389,7 @@ class Client:
*, *,
check: Optional[Callable[[Union[str, bytes]], bool]] = ..., check: Optional[Callable[[Union[str, bytes]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Union[str, bytes]: ) -> Union[str, bytes]: ...
...
# Entitlements # Entitlements
@overload @overload
@ -1415,8 +1400,7 @@ class Client:
*, *,
check: Optional[Callable[[Entitlement], bool]] = ..., check: Optional[Callable[[Entitlement], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Entitlement: ) -> Entitlement: ...
...
# Guilds # Guilds
@ -1433,8 +1417,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild], bool]] = ..., check: Optional[Callable[[Guild], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Guild: ) -> Guild: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1444,8 +1427,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild, Guild], bool]] = ..., check: Optional[Callable[[Guild, Guild], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Guild, Guild]: ) -> Tuple[Guild, Guild]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1455,8 +1437,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild, Sequence[Emoji], Sequence[Emoji]], bool]] = ..., check: Optional[Callable[[Guild, Sequence[Emoji], Sequence[Emoji]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Guild, Sequence[Emoji], Sequence[Emoji]]: ) -> Tuple[Guild, Sequence[Emoji], Sequence[Emoji]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1466,8 +1447,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild, Sequence[GuildSticker], Sequence[GuildSticker]], bool]] = ..., check: Optional[Callable[[Guild, Sequence[GuildSticker], Sequence[GuildSticker]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Guild, Sequence[GuildSticker], Sequence[GuildSticker]]: ) -> Tuple[Guild, Sequence[GuildSticker], Sequence[GuildSticker]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1477,8 +1457,7 @@ class Client:
*, *,
check: Optional[Callable[[Invite], bool]] = ..., check: Optional[Callable[[Invite], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Invite: ) -> Invite: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1488,8 +1467,7 @@ class Client:
*, *,
check: Optional[Callable[[AuditLogEntry], bool]] = ..., check: Optional[Callable[[AuditLogEntry], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> AuditLogEntry: ) -> AuditLogEntry: ...
...
# Integrations # Integrations
@ -1501,8 +1479,7 @@ class Client:
*, *,
check: Optional[Callable[[Integration], bool]] = ..., check: Optional[Callable[[Integration], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Integration: ) -> Integration: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1512,8 +1489,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild], bool]] = ..., check: Optional[Callable[[Guild], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Guild: ) -> Guild: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1523,8 +1499,7 @@ class Client:
*, *,
check: Optional[Callable[[GuildChannel], bool]] = ..., check: Optional[Callable[[GuildChannel], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> GuildChannel: ) -> GuildChannel: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1534,8 +1509,7 @@ class Client:
*, *,
check: Optional[Callable[[RawIntegrationDeleteEvent], bool]] = ..., check: Optional[Callable[[RawIntegrationDeleteEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawIntegrationDeleteEvent: ) -> RawIntegrationDeleteEvent: ...
...
# Interactions # Interactions
@ -1547,8 +1521,7 @@ class Client:
*, *,
check: Optional[Callable[[Interaction[Self]], bool]] = ..., check: Optional[Callable[[Interaction[Self]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Interaction[Self]: ) -> Interaction[Self]: ...
...
# Members # Members
@ -1560,8 +1533,7 @@ class Client:
*, *,
check: Optional[Callable[[Member], bool]] = ..., check: Optional[Callable[[Member], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Member: ) -> Member: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1571,8 +1543,7 @@ class Client:
*, *,
check: Optional[Callable[[RawMemberRemoveEvent], bool]] = ..., check: Optional[Callable[[RawMemberRemoveEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawMemberRemoveEvent: ) -> RawMemberRemoveEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1582,8 +1553,7 @@ class Client:
*, *,
check: Optional[Callable[[Member, Member], bool]] = ..., check: Optional[Callable[[Member, Member], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Member, Member]: ) -> Tuple[Member, Member]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1593,8 +1563,7 @@ class Client:
*, *,
check: Optional[Callable[[User, User], bool]] = ..., check: Optional[Callable[[User, User], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[User, User]: ) -> Tuple[User, User]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1604,8 +1573,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild, Union[User, Member]], bool]] = ..., check: Optional[Callable[[Guild, Union[User, Member]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Guild, Union[User, Member]]: ) -> Tuple[Guild, Union[User, Member]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1615,8 +1583,7 @@ class Client:
*, *,
check: Optional[Callable[[Guild, User], bool]] = ..., check: Optional[Callable[[Guild, User], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Guild, User]: ) -> Tuple[Guild, User]: ...
...
# Messages # Messages
@ -1628,8 +1595,7 @@ class Client:
*, *,
check: Optional[Callable[[Message], bool]] = ..., check: Optional[Callable[[Message], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1639,8 +1605,7 @@ class Client:
*, *,
check: Optional[Callable[[Message, Message], bool]] = ..., check: Optional[Callable[[Message, Message], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Message, Message]: ) -> Tuple[Message, Message]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1650,8 +1615,7 @@ class Client:
*, *,
check: Optional[Callable[[List[Message]], bool]] = ..., check: Optional[Callable[[List[Message]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> List[Message]: ) -> List[Message]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1661,8 +1625,7 @@ class Client:
*, *,
check: Optional[Callable[[RawMessageUpdateEvent], bool]] = ..., check: Optional[Callable[[RawMessageUpdateEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawMessageUpdateEvent: ) -> RawMessageUpdateEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1672,8 +1635,7 @@ class Client:
*, *,
check: Optional[Callable[[RawMessageDeleteEvent], bool]] = ..., check: Optional[Callable[[RawMessageDeleteEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawMessageDeleteEvent: ) -> RawMessageDeleteEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1683,8 +1645,7 @@ class Client:
*, *,
check: Optional[Callable[[RawBulkMessageDeleteEvent], bool]] = ..., check: Optional[Callable[[RawBulkMessageDeleteEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawBulkMessageDeleteEvent: ) -> RawBulkMessageDeleteEvent: ...
...
# Reactions # Reactions
@ -1696,8 +1657,7 @@ class Client:
*, *,
check: Optional[Callable[[Reaction, Union[Member, User]], bool]] = ..., check: Optional[Callable[[Reaction, Union[Member, User]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Reaction, Union[Member, User]]: ) -> Tuple[Reaction, Union[Member, User]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1707,8 +1667,7 @@ class Client:
*, *,
check: Optional[Callable[[Message, List[Reaction]], bool]] = ..., check: Optional[Callable[[Message, List[Reaction]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Message, List[Reaction]]: ) -> Tuple[Message, List[Reaction]]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1718,8 +1677,7 @@ class Client:
*, *,
check: Optional[Callable[[Reaction], bool]] = ..., check: Optional[Callable[[Reaction], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Reaction: ) -> Reaction: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1729,8 +1687,7 @@ class Client:
*, *,
check: Optional[Callable[[RawReactionActionEvent], bool]] = ..., check: Optional[Callable[[RawReactionActionEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawReactionActionEvent: ) -> RawReactionActionEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1740,8 +1697,7 @@ class Client:
*, *,
check: Optional[Callable[[RawReactionClearEvent], bool]] = ..., check: Optional[Callable[[RawReactionClearEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawReactionClearEvent: ) -> RawReactionClearEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1751,8 +1707,7 @@ class Client:
*, *,
check: Optional[Callable[[RawReactionClearEmojiEvent], bool]] = ..., check: Optional[Callable[[RawReactionClearEmojiEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawReactionClearEmojiEvent: ) -> RawReactionClearEmojiEvent: ...
...
# Roles # Roles
@ -1764,8 +1719,7 @@ class Client:
*, *,
check: Optional[Callable[[Role], bool]] = ..., check: Optional[Callable[[Role], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Role: ) -> Role: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1775,8 +1729,7 @@ class Client:
*, *,
check: Optional[Callable[[Role, Role], bool]] = ..., check: Optional[Callable[[Role, Role], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Role, Role]: ) -> Tuple[Role, Role]: ...
...
# Scheduled Events # Scheduled Events
@ -1788,8 +1741,7 @@ class Client:
*, *,
check: Optional[Callable[[ScheduledEvent], bool]] = ..., check: Optional[Callable[[ScheduledEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1799,8 +1751,7 @@ class Client:
*, *,
check: Optional[Callable[[ScheduledEvent, User], bool]] = ..., check: Optional[Callable[[ScheduledEvent, User], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[ScheduledEvent, User]: ) -> Tuple[ScheduledEvent, User]: ...
...
# Stages # Stages
@ -1812,8 +1763,7 @@ class Client:
*, *,
check: Optional[Callable[[StageInstance], bool]] = ..., check: Optional[Callable[[StageInstance], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> StageInstance: ) -> StageInstance: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1823,8 +1773,7 @@ class Client:
*, *,
check: Optional[Callable[[StageInstance, StageInstance], bool]] = ..., check: Optional[Callable[[StageInstance, StageInstance], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Coroutine[Any, Any, Tuple[StageInstance, StageInstance]]: ) -> Coroutine[Any, Any, Tuple[StageInstance, StageInstance]]: ...
...
# Subscriptions # Subscriptions
@overload @overload
@ -1835,8 +1784,7 @@ class Client:
*, *,
check: Optional[Callable[[Subscription], bool]] = ..., check: Optional[Callable[[Subscription], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Subscription: ) -> Subscription: ...
...
# Threads # Threads
@overload @overload
@ -1847,8 +1795,7 @@ class Client:
*, *,
check: Optional[Callable[[Thread], bool]] = ..., check: Optional[Callable[[Thread], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Thread: ) -> Thread: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1858,8 +1805,7 @@ class Client:
*, *,
check: Optional[Callable[[Thread, Thread], bool]] = ..., check: Optional[Callable[[Thread, Thread], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Thread, Thread]: ) -> Tuple[Thread, Thread]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1869,8 +1815,7 @@ class Client:
*, *,
check: Optional[Callable[[RawThreadUpdateEvent], bool]] = ..., check: Optional[Callable[[RawThreadUpdateEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawThreadUpdateEvent: ) -> RawThreadUpdateEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1880,8 +1825,7 @@ class Client:
*, *,
check: Optional[Callable[[RawThreadDeleteEvent], bool]] = ..., check: Optional[Callable[[RawThreadDeleteEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawThreadDeleteEvent: ) -> RawThreadDeleteEvent: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1891,8 +1835,7 @@ class Client:
*, *,
check: Optional[Callable[[ThreadMember], bool]] = ..., check: Optional[Callable[[ThreadMember], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> ThreadMember: ) -> ThreadMember: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1902,8 +1845,7 @@ class Client:
*, *,
check: Optional[Callable[[RawThreadMembersUpdate], bool]] = ..., check: Optional[Callable[[RawThreadMembersUpdate], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawThreadMembersUpdate: ) -> RawThreadMembersUpdate: ...
...
# Voice # Voice
@ -1915,8 +1857,7 @@ class Client:
*, *,
check: Optional[Callable[[Member, VoiceState, VoiceState], bool]] = ..., check: Optional[Callable[[Member, VoiceState, VoiceState], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Member, VoiceState, VoiceState]: ) -> Tuple[Member, VoiceState, VoiceState]: ...
...
# Polls # Polls
@ -1928,8 +1869,7 @@ class Client:
*, *,
check: Optional[Callable[[Union[User, Member], PollAnswer], bool]] = ..., check: Optional[Callable[[Union[User, Member], PollAnswer], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Union[User, Member], PollAnswer]: ) -> Tuple[Union[User, Member], PollAnswer]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1939,32 +1879,29 @@ class Client:
*, *,
check: Optional[Callable[[RawPollVoteActionEvent], bool]] = ..., check: Optional[Callable[[RawPollVoteActionEvent], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> RawPollVoteActionEvent: ) -> RawPollVoteActionEvent: ...
...
# Commands # Commands
@overload @overload
async def wait_for( async def wait_for(
self: Union[Bot, AutoShardedBot], self: Union[Bot, AutoShardedBot],
event: Literal["command", "command_completion"], event: Literal['command', 'command_completion'],
/, /,
*, *,
check: Optional[Callable[[Context[Any]], bool]] = ..., check: Optional[Callable[[Context[Any]], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Context[Any]: ) -> Context[Any]: ...
...
@overload @overload
async def wait_for( async def wait_for(
self: Union[Bot, AutoShardedBot], self: Union[Bot, AutoShardedBot],
event: Literal["command_error"], event: Literal['command_error'],
/, /,
*, *,
check: Optional[Callable[[Context[Any], CommandError], bool]] = ..., check: Optional[Callable[[Context[Any], CommandError], bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Tuple[Context[Any], CommandError]: ) -> Tuple[Context[Any], CommandError]: ...
...
@overload @overload
async def wait_for( async def wait_for(
@ -1974,8 +1911,7 @@ class Client:
*, *,
check: Optional[Callable[..., bool]] = ..., check: Optional[Callable[..., bool]] = ...,
timeout: Optional[float] = ..., timeout: Optional[float] = ...,
) -> Any: ) -> Any: ...
...
def wait_for( def wait_for(
self, self,

3
discord/embeds.py

@ -189,7 +189,6 @@ class Embed:
description: Optional[Any] = None, description: Optional[Any] = None,
timestamp: Optional[datetime.datetime] = None, timestamp: Optional[datetime.datetime] = None,
): ):
self.colour = colour if colour is not None else color self.colour = colour if colour is not None else color
self.title: Optional[str] = title self.title: Optional[str] = title
self.type: EmbedType = type self.type: EmbedType = type
@ -362,7 +361,7 @@ class Embed:
elif value is None: elif value is None:
self._timestamp = None self._timestamp = None
else: else:
raise TypeError(f"Expected datetime.datetime or None received {value.__class__.__name__} instead") raise TypeError(f'Expected datetime.datetime or None received {value.__class__.__name__} instead')
@property @property
def footer(self) -> _EmbedFooterProxy: def footer(self) -> _EmbedFooterProxy:

2
discord/enums.py

@ -176,7 +176,7 @@ class EnumMeta(type):
try: try:
return cls._enum_value_map_[value] return cls._enum_value_map_[value]
except (KeyError, TypeError): except (KeyError, TypeError):
raise ValueError(f"{value!r} is not a valid {cls.__name__}") raise ValueError(f'{value!r} is not a valid {cls.__name__}')
def __getitem__(cls, key: str) -> Any: def __getitem__(cls, key: str) -> Any:
return cls._enum_member_map_[key] return cls._enum_member_map_[key]

2
discord/errors.py

@ -261,7 +261,7 @@ class PrivilegedIntentsRequired(ClientException):
msg = ( msg = (
'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the ' 'Shard ID %s is requesting privileged intents that have not been explicitly enabled in the '
'developer portal. It is recommended to go to https://discord.com/developers/applications/ ' 'developer portal. It is recommended to go to https://discord.com/developers/applications/ '
'and explicitly enable the privileged intents within your application\'s page. If this is not ' "and explicitly enable the privileged intents within your application's page. If this is not "
'possible, then consider disabling the privileged intents instead.' 'possible, then consider disabling the privileged intents instead.'
) )
super().__init__(msg % shard_id) super().__init__(msg % shard_id)

11
discord/ext/commands/_types.py

@ -22,7 +22,6 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from typing import Any, Awaitable, Callable, Coroutine, TYPE_CHECKING, Protocol, TypeVar, Union, Tuple, Optional from typing import Any, Awaitable, Callable, Coroutine, TYPE_CHECKING, Protocol, TypeVar, Union, Tuple, Optional
@ -49,9 +48,9 @@ MaybeCoro = Union[T, Coro[T]]
MaybeAwaitable = Union[T, Awaitable[T]] MaybeAwaitable = Union[T, Awaitable[T]]
CogT = TypeVar('CogT', bound='Optional[Cog]') CogT = TypeVar('CogT', bound='Optional[Cog]')
UserCheck = Callable[["ContextT"], MaybeCoro[bool]] UserCheck = Callable[['ContextT'], MaybeCoro[bool]]
Hook = Union[Callable[["CogT", "ContextT"], Coro[Any]], Callable[["ContextT"], Coro[Any]]] Hook = Union[Callable[['CogT', 'ContextT'], Coro[Any]], Callable[['ContextT'], Coro[Any]]]
Error = Union[Callable[["CogT", "ContextT", "CommandError"], Coro[Any]], Callable[["ContextT", "CommandError"], Coro[Any]]] Error = Union[Callable[['CogT', 'ContextT', 'CommandError'], Coro[Any]], Callable[['ContextT', 'CommandError'], Coro[Any]]]
ContextT = TypeVar('ContextT', bound='Context[Any]') ContextT = TypeVar('ContextT', bound='Context[Any]')
BotT = TypeVar('BotT', bound=_Bot, covariant=True) BotT = TypeVar('BotT', bound=_Bot, covariant=True)
@ -60,11 +59,9 @@ ContextT_co = TypeVar('ContextT_co', bound='Context[Any]', covariant=True)
class Check(Protocol[ContextT_co]): # type: ignore # TypeVar is expected to be invariant class Check(Protocol[ContextT_co]): # type: ignore # TypeVar is expected to be invariant
predicate: Callable[[ContextT_co], Coroutine[Any, Any, bool]] predicate: Callable[[ContextT_co], Coroutine[Any, Any, bool]]
def __call__(self, coro_or_commands: T) -> T: def __call__(self, coro_or_commands: T) -> T: ...
...
# This is merely a tag type to avoid circular import issues. # This is merely a tag type to avoid circular import issues.

19
discord/ext/commands/bot.py

@ -94,8 +94,7 @@ if TYPE_CHECKING:
strip_after_prefix: bool strip_after_prefix: bool
case_insensitive: bool case_insensitive: bool
class _AutoShardedBotOptions(_AutoShardedClientOptions, _BotOptions): class _AutoShardedBotOptions(_AutoShardedClientOptions, _BotOptions): ...
...
__all__ = ( __all__ = (
@ -1233,8 +1232,8 @@ class BotBase(GroupMixin[None]):
raise raise
raise TypeError( raise TypeError(
"command_prefix must be plain string, iterable of strings, or callable " 'command_prefix must be plain string, iterable of strings, or callable '
f"returning either of these, not {ret.__class__.__name__}" f'returning either of these, not {ret.__class__.__name__}'
) )
return ret return ret
@ -1254,8 +1253,7 @@ class BotBase(GroupMixin[None]):
/, /,
*, *,
cls: Type[ContextT], cls: Type[ContextT],
) -> ContextT: ) -> ContextT: ...
...
async def get_context( async def get_context(
self, self,
@ -1332,15 +1330,15 @@ class BotBase(GroupMixin[None]):
except TypeError: except TypeError:
if not isinstance(prefix, list): if not isinstance(prefix, list):
raise TypeError( raise TypeError(
"get_prefix must return either a string or a list of string, " f"not {prefix.__class__.__name__}" f'get_prefix must return either a string or a list of string, not {prefix.__class__.__name__}'
) )
# It's possible a bad command_prefix got us here. # It's possible a bad command_prefix got us here.
for value in prefix: for value in prefix:
if not isinstance(value, str): if not isinstance(value, str):
raise TypeError( raise TypeError(
"Iterable command_prefix or list returned from get_prefix must " 'Iterable command_prefix or list returned from get_prefix must '
f"contain only strings, not {value.__class__.__name__}" f'contain only strings, not {value.__class__.__name__}'
) )
# Getting here shouldn't happen # Getting here shouldn't happen
@ -1552,5 +1550,4 @@ class AutoShardedBot(BotBase, discord.AutoShardedClient):
allowed_installs: app_commands.AppInstallationType = MISSING, allowed_installs: app_commands.AppInstallationType = MISSING,
intents: discord.Intents, intents: discord.Intents,
**kwargs: Unpack[_AutoShardedBotOptions], **kwargs: Unpack[_AutoShardedBotOptions],
) -> None: ) -> None: ...
...

1
discord/ext/commands/cog.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
import inspect import inspect

43
discord/ext/commands/context.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
import re import re
@ -70,7 +71,7 @@ MISSING: Any = discord.utils.MISSING
T = TypeVar('T') T = TypeVar('T')
CogT = TypeVar('CogT', bound="Cog") CogT = TypeVar('CogT', bound='Cog')
if TYPE_CHECKING: if TYPE_CHECKING:
P = ParamSpec('P') P = ParamSpec('P')
@ -424,8 +425,8 @@ class Context(discord.abc.Messageable, Generic[BotT]):
# consider this to be an *incredibly* strange use case. I'd rather go # consider this to be an *incredibly* strange use case. I'd rather go
# for this common use case rather than waste performance for the # for this common use case rather than waste performance for the
# odd one. # odd one.
pattern = re.compile(r"<@!?%s>" % user.id) pattern = re.compile(r'<@!?%s>' % user.id)
return pattern.sub("@%s" % user.display_name.replace('\\', r'\\'), self.prefix) return pattern.sub('@%s' % user.display_name.replace('\\', r'\\'), self.prefix)
@property @property
def cog(self) -> Optional[Cog]: def cog(self) -> Optional[Cog]:
@ -642,8 +643,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -659,8 +659,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -681,8 +680,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -703,8 +701,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -725,8 +722,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -747,8 +743,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message: async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
"""|coro| """|coro|
@ -865,8 +860,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -882,8 +876,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -904,8 +897,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -926,8 +918,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -948,8 +939,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def send( async def send(
@ -970,8 +960,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
async def send( async def send(
self, self,

6
discord/ext/commands/converter.py

@ -1347,13 +1347,11 @@ async def _actual_conversion(ctx: Context[BotT], converter: Any, argument: str,
@overload @overload
async def run_converters( async def run_converters(
ctx: Context[BotT], converter: Union[Type[Converter[T]], Converter[T]], argument: str, param: Parameter ctx: Context[BotT], converter: Union[Type[Converter[T]], Converter[T]], argument: str, param: Parameter
) -> T: ) -> T: ...
...
@overload @overload
async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any: async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any: ...
...
async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any: async def run_converters(ctx: Context[BotT], converter: Any, argument: str, param: Parameter) -> Any:

4
discord/ext/commands/cooldowns.py

@ -242,10 +242,10 @@ class MaxConcurrency:
self.wait: bool = wait self.wait: bool = wait
if number <= 0: if number <= 0:
raise ValueError('max_concurrency \'number\' cannot be less than 1') raise ValueError("max_concurrency 'number' cannot be less than 1")
if not isinstance(per, BucketType): if not isinstance(per, BucketType):
raise TypeError(f'max_concurrency \'per\' must be of type BucketType not {type(per)!r}') raise TypeError(f"max_concurrency 'per' must be of type BucketType not {type(per)!r}")
def copy(self) -> Self: def copy(self) -> Self:
return self.__class__(self.number, per=self.per, wait=self.wait) return self.__class__(self.number, per=self.per, wait=self.wait)

63
discord/ext/commands/core.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
import asyncio import asyncio
@ -398,6 +399,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
.. versionadded:: 2.0 .. versionadded:: 2.0
""" """
__original_kwargs__: Dict[str, Any] __original_kwargs__: Dict[str, Any]
def __new__(cls, *args: Any, **kwargs: Any) -> Self: def __new__(cls, *args: Any, **kwargs: Any) -> Self:
@ -451,7 +453,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
self.extras: Dict[Any, Any] = kwargs.get('extras', {}) self.extras: Dict[Any, Any] = kwargs.get('extras', {})
if not isinstance(self.aliases, (list, tuple)): if not isinstance(self.aliases, (list, tuple)):
raise TypeError("Aliases of a command must be a list or a tuple of strings.") raise TypeError('Aliases of a command must be a list or a tuple of strings.')
self.description: str = inspect.cleandoc(kwargs.get('description', '')) self.description: str = inspect.cleandoc(kwargs.get('description', ''))
self.hidden: bool = kwargs.get('hidden', False) self.hidden: bool = kwargs.get('hidden', False)
@ -474,7 +476,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
elif isinstance(cooldown, CooldownMapping): elif isinstance(cooldown, CooldownMapping):
buckets: CooldownMapping[Context[Any]] = cooldown buckets: CooldownMapping[Context[Any]] = cooldown
else: else:
raise TypeError("Cooldown must be an instance of CooldownMapping or None.") raise TypeError('Cooldown must be an instance of CooldownMapping or None.')
self._buckets: CooldownMapping[Context[Any]] = buckets self._buckets: CooldownMapping[Context[Any]] = buckets
try: try:
@ -520,7 +522,10 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
@property @property
def callback( def callback(
self, self,
) -> Union[Callable[Concatenate[CogT, Context[Any], P], Coro[T]], Callable[Concatenate[Context[Any], P], Coro[T]],]: ) -> Union[
Callable[Concatenate[CogT, Context[Any], P], Coro[T]],
Callable[Concatenate[Context[Any], P], Coro[T]],
]:
return self._callback return self._callback
@callback.setter @callback.setter
@ -1507,8 +1512,7 @@ class GroupMixin(Generic[CogT]):
] ]
], ],
Command[CogT, P, T], Command[CogT, P, T],
]: ]: ...
...
@overload @overload
def command( def command(
@ -1525,8 +1529,7 @@ class GroupMixin(Generic[CogT]):
] ]
], ],
CommandT, CommandT,
]: ]: ...
...
def command( def command(
self, self,
@ -1566,8 +1569,7 @@ class GroupMixin(Generic[CogT]):
] ]
], ],
Group[CogT, P, T], Group[CogT, P, T],
]: ]: ...
...
@overload @overload
def group( def group(
@ -1584,8 +1586,7 @@ class GroupMixin(Generic[CogT]):
] ]
], ],
GroupT, GroupT,
]: ]: ...
...
def group( def group(
self, self,
@ -1731,35 +1732,28 @@ if TYPE_CHECKING:
class _CommandDecorator: class _CommandDecorator:
@overload @overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Command[CogT, P, T]: def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Command[CogT, P, T]: ...
...
@overload @overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Command[None, P, T]: def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Command[None, P, T]: ...
...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
...
class _GroupDecorator: class _GroupDecorator:
@overload @overload
def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Group[CogT, P, T]: def __call__(self, func: Callable[Concatenate[CogT, ContextT, P], Coro[T]], /) -> Group[CogT, P, T]: ...
...
@overload @overload
def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Group[None, P, T]: def __call__(self, func: Callable[Concatenate[ContextT, P], Coro[T]], /) -> Group[None, P, T]: ...
...
def __call__(self, func: Callable[..., Coro[T]], /) -> Any: def __call__(self, func: Callable[..., Coro[T]], /) -> Any: ...
...
@overload @overload
def command( def command(
name: str = ..., name: str = ...,
**attrs: Unpack[_CommandDecoratorKwargs], **attrs: Unpack[_CommandDecoratorKwargs],
) -> _CommandDecorator: ) -> _CommandDecorator: ...
...
@overload @overload
@ -1775,8 +1769,7 @@ def command(
] ]
], ],
CommandT, CommandT,
]: ]: ...
...
def command( def command(
@ -1828,8 +1821,7 @@ def command(
def group( def group(
name: str = ..., name: str = ...,
**attrs: Unpack[_GroupDecoratorKwargs], **attrs: Unpack[_GroupDecoratorKwargs],
) -> _GroupDecorator: ) -> _GroupDecorator: ...
...
@overload @overload
@ -1845,8 +1837,7 @@ def group(
] ]
], ],
GroupT, GroupT,
]: ]: ...
...
def group( def group(
@ -2226,7 +2217,7 @@ def has_permissions(**perms: Unpack[_PermissionsKwargs]) -> Check[Any]:
invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) invalid = set(perms) - set(discord.Permissions.VALID_FLAGS)
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(ctx: Context[BotT]) -> bool: def predicate(ctx: Context[BotT]) -> bool:
permissions = ctx.permissions permissions = ctx.permissions
@ -2251,7 +2242,7 @@ def bot_has_permissions(**perms: Unpack[_PermissionsKwargs]) -> Check[Any]:
invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) invalid = set(perms) - set(discord.Permissions.VALID_FLAGS)
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(ctx: Context[BotT]) -> bool: def predicate(ctx: Context[BotT]) -> bool:
permissions = ctx.bot_permissions permissions = ctx.bot_permissions
@ -2278,7 +2269,7 @@ def has_guild_permissions(**perms: Unpack[_PermissionsKwargs]) -> Check[Any]:
invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) invalid = set(perms) - set(discord.Permissions.VALID_FLAGS)
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(ctx: Context[BotT]) -> bool: def predicate(ctx: Context[BotT]) -> bool:
if not ctx.guild: if not ctx.guild:
@ -2304,7 +2295,7 @@ def bot_has_guild_permissions(**perms: Unpack[_PermissionsKwargs]) -> Check[Any]
invalid = set(perms) - set(discord.Permissions.VALID_FLAGS) invalid = set(perms) - set(discord.Permissions.VALID_FLAGS)
if invalid: if invalid:
raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") raise TypeError(f'Invalid permission(s): {", ".join(invalid)}')
def predicate(ctx: Context[BotT]) -> bool: def predicate(ctx: Context[BotT]) -> bool:
if not ctx.guild: if not ctx.guild:
@ -2544,7 +2535,7 @@ def dynamic_cooldown(
The type of cooldown to have. The type of cooldown to have.
""" """
if not callable(cooldown): if not callable(cooldown):
raise TypeError("A callable must be provided") raise TypeError('A callable must be provided')
if type is BucketType.default: if type is BucketType.default:
raise ValueError('BucketType.default cannot be used in dynamic cooldowns') raise ValueError('BucketType.default cannot be used in dynamic cooldowns')

2
discord/ext/commands/errors.py

@ -925,7 +925,7 @@ class BadLiteralArgument(UserInputError):
.. versionadded:: 2.3 .. versionadded:: 2.3
""" """
def __init__(self, param: Parameter, literals: Tuple[Any, ...], errors: List[CommandError], argument: str = "") -> None: def __init__(self, param: Parameter, literals: Tuple[Any, ...], errors: List[CommandError], argument: str = '') -> None:
self.param: Parameter = param self.param: Parameter = param
self.literals: Tuple[Any, ...] = literals self.literals: Tuple[Any, ...] = literals
self.errors: List[CommandError] = errors self.errors: List[CommandError] = errors

2
discord/ext/commands/flags.py

@ -197,7 +197,7 @@ def get_flags(namespace: Dict[str, Any], globals: Dict[str, Any], locals: Dict[s
if flag.positional: if flag.positional:
if positional is not None: if positional is not None:
raise TypeError(f"{flag.name!r} positional flag conflicts with {positional.name!r} flag.") raise TypeError(f'{flag.name!r} positional flag conflicts with {positional.name!r} flag.')
positional = flag positional = flag
annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache) annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache)

2
discord/ext/commands/help.py

@ -1072,7 +1072,7 @@ class DefaultHelpCommand(HelpCommand):
self.sort_commands: bool = options.pop('sort_commands', True) self.sort_commands: bool = options.pop('sort_commands', True)
self.dm_help: bool = options.pop('dm_help', False) self.dm_help: bool = options.pop('dm_help', False)
self.dm_help_threshold: int = options.pop('dm_help_threshold', 1000) self.dm_help_threshold: int = options.pop('dm_help_threshold', 1000)
self.arguments_heading: str = options.pop('arguments_heading', "Arguments:") self.arguments_heading: str = options.pop('arguments_heading', 'Arguments:')
self.commands_heading: str = options.pop('commands_heading', 'Commands:') self.commands_heading: str = options.pop('commands_heading', 'Commands:')
self.default_argument_description: str = options.pop('default_argument_description', 'No description given') self.default_argument_description: str = options.pop('default_argument_description', 'No description given')
self.no_category: str = options.pop('no_category', 'No Category') self.no_category: str = options.pop('no_category', 'No Category')

3
discord/ext/commands/parameters.py

@ -278,8 +278,7 @@ class ParameterAlias(Protocol):
description: str = empty, description: str = empty,
displayed_default: str = empty, displayed_default: str = empty,
displayed_name: str = empty, displayed_name: str = empty,
) -> Any: ) -> Any: ...
...
param: ParameterAlias = parameter param: ParameterAlias = parameter

32
discord/ext/commands/view.py

@ -31,22 +31,22 @@ from .errors import UnexpectedQuoteError, InvalidEndOfQuotedStringError, Expecte
# map from opening quotes to closing quotes # map from opening quotes to closing quotes
_quotes = { _quotes = {
'"': '"', '"': '"',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"": "", '': '',
"«": "»", '«': '»',
"": "", '': '',
"": "", '': '',
"": "", '': '',
} }
_all_quotes = set(_quotes.keys()) | set(_quotes.values()) _all_quotes = set(_quotes.keys()) | set(_quotes.values())

6
discord/flags.py

@ -112,12 +112,10 @@ class flag_value:
self.__doc__: Optional[str] = func.__doc__ self.__doc__: Optional[str] = func.__doc__
@overload @overload
def __get__(self, instance: None, owner: Type[BF]) -> Self: def __get__(self, instance: None, owner: Type[BF]) -> Self: ...
...
@overload @overload
def __get__(self, instance: BF, owner: Type[BF]) -> bool: def __get__(self, instance: BF, owner: Type[BF]) -> bool: ...
...
def __get__(self, instance: Optional[BF], owner: Type[BF]) -> Any: def __get__(self, instance: Optional[BF], owner: Type[BF]) -> Any:
if instance is None: if instance is None:

4
discord/gateway.py

@ -141,7 +141,7 @@ class KeepAliveHandler(threading.Thread):
self.shard_id: Optional[int] = shard_id self.shard_id: Optional[int] = shard_id
self.msg: str = 'Keeping shard ID %s websocket alive with sequence %s.' self.msg: str = 'Keeping shard ID %s websocket alive with sequence %s.'
self.block_msg: str = 'Shard ID %s heartbeat blocked for more than %s seconds.' self.block_msg: str = 'Shard ID %s heartbeat blocked for more than %s seconds.'
self.behind_msg: str = 'Can\'t keep up, shard ID %s websocket is %.1fs behind.' self.behind_msg: str = "Can't keep up, shard ID %s websocket is %.1fs behind."
self._stop_ev: threading.Event = threading.Event() self._stop_ev: threading.Event = threading.Event()
self._last_ack: float = time.perf_counter() self._last_ack: float = time.perf_counter()
self._last_send: float = time.perf_counter() self._last_send: float = time.perf_counter()
@ -152,7 +152,7 @@ class KeepAliveHandler(threading.Thread):
def run(self) -> None: def run(self) -> None:
while not self._stop_ev.wait(self.interval): while not self._stop_ev.wait(self.interval):
if self._last_recv + self.heartbeat_timeout < time.perf_counter(): if self._last_recv + self.heartbeat_timeout < time.perf_counter():
_log.warning("Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id) _log.warning('Shard ID %s has stopped responding to the gateway. Closing and restarting.', self.shard_id)
coro = self.ws.close(4000) coro = self.ws.close(4000)
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop) f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)

52
discord/guild.py

@ -219,8 +219,8 @@ class GuildPreview(Hashable):
'stickers', 'stickers',
'features', 'features',
'description', 'description',
"approximate_member_count", 'approximate_member_count',
"approximate_presence_count", 'approximate_presence_count',
) )
def __init__(self, *, data: GuildPreviewPayload, state: ConnectionState) -> None: def __init__(self, *, data: GuildPreviewPayload, state: ConnectionState) -> None:
@ -1296,8 +1296,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, TextChannelPayload]: ) -> Coroutine[Any, Any, TextChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1307,8 +1306,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, VoiceChannelPayload]: ) -> Coroutine[Any, Any, VoiceChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1318,8 +1316,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, StageChannelPayload]: ) -> Coroutine[Any, Any, StageChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1329,8 +1326,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, CategoryChannelPayload]: ) -> Coroutine[Any, Any, CategoryChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1340,8 +1336,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, NewsChannelPayload]: ) -> Coroutine[Any, Any, NewsChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1351,8 +1346,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, Union[TextChannelPayload, NewsChannelPayload]]: ) -> Coroutine[Any, Any, Union[TextChannelPayload, NewsChannelPayload]]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1362,8 +1356,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, ForumChannelPayload]: ) -> Coroutine[Any, Any, ForumChannelPayload]: ...
...
@overload @overload
def _create_channel( def _create_channel(
@ -1373,8 +1366,7 @@ class Guild(Hashable):
overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ..., overwrites: Mapping[Union[Role, Member, Object], PermissionOverwrite] = ...,
category: Optional[Snowflake] = ..., category: Optional[Snowflake] = ...,
**options: Any, **options: Any,
) -> Coroutine[Any, Any, GuildChannelPayload]: ) -> Coroutine[Any, Any, GuildChannelPayload]: ...
...
def _create_channel( def _create_channel(
self, self,
@ -1965,7 +1957,9 @@ class Guild(Hashable):
) )
channel = ForumChannel( channel = ForumChannel(
state=self._state, guild=self, data=data # pyright: ignore[reportArgumentType] # it's the correct data state=self._state,
guild=self,
data=data, # pyright: ignore[reportArgumentType] # it's the correct data
) )
# temporarily add to the cache # temporarily add to the cache
@ -3246,8 +3240,7 @@ class Guild(Hashable):
description: str = ..., description: str = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def create_scheduled_event( async def create_scheduled_event(
@ -3262,8 +3255,7 @@ class Guild(Hashable):
description: str = ..., description: str = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def create_scheduled_event( async def create_scheduled_event(
@ -3277,8 +3269,7 @@ class Guild(Hashable):
description: str = ..., description: str = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def create_scheduled_event( async def create_scheduled_event(
@ -3292,8 +3283,7 @@ class Guild(Hashable):
description: str = ..., description: str = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
async def create_scheduled_event( async def create_scheduled_event(
self, self,
@ -3405,7 +3395,7 @@ class Guild(Hashable):
if entity_type is None: if entity_type is None:
raise TypeError( raise TypeError(
'invalid GuildChannel type passed, must be VoiceChannel or StageChannel ' f'not {channel.__class__.__name__}' f'invalid GuildChannel type passed, must be VoiceChannel or StageChannel not {channel.__class__.__name__}'
) )
if privacy_level is not MISSING: if privacy_level is not MISSING:
@ -3660,8 +3650,7 @@ class Guild(Hashable):
mentionable: bool = ..., mentionable: bool = ...,
secondary_colour: Optional[Union[Colour, int]] = ..., secondary_colour: Optional[Union[Colour, int]] = ...,
tertiary_colour: Optional[Union[Colour, int]] = ..., tertiary_colour: Optional[Union[Colour, int]] = ...,
) -> Role: ) -> Role: ...
...
@overload @overload
async def create_role( async def create_role(
@ -3676,8 +3665,7 @@ class Guild(Hashable):
mentionable: bool = ..., mentionable: bool = ...,
secondary_color: Optional[Union[Colour, int]] = ..., secondary_color: Optional[Union[Colour, int]] = ...,
tertiary_color: Optional[Union[Colour, int]] = ..., tertiary_color: Optional[Union[Colour, int]] = ...,
) -> Role: ) -> Role: ...
...
async def create_role( async def create_role(
self, self,

30
discord/http.py

@ -2037,22 +2037,19 @@ class HTTPClient:
@overload @overload
def get_scheduled_events( def get_scheduled_events(
self, guild_id: Snowflake, with_user_count: Literal[True] self, guild_id: Snowflake, with_user_count: Literal[True]
) -> Response[List[scheduled_event.GuildScheduledEventWithUserCount]]: ) -> Response[List[scheduled_event.GuildScheduledEventWithUserCount]]: ...
...
@overload @overload
def get_scheduled_events( def get_scheduled_events(
self, guild_id: Snowflake, with_user_count: Literal[False] self, guild_id: Snowflake, with_user_count: Literal[False]
) -> Response[List[scheduled_event.GuildScheduledEvent]]: ) -> Response[List[scheduled_event.GuildScheduledEvent]]: ...
...
@overload @overload
def get_scheduled_events( def get_scheduled_events(
self, guild_id: Snowflake, with_user_count: bool self, guild_id: Snowflake, with_user_count: bool
) -> Union[ ) -> Union[
Response[List[scheduled_event.GuildScheduledEventWithUserCount]], Response[List[scheduled_event.GuildScheduledEvent]] Response[List[scheduled_event.GuildScheduledEventWithUserCount]], Response[List[scheduled_event.GuildScheduledEvent]]
]: ]: ...
...
def get_scheduled_events(self, guild_id: Snowflake, with_user_count: bool) -> Response[Any]: def get_scheduled_events(self, guild_id: Snowflake, with_user_count: bool) -> Response[Any]:
params = {'with_user_count': int(with_user_count)} params = {'with_user_count': int(with_user_count)}
@ -2081,20 +2078,19 @@ class HTTPClient:
@overload @overload
def get_scheduled_event( def get_scheduled_event(
self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[True] self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[True]
) -> Response[scheduled_event.GuildScheduledEventWithUserCount]: ) -> Response[scheduled_event.GuildScheduledEventWithUserCount]: ...
...
@overload @overload
def get_scheduled_event( def get_scheduled_event(
self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[False] self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: Literal[False]
) -> Response[scheduled_event.GuildScheduledEvent]: ) -> Response[scheduled_event.GuildScheduledEvent]: ...
...
@overload @overload
def get_scheduled_event( def get_scheduled_event(
self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool
) -> Union[Response[scheduled_event.GuildScheduledEventWithUserCount], Response[scheduled_event.GuildScheduledEvent]]: ) -> Union[
... Response[scheduled_event.GuildScheduledEventWithUserCount], Response[scheduled_event.GuildScheduledEvent]
]: ...
def get_scheduled_event( def get_scheduled_event(
self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool self, guild_id: Snowflake, guild_scheduled_event_id: Snowflake, with_user_count: bool
@ -2164,8 +2160,7 @@ class HTTPClient:
with_member: Literal[True], with_member: Literal[True],
before: Optional[Snowflake] = ..., before: Optional[Snowflake] = ...,
after: Optional[Snowflake] = ..., after: Optional[Snowflake] = ...,
) -> Response[scheduled_event.ScheduledEventUsersWithMember]: ) -> Response[scheduled_event.ScheduledEventUsersWithMember]: ...
...
@overload @overload
def get_scheduled_event_users( def get_scheduled_event_users(
@ -2176,8 +2171,7 @@ class HTTPClient:
with_member: Literal[False], with_member: Literal[False],
before: Optional[Snowflake] = ..., before: Optional[Snowflake] = ...,
after: Optional[Snowflake] = ..., after: Optional[Snowflake] = ...,
) -> Response[scheduled_event.ScheduledEventUsers]: ) -> Response[scheduled_event.ScheduledEventUsers]: ...
...
@overload @overload
def get_scheduled_event_users( def get_scheduled_event_users(
@ -2188,8 +2182,7 @@ class HTTPClient:
with_member: bool, with_member: bool,
before: Optional[Snowflake] = ..., before: Optional[Snowflake] = ...,
after: Optional[Snowflake] = ..., after: Optional[Snowflake] = ...,
) -> Union[Response[scheduled_event.ScheduledEventUsersWithMember], Response[scheduled_event.ScheduledEventUsers]]: ) -> Union[Response[scheduled_event.ScheduledEventUsersWithMember], Response[scheduled_event.ScheduledEventUsers]]: ...
...
def get_scheduled_event_users( def get_scheduled_event_users(
self, self,
@ -2572,7 +2565,6 @@ class HTTPClient:
mode: Optional[onboarding.OnboardingMode] = None, mode: Optional[onboarding.OnboardingMode] = None,
reason: Optional[str], reason: Optional[str],
) -> Response[onboarding.Onboarding]: ) -> Response[onboarding.Onboarding]:
payload = {} payload = {}
if prompts is not None: if prompts is not None:

17
discord/interactions.py

@ -95,8 +95,8 @@ if TYPE_CHECKING:
GroupChannel, GroupChannel,
] ]
InteractionCallbackResource = Union[ InteractionCallbackResource = Union[
"InteractionMessage", 'InteractionMessage',
"InteractionCallbackActivityInstance", 'InteractionCallbackActivityInstance',
] ]
MISSING: Any = utils.MISSING MISSING: Any = utils.MISSING
@ -735,7 +735,6 @@ class InteractionCallbackResponse(Generic[ClientT]):
resource = data.get('resource') resource = data.get('resource')
if resource is not None: if resource is not None:
self.type = try_enum(InteractionResponseType, resource['type']) self.type = try_enum(InteractionResponseType, resource['type'])
message = resource.get('message') message = resource.get('message')
@ -916,8 +915,7 @@ class InteractionResponse(Generic[ClientT]):
suppress_embeds: bool = False, suppress_embeds: bool = False,
silent: bool = False, silent: bool = False,
delete_after: Optional[float] = None, delete_after: Optional[float] = None,
) -> InteractionCallbackResponse[ClientT]: ) -> InteractionCallbackResponse[ClientT]: ...
...
@overload @overload
async def send_message( async def send_message(
@ -936,8 +934,7 @@ class InteractionResponse(Generic[ClientT]):
silent: bool = False, silent: bool = False,
delete_after: Optional[float] = None, delete_after: Optional[float] = None,
poll: Poll = MISSING, poll: Poll = MISSING,
) -> InteractionCallbackResponse[ClientT]: ) -> InteractionCallbackResponse[ClientT]: ...
...
async def send_message( async def send_message(
self, self,
@ -1437,8 +1434,7 @@ class InteractionMessage(Message):
view: LayoutView, view: LayoutView,
allowed_mentions: Optional[AllowedMentions] = None, allowed_mentions: Optional[AllowedMentions] = None,
delete_after: Optional[float] = None, delete_after: Optional[float] = None,
) -> InteractionMessage: ) -> InteractionMessage: ...
...
@overload @overload
async def edit( async def edit(
@ -1452,8 +1448,7 @@ class InteractionMessage(Message):
allowed_mentions: Optional[AllowedMentions] = None, allowed_mentions: Optional[AllowedMentions] = None,
delete_after: Optional[float] = None, delete_after: Optional[float] = None,
poll: Poll = MISSING, poll: Poll = MISSING,
) -> InteractionMessage: ) -> InteractionMessage: ...
...
async def edit( async def edit(
self, self,

2
discord/invite.py

@ -418,7 +418,7 @@ class Invite(Hashable):
target_user_data = data.get('target_user') target_user_data = data.get('target_user')
self.target_user: Optional[User] = None if target_user_data is None else self._state.create_user(target_user_data) self.target_user: Optional[User] = None if target_user_data is None else self._state.create_user(target_user_data)
self.target_type: InviteTarget = try_enum(InviteTarget, data.get("target_type", 0)) self.target_type: InviteTarget = try_enum(InviteTarget, data.get('target_type', 0))
application = data.get('target_application') application = data.get('target_application')
self.target_application: Optional[PartialAppInfo] = ( self.target_application: Optional[PartialAppInfo] = (

52
discord/message.py

@ -448,7 +448,7 @@ class DeletedReferencedMessage:
self._parent: MessageReference = parent self._parent: MessageReference = parent
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<DeletedReferencedMessage id={self.id} channel_id={self.channel_id} guild_id={self.guild_id!r}>" return f'<DeletedReferencedMessage id={self.id} channel_id={self.channel_id} guild_id={self.guild_id!r}>'
@property @property
def id(self) -> int: def id(self) -> int:
@ -883,7 +883,9 @@ class MessageInteractionMetadata(Hashable):
self.modal_interaction: Optional[MessageInteractionMetadata] = None self.modal_interaction: Optional[MessageInteractionMetadata] = None
try: try:
self.modal_interaction = MessageInteractionMetadata( self.modal_interaction = MessageInteractionMetadata(
state=state, guild=guild, data=data['triggering_interaction_metadata'] # type: ignore # EAFP state=state,
guild=guild,
data=data['triggering_interaction_metadata'], # type: ignore # EAFP
) )
except KeyError: except KeyError:
pass pass
@ -1748,8 +1750,7 @@ class PartialMessage(Hashable):
mention_author: bool = ..., mention_author: bool = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -1764,8 +1765,7 @@ class PartialMessage(Hashable):
mention_author: bool = ..., mention_author: bool = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -1785,8 +1785,7 @@ class PartialMessage(Hashable):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -1806,8 +1805,7 @@ class PartialMessage(Hashable):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -1827,8 +1825,7 @@ class PartialMessage(Hashable):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
@overload @overload
async def reply( async def reply(
@ -1848,8 +1845,7 @@ class PartialMessage(Hashable):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ..., poll: Poll = ...,
) -> Message: ) -> Message: ...
...
async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message: async def reply(self, content: Optional[str] = None, **kwargs: Any) -> Message:
"""|coro| """|coro|
@ -2726,19 +2722,19 @@ class Message(PartialMessage, Hashable):
if self.type is MessageType.new_member: if self.type is MessageType.new_member:
formats = [ formats = [
"{0} joined the party.", '{0} joined the party.',
"{0} is here.", '{0} is here.',
"Welcome, {0}. We hope you brought pizza.", 'Welcome, {0}. We hope you brought pizza.',
"A wild {0} appeared.", 'A wild {0} appeared.',
"{0} just landed.", '{0} just landed.',
"{0} just slid into the server.", '{0} just slid into the server.',
"{0} just showed up!", '{0} just showed up!',
"Welcome {0}. Say hi!", 'Welcome {0}. Say hi!',
"{0} hopped into the server.", '{0} hopped into the server.',
"Everyone welcome {0}!", 'Everyone welcome {0}!',
"Glad you're here, {0}.", "Glad you're here, {0}.",
"Good to see you, {0}.", 'Good to see you, {0}.',
"Yay you made it, {0}!", 'Yay you made it, {0}!',
] ]
created_at_ms = int(self.created_at.timestamp() * 1000) created_at_ms = int(self.created_at.timestamp() * 1000)
@ -2797,7 +2793,7 @@ class Message(PartialMessage, Hashable):
if self.type is MessageType.thread_starter_message: if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None: if self.reference is None or self.reference.resolved is None:
return 'Sorry, we couldn\'t load the first message in this thread' return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message # the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore return self.reference.resolved.content # type: ignore
@ -2867,7 +2863,7 @@ class Message(PartialMessage, Hashable):
embed.fields, embed.fields,
name='poll_question_text', name='poll_question_text',
) )
return f'{self.author.display_name}\'s poll {poll_title.value} has closed.' # type: ignore return f"{self.author.display_name}'s poll {poll_title.value} has closed." # type: ignore
# Fallback for unknown message types # Fallback for unknown message types
return '' return ''

12
discord/opus.py

@ -72,7 +72,7 @@ __all__ = (
_log = logging.getLogger(__name__) _log = logging.getLogger(__name__)
OPUS_SILENCE = b'\xF8\xFF\xFE' OPUS_SILENCE = b'\xf8\xff\xfe'
c_int_ptr = ctypes.POINTER(ctypes.c_int) c_int_ptr = ctypes.POINTER(ctypes.c_int)
c_int16_ptr = ctypes.POINTER(ctypes.c_int16) c_int16_ptr = ctypes.POINTER(ctypes.c_int16)
@ -218,7 +218,7 @@ def libopus_loader(name: str) -> Any:
if item[3]: if item[3]:
func.errcheck = item[3] func.errcheck = item[3]
except KeyError: except KeyError:
_log.exception("Error assigning check function to %s", func) _log.exception('Error assigning check function to %s', func)
return lib return lib
@ -476,16 +476,14 @@ class Decoder(_OpusStruct):
return ret.value return ret.value
@overload @overload
def decode(self, data: bytes, *, fec: bool) -> bytes: def decode(self, data: bytes, *, fec: bool) -> bytes: ...
...
@overload @overload
def decode(self, data: Literal[None], *, fec: Literal[False]) -> bytes: def decode(self, data: Literal[None], *, fec: Literal[False]) -> bytes: ...
...
def decode(self, data: Optional[bytes], *, fec: bool = False) -> bytes: def decode(self, data: Optional[bytes], *, fec: bool = False) -> bytes:
if data is None and fec: if data is None and fec:
raise TypeError("Invalid arguments: FEC cannot be used with null data") raise TypeError('Invalid arguments: FEC cannot be used with null data')
if data is None: if data is None:
frame_size = self._get_last_packet_duration() or self.SAMPLES_PER_FRAME frame_size = self._get_last_packet_duration() or self.SAMPLES_PER_FRAME

10
discord/permissions.py

@ -94,11 +94,9 @@ if TYPE_CHECKING:
create_polls: BoolOrNoneT create_polls: BoolOrNoneT
use_external_apps: BoolOrNoneT use_external_apps: BoolOrNoneT
class _PermissionsKwargs(_BasePermissionsKwargs[bool]): class _PermissionsKwargs(_BasePermissionsKwargs[bool]): ...
...
class _PermissionOverwriteKwargs(_BasePermissionsKwargs[Optional[bool]]): class _PermissionOverwriteKwargs(_BasePermissionsKwargs[Optional[bool]]): ...
...
# A permission alias works like a regular flag but is marked # A permission alias works like a regular flag but is marked
@ -219,14 +217,14 @@ class Permissions(BaseFlags):
if isinstance(other, Permissions): if isinstance(other, Permissions):
return (self.value & other.value) == self.value return (self.value & other.value) == self.value
else: else:
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}") raise TypeError(f'cannot compare {self.__class__.__name__} with {other.__class__.__name__}')
def is_superset(self, other: Permissions) -> bool: def is_superset(self, other: Permissions) -> bool:
"""Returns ``True`` if self has the same or more permissions as other.""" """Returns ``True`` if self has the same or more permissions as other."""
if isinstance(other, Permissions): if isinstance(other, Permissions):
return (self.value | other.value) == self.value return (self.value | other.value) == self.value
else: else:
raise TypeError(f"cannot compare {self.__class__.__name__} with {other.__class__.__name__}") raise TypeError(f'cannot compare {self.__class__.__name__} with {other.__class__.__name__}')
def is_strict_subset(self, other: Permissions) -> bool: def is_strict_subset(self, other: Permissions) -> bool:
"""Returns ``True`` if the permissions on other are a strict subset of those on self.""" """Returns ``True`` if the permissions on other are a strict subset of those on self."""

15
discord/player.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
import threading import threading
@ -163,7 +164,7 @@ class FFmpegAudio(AudioSource):
stderr: Optional[IO[bytes]] = subprocess_kwargs.pop('stderr', None) stderr: Optional[IO[bytes]] = subprocess_kwargs.pop('stderr', None)
if stderr == subprocess.PIPE: if stderr == subprocess.PIPE:
warnings.warn("Passing subprocess.PIPE does nothing", DeprecationWarning, stacklevel=3) warnings.warn('Passing subprocess.PIPE does nothing', DeprecationWarning, stacklevel=3)
stderr = None stderr = None
piping_stderr = False piping_stderr = False
@ -573,7 +574,7 @@ class FFmpegOpusAudio(FFmpegAudio):
if isinstance(method, str): if isinstance(method, str):
probefunc = getattr(cls, '_probe_codec_' + method, None) probefunc = getattr(cls, '_probe_codec_' + method, None)
if probefunc is None: if probefunc is None:
raise AttributeError(f"Invalid probe method {method!r}") raise AttributeError(f'Invalid probe method {method!r}')
if probefunc is cls._probe_codec_native: if probefunc is cls._probe_codec_native:
fallback = cls._probe_codec_fallback fallback = cls._probe_codec_fallback
@ -603,9 +604,9 @@ class FFmpegOpusAudio(FFmpegAudio):
except BaseException: except BaseException:
_log.exception("Fallback probe using '%s' failed", executable) _log.exception("Fallback probe using '%s' failed", executable)
else: else:
_log.debug("Fallback probe found codec=%s, bitrate=%s", codec, bitrate) _log.debug('Fallback probe found codec=%s, bitrate=%s', codec, bitrate)
else: else:
_log.debug("Probe found codec=%s, bitrate=%s", codec, bitrate) _log.debug('Probe found codec=%s, bitrate=%s', codec, bitrate)
return codec, bitrate return codec, bitrate
@ -634,11 +635,11 @@ class FFmpegOpusAudio(FFmpegAudio):
output = out.decode('utf8') output = out.decode('utf8')
codec = bitrate = None codec = bitrate = None
codec_match = re.search(r"Stream #0.*?Audio: (\w+)", output) codec_match = re.search(r'Stream #0.*?Audio: (\w+)', output)
if codec_match: if codec_match:
codec = codec_match.group(1) codec = codec_match.group(1)
br_match = re.search(r"(\d+) [kK]b/s", output) br_match = re.search(r'(\d+) [kK]b/s', output)
if br_match: if br_match:
bitrate = max(int(br_match.group(1)), 512) bitrate = max(int(br_match.group(1)), 512)
@ -825,7 +826,7 @@ class AudioPlayer(threading.Thread):
try: try:
asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.client.loop) asyncio.run_coroutine_threadsafe(self.client.ws.speak(speaking), self.client.client.loop)
except Exception: except Exception:
_log.exception("Speaking call in player failed") _log.exception('Speaking call in player failed')
def send_silence(self, count: int = 5) -> None: def send_silence(self, count: int = 5) -> None:
try: try:

2
discord/poll.py

@ -483,7 +483,7 @@ class Poll:
return data return data
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Poll duration={self.duration} question=\"{self.question}\" answers={self.answers}>" return f'<Poll duration={self.duration} question="{self.question}" answers={self.answers}>'
@property @property
def question(self) -> str: def question(self) -> str:

1
discord/presences.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Optional, Tuple from typing import TYPE_CHECKING, Optional, Tuple

2
discord/primary_guild.py

@ -83,7 +83,7 @@ class PrimaryGuild:
@classmethod @classmethod
def _default(cls, state: ConnectionState) -> Self: def _default(cls, state: ConnectionState) -> Self:
payload: PrimaryGuildPayload = {"identity_enabled": False} # type: ignore payload: PrimaryGuildPayload = {'identity_enabled': False} # type: ignore
return cls(state=state, data=payload) return cls(state=state, data=payload)
def __repr__(self) -> str: def __repr__(self) -> str:

18
discord/role.py

@ -429,10 +429,10 @@ class Role(Hashable):
async def _move(self, position: int, reason: Optional[str]) -> None: async def _move(self, position: int, reason: Optional[str]) -> None:
if position <= 0: if position <= 0:
raise ValueError("Cannot move role to position 0 or below") raise ValueError('Cannot move role to position 0 or below')
if self.is_default(): if self.is_default():
raise ValueError("Cannot move default role") raise ValueError('Cannot move default role')
if self.position == position: if self.position == position:
return # Save discord the extra request. return # Save discord the extra request.
@ -447,7 +447,7 @@ class Role(Hashable):
else: else:
roles.append(self.id) roles.append(self.id)
payload: List[RolePositionUpdate] = [{"id": z[0], "position": z[1]} for z in zip(roles, change_range)] payload: List[RolePositionUpdate] = [{'id': z[0], 'position': z[1]} for z in zip(roles, change_range)]
await http.move_role_position(self.guild.id, payload, reason=reason) await http.move_role_position(self.guild.id, payload, reason=reason)
async def edit( async def edit(
@ -599,20 +599,16 @@ class Role(Hashable):
return Role(guild=self.guild, data=data, state=self._state) return Role(guild=self.guild, data=data, state=self._state)
@overload @overload
async def move(self, *, beginning: bool, offset: int = ..., reason: Optional[str] = ...): async def move(self, *, beginning: bool, offset: int = ..., reason: Optional[str] = ...): ...
...
@overload @overload
async def move(self, *, end: bool, offset: int = ..., reason: Optional[str] = ...): async def move(self, *, end: bool, offset: int = ..., reason: Optional[str] = ...): ...
...
@overload @overload
async def move(self, *, above: Role, offset: int = ..., reason: Optional[str] = ...): async def move(self, *, above: Role, offset: int = ..., reason: Optional[str] = ...): ...
...
@overload @overload
async def move(self, *, below: Role, offset: int = ..., reason: Optional[str] = ...): async def move(self, *, below: Role, offset: int = ..., reason: Optional[str] = ...): ...
...
async def move( async def move(
self, self,

15
discord/scheduled_event.py

@ -310,8 +310,7 @@ class ScheduledEvent(Hashable):
status: EventStatus = ..., status: EventStatus = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def edit( async def edit(
@ -327,8 +326,7 @@ class ScheduledEvent(Hashable):
status: EventStatus = ..., status: EventStatus = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def edit( async def edit(
@ -344,8 +342,7 @@ class ScheduledEvent(Hashable):
image: bytes = ..., image: bytes = ...,
location: str, location: str,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def edit( async def edit(
@ -360,8 +357,7 @@ class ScheduledEvent(Hashable):
status: EventStatus = ..., status: EventStatus = ...,
image: bytes = ..., image: bytes = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
@overload @overload
async def edit( async def edit(
@ -376,8 +372,7 @@ class ScheduledEvent(Hashable):
image: bytes = ..., image: bytes = ...,
location: str, location: str,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> ScheduledEvent: ) -> ScheduledEvent: ...
...
async def edit( async def edit(
self, self,

2
discord/shard.py

@ -319,7 +319,7 @@ class SessionStartLimits:
The number of identify requests allowed per 5 seconds The number of identify requests allowed per 5 seconds
""" """
__slots__ = ("total", "remaining", "reset_after", "max_concurrency") __slots__ = ('total', 'remaining', 'reset_after', 'max_concurrency')
def __init__(self, **kwargs: Unpack[SessionStartLimit]): def __init__(self, **kwargs: Unpack[SessionStartLimit]):
self.total: int = kwargs['total'] self.total: int = kwargs['total']

1
discord/sku.py

@ -22,7 +22,6 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import AsyncIterator, Optional, TYPE_CHECKING from typing import AsyncIterator, Optional, TYPE_CHECKING

4
discord/soundboard.py

@ -146,7 +146,7 @@ class SoundboardDefaultSound(BaseSoundboardSound):
('emoji', self.emoji), ('emoji', self.emoji),
] ]
inner = ' '.join('%s=%r' % t for t in attrs) inner = ' '.join('%s=%r' % t for t in attrs)
return f"<{self.__class__.__name__} {inner}>" return f'<{self.__class__.__name__} {inner}>'
class SoundboardSound(BaseSoundboardSound): class SoundboardSound(BaseSoundboardSound):
@ -203,7 +203,7 @@ class SoundboardSound(BaseSoundboardSound):
('user', self.user), ('user', self.user),
] ]
inner = ' '.join('%s=%r' % t for t in attrs) inner = ' '.join('%s=%r' % t for t in attrs)
return f"<{self.__class__.__name__} {inner}>" return f'<{self.__class__.__name__} {inner}>'
def _update(self, data: SoundboardSoundPayload): def _update(self, data: SoundboardSoundPayload):
super()._update(data) super()._update(data)

11
discord/state.py

@ -1265,14 +1265,12 @@ class ConnectionState(Generic[ClientT]):
return guild.id not in self._guilds return guild.id not in self._guilds
@overload @overload
async def chunk_guild(self, guild: Guild, *, wait: Literal[True] = ..., cache: Optional[bool] = ...) -> List[Member]: async def chunk_guild(self, guild: Guild, *, wait: Literal[True] = ..., cache: Optional[bool] = ...) -> List[Member]: ...
...
@overload @overload
async def chunk_guild( async def chunk_guild(
self, guild: Guild, *, wait: Literal[False] = ..., cache: Optional[bool] = ... self, guild: Guild, *, wait: Literal[False] = ..., cache: Optional[bool] = ...
) -> asyncio.Future[List[Member]]: ) -> asyncio.Future[List[Member]]: ...
...
async def chunk_guild( async def chunk_guild(
self, guild: Guild, *, wait: bool = True, cache: Optional[bool] = None self, guild: Guild, *, wait: bool = True, cache: Optional[bool] = None
@ -1803,7 +1801,10 @@ class ConnectionState(Generic[ClientT]):
return self._emojis[emoji_id] return self._emojis[emoji_id]
except KeyError: except KeyError:
return PartialEmoji.with_state( return PartialEmoji.with_state(
self, animated=data.get('animated', False), id=emoji_id, name=data['name'] # type: ignore self,
animated=data.get('animated', False),
id=emoji_id,
name=data['name'], # type: ignore
) )
def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]: def _upgrade_partial_emoji(self, emoji: PartialEmoji) -> Union[Emoji, PartialEmoji, str]:

3
discord/types/automod.py

@ -33,8 +33,7 @@ AutoModerationRuleEventType = Literal[1]
AutoModerationTriggerPresets = Literal[1, 2, 3] AutoModerationTriggerPresets = Literal[1, 2, 3]
class Empty(TypedDict): class Empty(TypedDict): ...
...
class _AutoModerationActionMetadataAlert(TypedDict): class _AutoModerationActionMetadataAlert(TypedDict):

2
discord/types/command.py

@ -163,7 +163,7 @@ class _ChatInputApplicationCommand(_BaseApplicationCommand, total=False):
class _BaseContextMenuApplicationCommand(_BaseApplicationCommand): class _BaseContextMenuApplicationCommand(_BaseApplicationCommand):
description: Literal[""] description: Literal['']
class _UserApplicationCommand(_BaseContextMenuApplicationCommand): class _UserApplicationCommand(_BaseContextMenuApplicationCommand):

6
discord/types/guild.py

@ -116,8 +116,7 @@ class _GuildPreviewUnique(TypedDict):
approximate_presence_count: int approximate_presence_count: int
class GuildPreview(_BaseGuildPreview, _GuildPreviewUnique): class GuildPreview(_BaseGuildPreview, _GuildPreviewUnique): ...
...
class Guild(_BaseGuildPreview): class Guild(_BaseGuildPreview):
@ -167,8 +166,7 @@ class InviteGuild(Guild, total=False):
welcome_screen: WelcomeScreen welcome_screen: WelcomeScreen
class GuildWithCounts(Guild, _GuildPreviewUnique): class GuildWithCounts(Guild, _GuildPreviewUnique): ...
...
class GuildPrune(TypedDict): class GuildPrune(TypedDict):

3
discord/types/invite.py

@ -68,8 +68,7 @@ class Invite(IncompleteInvite, total=False):
expires_at: Optional[str] expires_at: Optional[str]
class InviteWithCounts(Invite, _GuildPreviewUnique): class InviteWithCounts(Invite, _GuildPreviewUnique): ...
...
class GatewayInviteCreate(TypedDict): class GatewayInviteCreate(TypedDict):

9
discord/types/scheduled_event.py

@ -81,16 +81,13 @@ class _WithUserCount(TypedDict):
user_count: int user_count: int
class _StageInstanceScheduledEventWithUserCount(StageInstanceScheduledEvent, _WithUserCount): class _StageInstanceScheduledEventWithUserCount(StageInstanceScheduledEvent, _WithUserCount): ...
...
class _VoiceScheduledEventWithUserCount(VoiceScheduledEvent, _WithUserCount): class _VoiceScheduledEventWithUserCount(VoiceScheduledEvent, _WithUserCount): ...
...
class _ExternalScheduledEventWithUserCount(ExternalScheduledEvent, _WithUserCount): class _ExternalScheduledEventWithUserCount(ExternalScheduledEvent, _WithUserCount): ...
...
GuildScheduledEventWithUserCount = Union[ GuildScheduledEventWithUserCount = Union[

3
discord/types/webhook.py

@ -63,5 +63,4 @@ class _FullWebhook(TypedDict, total=False):
application_id: Optional[Snowflake] application_id: Optional[Snowflake]
class Webhook(PartialWebhook, _FullWebhook): class Webhook(PartialWebhook, _FullWebhook): ...
...

16
discord/ui/action_row.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import ( from typing import (
@ -405,8 +406,7 @@ class ActionRow(Item[V]):
max_values: int = ..., max_values: int = ...,
disabled: bool = ..., disabled: bool = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, SelectT]: ) -> SelectCallbackDecorator[S, SelectT]: ...
...
@overload @overload
def select( def select(
@ -422,8 +422,7 @@ class ActionRow(Item[V]):
disabled: bool = ..., disabled: bool = ...,
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, UserSelectT]: ) -> SelectCallbackDecorator[S, UserSelectT]: ...
...
@overload @overload
def select( def select(
@ -439,8 +438,7 @@ class ActionRow(Item[V]):
disabled: bool = ..., disabled: bool = ...,
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, RoleSelectT]: ) -> SelectCallbackDecorator[S, RoleSelectT]: ...
...
@overload @overload
def select( def select(
@ -456,8 +454,7 @@ class ActionRow(Item[V]):
disabled: bool = ..., disabled: bool = ...,
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, ChannelSelectT]: ) -> SelectCallbackDecorator[S, ChannelSelectT]: ...
...
@overload @overload
def select( def select(
@ -473,8 +470,7 @@ class ActionRow(Item[V]):
disabled: bool = ..., disabled: bool = ...,
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, MentionableSelectT]: ) -> SelectCallbackDecorator[S, MentionableSelectT]: ...
...
def select( def select(
self, self,

1
discord/ui/media_gallery.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, List, Literal, Optional, TypeVar, Union from typing import TYPE_CHECKING, List, Literal, Optional, TypeVar, Union

2
discord/ui/modal.py

@ -176,7 +176,7 @@ class Modal(View):
else: else:
item = find(lambda i: getattr(i, 'custom_id', None) == component['custom_id'], self.walk_children()) # type: ignore item = find(lambda i: getattr(i, 'custom_id', None) == component['custom_id'], self.walk_children()) # type: ignore
if item is None: if item is None:
_log.debug("Modal interaction referencing unknown item custom_id %s. Discarding", component['custom_id']) _log.debug('Modal interaction referencing unknown item custom_id %s. Discarding', component['custom_id'])
continue continue
item._refresh_state(interaction, component) # type: ignore item._refresh_state(interaction, component) # type: ignore

1
discord/ui/section.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Generator, List, Literal, Optional, TypeVar, Union, ClassVar from typing import TYPE_CHECKING, Any, Dict, Generator, List, Literal, Optional, TypeVar, Union, ClassVar

20
discord/ui/select.py

@ -361,11 +361,12 @@ class BaseSelect(Item[V]):
payload: List[PossibleValue] payload: List[PossibleValue]
try: try:
resolved = Namespace._get_resolved_items( resolved = Namespace._get_resolved_items(
interaction, data['resolved'] # pyright: ignore[reportTypedDictNotRequiredAccess] interaction,
data['resolved'], # pyright: ignore[reportTypedDictNotRequiredAccess]
) )
payload = list(resolved.values()) payload = list(resolved.values())
except KeyError: except KeyError:
payload = data.get("values", []) # type: ignore payload = data.get('values', []) # type: ignore
self._values = values[self.custom_id] = payload self._values = values[self.custom_id] = payload
selected_values.set(values) selected_values.set(values)
@ -985,8 +986,7 @@ def select(
disabled: bool = ..., disabled: bool = ...,
row: Optional[int] = ..., row: Optional[int] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, SelectT]: ) -> SelectCallbackDecorator[S, SelectT]: ...
...
@overload @overload
@ -1003,8 +1003,7 @@ def select(
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
row: Optional[int] = ..., row: Optional[int] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, UserSelectT]: ) -> SelectCallbackDecorator[S, UserSelectT]: ...
...
@overload @overload
@ -1021,8 +1020,7 @@ def select(
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
row: Optional[int] = ..., row: Optional[int] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, RoleSelectT]: ) -> SelectCallbackDecorator[S, RoleSelectT]: ...
...
@overload @overload
@ -1039,8 +1037,7 @@ def select(
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
row: Optional[int] = ..., row: Optional[int] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, ChannelSelectT]: ) -> SelectCallbackDecorator[S, ChannelSelectT]: ...
...
@overload @overload
@ -1057,8 +1054,7 @@ def select(
default_values: Sequence[ValidDefaultValues] = ..., default_values: Sequence[ValidDefaultValues] = ...,
row: Optional[int] = ..., row: Optional[int] = ...,
id: Optional[int] = ..., id: Optional[int] = ...,
) -> SelectCallbackDecorator[S, MentionableSelectT]: ) -> SelectCallbackDecorator[S, MentionableSelectT]: ...
...
def select( def select(

1
discord/ui/separator.py

@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. DEALINGS IN THE SOFTWARE.
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Literal, Optional, TypeVar from typing import TYPE_CHECKING, Literal, Optional, TypeVar

8
discord/ui/view.py

@ -689,8 +689,7 @@ class View(BaseView):
if TYPE_CHECKING: if TYPE_CHECKING:
@classmethod @classmethod
def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View: def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> View: ...
...
def __init_subclass__(cls) -> None: def __init_subclass__(cls) -> None:
super().__init_subclass__() super().__init_subclass__()
@ -783,8 +782,7 @@ class LayoutView(BaseView):
if TYPE_CHECKING: if TYPE_CHECKING:
@classmethod @classmethod
def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> LayoutView: def from_message(cls, message: Message, /, *, timeout: Optional[float] = 180.0) -> LayoutView: ...
...
def __init__(self, *, timeout: Optional[float] = 180.0) -> None: def __init__(self, *, timeout: Optional[float] = 180.0) -> None:
super().__init__(timeout=timeout) super().__init__(timeout=timeout)
@ -1046,7 +1044,7 @@ class ViewStore:
) -> None: ) -> None:
modal = self._modals.get(custom_id) modal = self._modals.get(custom_id)
if modal is None: if modal is None:
_log.debug("Modal interaction referencing unknown custom_id %s. Discarding", custom_id) _log.debug('Modal interaction referencing unknown custom_id %s. Discarding', custom_id)
return return
self.add_task(modal._dispatch_submit(interaction, components)) self.add_task(modal._dispatch_submit(interaction, components))

4
discord/user.py

@ -101,8 +101,8 @@ class BaseUser(_UserTag):
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (
f"<BaseUser id={self.id} name={self.name!r} global_name={self.global_name!r}" f'<BaseUser id={self.id} name={self.name!r} global_name={self.global_name!r}'
f" bot={self.bot} system={self.system}>" f' bot={self.bot} system={self.system}>'
) )
def __str__(self) -> str: def __str__(self) -> str:

84
discord/utils.py

@ -158,8 +158,7 @@ if TYPE_CHECKING:
class _DecompressionContext(Protocol): class _DecompressionContext(Protocol):
COMPRESSION_TYPE: str COMPRESSION_TYPE: str
def decompress(self, data: bytes, /) -> str | None: def decompress(self, data: bytes, /) -> str | None: ...
...
P = ParamSpec('P') P = ParamSpec('P')
@ -186,12 +185,10 @@ class CachedSlotProperty(Generic[T, T_co]):
self.__doc__ = getattr(function, '__doc__') self.__doc__ = getattr(function, '__doc__')
@overload @overload
def __get__(self, instance: None, owner: Type[T]) -> CachedSlotProperty[T, T_co]: def __get__(self, instance: None, owner: Type[T]) -> CachedSlotProperty[T, T_co]: ...
...
@overload @overload
def __get__(self, instance: T, owner: Type[T]) -> T_co: def __get__(self, instance: T, owner: Type[T]) -> T_co: ...
...
def __get__(self, instance: Optional[T], owner: Type[T]) -> Any: def __get__(self, instance: Optional[T], owner: Type[T]) -> Any:
if instance is None: if instance is None:
@ -240,15 +237,13 @@ class SequenceProxy(Sequence[T_co]):
return self.__proxied return self.__proxied
def __repr__(self) -> str: def __repr__(self) -> str:
return f"SequenceProxy({self.__proxied!r})" return f'SequenceProxy({self.__proxied!r})'
@overload @overload
def __getitem__(self, idx: SupportsIndex) -> T_co: def __getitem__(self, idx: SupportsIndex) -> T_co: ...
...
@overload @overload
def __getitem__(self, idx: slice) -> List[T_co]: def __getitem__(self, idx: slice) -> List[T_co]: ...
...
def __getitem__(self, idx: Union[SupportsIndex, slice]) -> Union[T_co, List[T_co]]: def __getitem__(self, idx: Union[SupportsIndex, slice]) -> Union[T_co, List[T_co]]:
return self.__copied[idx] return self.__copied[idx]
@ -273,18 +268,15 @@ class SequenceProxy(Sequence[T_co]):
@overload @overload
def parse_time(timestamp: None) -> None: def parse_time(timestamp: None) -> None: ...
...
@overload @overload
def parse_time(timestamp: str) -> datetime.datetime: def parse_time(timestamp: str) -> datetime.datetime: ...
...
@overload @overload
def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: ...
...
def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]: def parse_time(timestamp: Optional[str]) -> Optional[datetime.datetime]:
@ -308,7 +300,7 @@ def deprecated(instead: Optional[str] = None) -> Callable[[Callable[P, T]], Call
def decorated(*args: P.args, **kwargs: P.kwargs) -> T: def decorated(*args: P.args, **kwargs: P.kwargs) -> T:
warnings.simplefilter('always', DeprecationWarning) # turn off filter warnings.simplefilter('always', DeprecationWarning) # turn off filter
if instead: if instead:
fmt = "{0.__name__} is deprecated, use {1} instead." fmt = '{0.__name__} is deprecated, use {1} instead.'
else: else:
fmt = '{0.__name__} is deprecated.' fmt = '{0.__name__} is deprecated.'
@ -447,13 +439,11 @@ async def _afind(predicate: Callable[[T], Any], iterable: AsyncIterable[T], /) -
@overload @overload
def find(predicate: Callable[[T], Any], iterable: AsyncIterable[T], /) -> Coro[Optional[T]]: def find(predicate: Callable[[T], Any], iterable: AsyncIterable[T], /) -> Coro[Optional[T]]: ...
...
@overload @overload
def find(predicate: Callable[[T], Any], iterable: Iterable[T], /) -> Optional[T]: def find(predicate: Callable[[T], Any], iterable: Iterable[T], /) -> Optional[T]: ...
...
def find(predicate: Callable[[T], Any], iterable: _Iter[T], /) -> Union[Optional[T], Coro[Optional[T]]]: def find(predicate: Callable[[T], Any], iterable: _Iter[T], /) -> Union[Optional[T], Coro[Optional[T]]]:
@ -533,13 +523,11 @@ async def _aget(iterable: AsyncIterable[T], /, **attrs: Any) -> Optional[T]:
@overload @overload
def get(iterable: AsyncIterable[T], /, **attrs: Any) -> Coro[Optional[T]]: def get(iterable: AsyncIterable[T], /, **attrs: Any) -> Coro[Optional[T]]: ...
...
@overload @overload
def get(iterable: Iterable[T], /, **attrs: Any) -> Optional[T]: def get(iterable: Iterable[T], /, **attrs: Any) -> Optional[T]: ...
...
def get(iterable: _Iter[T], /, **attrs: Any) -> Union[Optional[T], Coro[Optional[T]]]: def get(iterable: _Iter[T], /, **attrs: Any) -> Union[Optional[T], Coro[Optional[T]]]:
@ -622,7 +610,7 @@ def _get_as_snowflake(data: Any, key: str) -> Optional[int]:
def _get_mime_type_for_image(data: bytes): def _get_mime_type_for_image(data: bytes):
if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'): if data.startswith(b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a'):
return 'image/png' return 'image/png'
elif data[0:3] == b'\xff\xd8\xff' or data[6:10] in (b'JFIF', b'Exif'): elif data[0:3] == b'\xff\xd8\xff' or data[6:10] in (b'JFIF', b'Exif'):
return 'image/jpeg' return 'image/jpeg'
@ -756,13 +744,11 @@ def compute_timedelta(dt: datetime.datetime) -> float:
@overload @overload
async def sleep_until(when: datetime.datetime, result: T) -> T: async def sleep_until(when: datetime.datetime, result: T) -> T: ...
...
@overload @overload
async def sleep_until(when: datetime.datetime) -> None: async def sleep_until(when: datetime.datetime) -> None: ...
...
async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]: async def sleep_until(when: datetime.datetime, result: Optional[T] = None) -> Optional[T]:
@ -823,8 +809,7 @@ class SnowflakeList(_SnowflakeListBase):
if TYPE_CHECKING: if TYPE_CHECKING:
def __init__(self, data: Iterable[int], *, is_sorted: bool = False): def __init__(self, data: Iterable[int], *, is_sorted: bool = False): ...
...
def __new__(cls, data: Iterable[int], *, is_sorted: bool = False) -> Self: def __new__(cls, data: Iterable[int], *, is_sorted: bool = False) -> Self:
return array.array.__new__(cls, 'Q', data if is_sorted else sorted(data)) # type: ignore return array.array.__new__(cls, 'Q', data if is_sorted else sorted(data)) # type: ignore
@ -934,11 +919,11 @@ _MARKDOWN_ESCAPE_SUBREGEX = '|'.join(r'\{0}(?=([\s\S]*((?<!\{0})\{0})))'.format(
_MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)|^#{1,3}|^\s*-' _MARKDOWN_ESCAPE_COMMON = r'^>(?:>>)?\s|\[.+\]\(.+\)|^#{1,3}|^\s*-'
_MARKDOWN_ESCAPE_REGEX = re.compile(fr'(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})', re.MULTILINE) _MARKDOWN_ESCAPE_REGEX = re.compile(rf'(?P<markdown>{_MARKDOWN_ESCAPE_SUBREGEX}|{_MARKDOWN_ESCAPE_COMMON})', re.MULTILINE)
_URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])' _URL_REGEX = r'(?P<url><[^: >]+:\/[^ >]+>|(?:https?|steam):\/\/[^\s<]+[^<.,:;\"\'\]\s])'
_MARKDOWN_STOCK_REGEX = fr'(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})' _MARKDOWN_STOCK_REGEX = rf'(?P<markdown>[_\\~|\*`]|{_MARKDOWN_ESCAPE_COMMON})'
def remove_markdown(text: str, *, ignore_links: bool = True) -> str: def remove_markdown(text: str, *, ignore_links: bool = True) -> str:
@ -1073,13 +1058,11 @@ async def _achunk(iterator: AsyncIterable[T], max_size: int) -> AsyncIterator[Li
@overload @overload
def as_chunks(iterator: AsyncIterable[T], max_size: int) -> AsyncIterator[List[T]]: def as_chunks(iterator: AsyncIterable[T], max_size: int) -> AsyncIterator[List[T]]: ...
...
@overload @overload
def as_chunks(iterator: Iterable[T], max_size: int) -> Iterator[List[T]]: def as_chunks(iterator: Iterable[T], max_size: int) -> Iterator[List[T]]: ...
...
def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]: def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]:
@ -1304,7 +1287,6 @@ def stream_supports_colour(stream: Any) -> bool:
class _ColourFormatter(logging.Formatter): class _ColourFormatter(logging.Formatter):
# ANSI codes are a bit weird to decipher if you're unfamiliar with them, so here's a refresher # ANSI codes are a bit weird to decipher if you're unfamiliar with them, so here's a refresher
# It starts off with a format like \x1b[XXXm where XXX is a semicolon separated list of commands # It starts off with a format like \x1b[XXXm where XXX is a semicolon separated list of commands
# The important ones here relate to colour. # The important ones here relate to colour.
@ -1499,37 +1481,37 @@ def _format_call_duration(duration: datetime.timedelta) -> str:
threshold_M = 10.5 threshold_M = 10.5
if seconds < threshold_s: if seconds < threshold_s:
formatted = "a few seconds" formatted = 'a few seconds'
elif seconds < (threshold_m * minutes_s): elif seconds < (threshold_m * minutes_s):
minutes = round(seconds / minutes_s) minutes = round(seconds / minutes_s)
if minutes == 1: if minutes == 1:
formatted = "a minute" formatted = 'a minute'
else: else:
formatted = f"{minutes} minutes" formatted = f'{minutes} minutes'
elif seconds < (threshold_h * hours_s): elif seconds < (threshold_h * hours_s):
hours = round(seconds / hours_s) hours = round(seconds / hours_s)
if hours == 1: if hours == 1:
formatted = "an hour" formatted = 'an hour'
else: else:
formatted = f"{hours} hours" formatted = f'{hours} hours'
elif seconds < (threshold_d * days_s): elif seconds < (threshold_d * days_s):
days = round(seconds / days_s) days = round(seconds / days_s)
if days == 1: if days == 1:
formatted = "a day" formatted = 'a day'
else: else:
formatted = f"{days} days" formatted = f'{days} days'
elif seconds < (threshold_M * months_s): elif seconds < (threshold_M * months_s):
months = round(seconds / months_s) months = round(seconds / months_s)
if months == 1: if months == 1:
formatted = "a month" formatted = 'a month'
else: else:
formatted = f"{months} months" formatted = f'{months} months'
else: else:
years = round(seconds / years_s) years = round(seconds / years_s)
if years == 1: if years == 1:
formatted = "a year" formatted = 'a year'
else: else:
formatted = f"{years} years" formatted = f'{years} years'
return formatted return formatted

6
discord/voice_client.py

@ -217,7 +217,7 @@ class VoiceClient(VoiceProtocol):
def __init__(self, client: Client, channel: abc.Connectable) -> None: def __init__(self, client: Client, channel: abc.Connectable) -> None:
if not has_nacl: if not has_nacl:
raise RuntimeError("PyNaCl library needed in order to use voice") raise RuntimeError('PyNaCl library needed in order to use voice')
super().__init__(client, channel) super().__init__(client, channel)
state = client._connection state = client._connection
@ -321,7 +321,7 @@ class VoiceClient(VoiceProtocol):
.. versionadded:: 1.4 .. versionadded:: 1.4
""" """
ws = self._connection.ws ws = self._connection.ws
return float("inf") if not ws else ws.latency return float('inf') if not ws else ws.latency
@property @property
def average_latency(self) -> float: def average_latency(self) -> float:
@ -330,7 +330,7 @@ class VoiceClient(VoiceProtocol):
.. versionadded:: 1.4 .. versionadded:: 1.4
""" """
ws = self._connection.ws ws = self._connection.ws
return float("inf") if not ws else ws.average_latency return float('inf') if not ws else ws.average_latency
async def disconnect(self, *, force: bool = False) -> None: async def disconnect(self, *, force: bool = False) -> None:
"""|coro| """|coro|

2
discord/voice_state.py

@ -148,7 +148,7 @@ class SocketReader(threading.Thread):
readable, _, _ = select.select([self.state.socket], [], [], 30) readable, _, _ = select.select([self.state.socket], [], [], 30)
except (ValueError, TypeError, OSError) as e: except (ValueError, TypeError, OSError) as e:
_log.debug( _log.debug(
"Select error handling socket in reader, this should be safe to ignore: %s: %s", e.__class__.__name__, e 'Select error handling socket in reader, this should be safe to ignore: %s: %s', e.__class__.__name__, e
) )
# The socket is either closed or doesn't exist at the moment # The socket is either closed or doesn't exist at the moment
continue continue

20
discord/webhook/async_.py

@ -1324,7 +1324,7 @@ class Webhook(BaseWebhook):
@classmethod @classmethod
def _as_follower(cls, data, *, channel, user) -> Self: def _as_follower(cls, data, *, channel, user) -> Self:
name = f"{channel.guild} #{channel}" name = f'{channel.guild} #{channel}'
feed: WebhookPayload = { feed: WebhookPayload = {
'id': data['webhook_id'], 'id': data['webhook_id'],
'type': 2, 'type': 2,
@ -1622,8 +1622,7 @@ class Webhook(BaseWebhook):
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
) -> WebhookMessage: ) -> WebhookMessage: ...
...
@overload @overload
async def send( async def send(
@ -1642,8 +1641,7 @@ class Webhook(BaseWebhook):
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
) -> None: ) -> None: ...
...
@overload @overload
async def send( async def send(
@ -1667,8 +1665,7 @@ class Webhook(BaseWebhook):
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING, poll: Poll = MISSING,
) -> WebhookMessage: ) -> WebhookMessage: ...
...
@overload @overload
async def send( async def send(
@ -1692,8 +1689,7 @@ class Webhook(BaseWebhook):
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING, poll: Poll = MISSING,
) -> None: ) -> None: ...
...
async def send( async def send(
self, self,
@ -1987,8 +1983,7 @@ class Webhook(BaseWebhook):
view: LayoutView, view: LayoutView,
allowed_mentions: Optional[AllowedMentions] = ..., allowed_mentions: Optional[AllowedMentions] = ...,
thread: Snowflake = ..., thread: Snowflake = ...,
) -> WebhookMessage: ) -> WebhookMessage: ...
...
@overload @overload
async def edit_message( async def edit_message(
@ -2002,8 +1997,7 @@ class Webhook(BaseWebhook):
view: Optional[View] = ..., view: Optional[View] = ...,
allowed_mentions: Optional[AllowedMentions] = ..., allowed_mentions: Optional[AllowedMentions] = ...,
thread: Snowflake = ..., thread: Snowflake = ...,
) -> WebhookMessage: ) -> WebhookMessage: ...
...
async def edit_message( async def edit_message(
self, self,

18
discord/webhook/sync.py

@ -872,8 +872,7 @@ class SyncWebhook(BaseWebhook):
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage: ...
...
@overload @overload
def send( def send(
@ -891,8 +890,7 @@ class SyncWebhook(BaseWebhook):
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
) -> None: ) -> None: ...
...
@overload @overload
def send( def send(
@ -915,8 +913,7 @@ class SyncWebhook(BaseWebhook):
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING, poll: Poll = MISSING,
view: View = MISSING, view: View = MISSING,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage: ...
...
@overload @overload
def send( def send(
@ -939,8 +936,7 @@ class SyncWebhook(BaseWebhook):
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING, poll: Poll = MISSING,
view: View = MISSING, view: View = MISSING,
) -> None: ) -> None: ...
...
def send( def send(
self, self,
@ -1192,8 +1188,7 @@ class SyncWebhook(BaseWebhook):
view: LayoutView, view: LayoutView,
allowed_mentions: Optional[AllowedMentions] = ..., allowed_mentions: Optional[AllowedMentions] = ...,
thread: Snowflake = ..., thread: Snowflake = ...,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage: ...
...
@overload @overload
def edit_message( def edit_message(
@ -1207,8 +1202,7 @@ class SyncWebhook(BaseWebhook):
view: Optional[View] = ..., view: Optional[View] = ...,
allowed_mentions: Optional[AllowedMentions] = ..., allowed_mentions: Optional[AllowedMentions] = ...,
thread: Snowflake = ..., thread: Snowflake = ...,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage: ...
...
def edit_message( def edit_message(
self, self,

4
discord/widget.py

@ -195,7 +195,7 @@ class WidgetMember(BaseUser):
self.connected_channel: Optional[WidgetChannel] = connected_channel self.connected_channel: Optional[WidgetChannel] = connected_channel
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<WidgetMember name={self.name!r} global_name={self.global_name!r}" f" bot={self.bot} nick={self.nick!r}>" return f'<WidgetMember name={self.name!r} global_name={self.global_name!r} bot={self.bot} nick={self.nick!r}>'
@property @property
def display_name(self) -> str: def display_name(self) -> str:
@ -292,7 +292,7 @@ class Widget:
@property @property
def json_url(self) -> str: def json_url(self) -> str:
""":class:`str`: The JSON URL of the widget.""" """:class:`str`: The JSON URL of the widget."""
return f"https://discord.com/api/guilds/{self.id}/widget.json" return f'https://discord.com/api/guilds/{self.id}/widget.json'
@property @property
def invite_url(self) -> Optional[str]: def invite_url(self) -> Optional[str]:

2
examples/advanced_startup.py

@ -31,7 +31,6 @@ class CustomBot(commands.Bot):
self.initial_extensions = initial_extensions self.initial_extensions = initial_extensions
async def setup_hook(self) -> None: async def setup_hook(self) -> None:
# here, we are loading extensions prior to sync to ensure we are syncing interactions defined in those extensions. # here, we are loading extensions prior to sync to ensure we are syncing interactions defined in those extensions.
for extension in self.initial_extensions: for extension in self.initial_extensions:
@ -53,7 +52,6 @@ class CustomBot(commands.Bot):
async def main(): async def main():
# When taking over how the bot process is run, you become responsible for a few additional things. # When taking over how the bot process is run, you become responsible for a few additional things.
# 1. logging # 1. logging

1
examples/app_commands/basic.py

@ -92,6 +92,7 @@ async def joined(interaction: discord.Interaction, member: Optional[discord.Memb
# accessing a menu within the client, usually via right clicking. # accessing a menu within the client, usually via right clicking.
# It always takes an interaction as its first parameter and a Member or Message as its second parameter. # It always takes an interaction as its first parameter and a Member or Message as its second parameter.
# This context menu command only works on members # This context menu command only works on members
@client.tree.context_menu(name='Show Join Date') @client.tree.context_menu(name='Show Join Date')
async def show_join_date(interaction: discord.Interaction, member: discord.Member): async def show_join_date(interaction: discord.Interaction, member: discord.Member):

2
examples/app_commands/transformers.py

@ -60,6 +60,7 @@ async def add(
# Examples of these include int, str, float, bool, User, Member, Role, and any channel type. # Examples of these include int, str, float, bool, User, Member, Role, and any channel type.
# Since there are a lot of these, for brevity only a channel example will be included. # Since there are a lot of these, for brevity only a channel example will be included.
# This command shows how to only show text and voice channels to a user using the Union type hint # This command shows how to only show text and voice channels to a user using the Union type hint
# combined with the VoiceChannel and TextChannel types. # combined with the VoiceChannel and TextChannel types.
@client.tree.command(name='channel-info') @client.tree.command(name='channel-info')
@ -83,6 +84,7 @@ async def channel_info(interaction: discord.Interaction, channel: Union[discord.
# In order to support choices, the library has a few ways of doing this. # In order to support choices, the library has a few ways of doing this.
# The first one is using a typing.Literal for basic choices. # The first one is using a typing.Literal for basic choices.
# On Discord, this will show up as two choices, Buy and Sell. # On Discord, this will show up as two choices, Buy and Sell.
# In the code, you will receive either 'Buy' or 'Sell' as a string. # In the code, you will receive either 'Buy' or 'Sell' as a string.
@client.tree.command() @client.tree.command()

4
examples/basic_bot.py

@ -4,10 +4,10 @@ import discord
from discord.ext import commands from discord.ext import commands
import random import random
description = '''An example bot to showcase the discord.ext.commands extension description = """An example bot to showcase the discord.ext.commands extension
module. module.
There are a number of utility commands being showcased here.''' There are a number of utility commands being showcased here."""
intents = discord.Intents.default() intents = discord.Intents.default()
intents.members = True intents.members = True

10
examples/basic_voice.py

@ -97,10 +97,10 @@ class Music(commands.Cog):
"""Changes the player's volume""" """Changes the player's volume"""
if ctx.voice_client is None: if ctx.voice_client is None:
return await ctx.send("Not connected to a voice channel.") return await ctx.send('Not connected to a voice channel.')
ctx.voice_client.source.volume = volume / 100 ctx.voice_client.source.volume = volume / 100
await ctx.send(f"Changed volume to {volume}%") await ctx.send(f'Changed volume to {volume}%')
@commands.command() @commands.command()
async def stop(self, ctx): async def stop(self, ctx):
@ -116,8 +116,8 @@ class Music(commands.Cog):
if ctx.author.voice: if ctx.author.voice:
await ctx.author.voice.channel.connect() await ctx.author.voice.channel.connect()
else: else:
await ctx.send("You are not connected to a voice channel.") await ctx.send('You are not connected to a voice channel.')
raise commands.CommandError("Author not connected to a voice channel.") raise commands.CommandError('Author not connected to a voice channel.')
elif ctx.voice_client.is_playing(): elif ctx.voice_client.is_playing():
ctx.voice_client.stop() ctx.voice_client.stop()
@ -126,7 +126,7 @@ intents = discord.Intents.default()
intents.message_content = True intents.message_content = True
bot = commands.Bot( bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"), command_prefix=commands.when_mentioned_or('!'),
description='Relatively simple music bot example', description='Relatively simple music bot example',
intents=intents, intents=intents,
) )

2
examples/converters.py

@ -40,7 +40,7 @@ async def userinfo_error(ctx: commands.Context, error: commands.CommandError):
# If the conversion above fails for any reason, it will raise `commands.BadArgument` # If the conversion above fails for any reason, it will raise `commands.BadArgument`
# so we handle this in this error handler: # so we handle this in this error handler:
if isinstance(error, commands.BadArgument): if isinstance(error, commands.BadArgument):
return await ctx.send('Couldn\'t find that user.') return await ctx.send("Couldn't find that user.")
# The default `on_command_error` will ignore errors from this command # The default `on_command_error` will ignore errors from this command
# because we made our own command-specific error handler, # because we made our own command-specific error handler,
# so we need to log tracebacks ourselves. # so we need to log tracebacks ourselves.

2
examples/custom_context.py

@ -55,5 +55,5 @@ async def guess(ctx, number: int):
# let people do very malicious things with your # let people do very malicious things with your
# bot. Try to use a file or something to keep # bot. Try to use a file or something to keep
# them private, and don't commit it to GitHub # them private, and don't commit it to GitHub
token = "your token here" token = 'your token here'
bot.run(token) bot.run(token)

2
examples/modals/basic.py

@ -70,7 +70,7 @@ class Feedback(discord.ui.Modal, title='Feedback'):
client = MyClient() client = MyClient()
@client.tree.command(guild=TEST_GUILD, description="Submit feedback") @client.tree.command(guild=TEST_GUILD, description='Submit feedback')
async def feedback(interaction: discord.Interaction): async def feedback(interaction: discord.Interaction):
# Send the modal with an instance of our `Feedback` class # Send the modal with an instance of our `Feedback` class
# Since modals require an interaction, they cannot be done as a response to a text command. # Since modals require an interaction, they cannot be done as a response to a text command.

2
examples/modals/label.py

@ -84,7 +84,7 @@ class TimeoutModal(discord.ui.Modal, title='Timeout Member'):
client = MyClient() client = MyClient()
@client.tree.command(guild=TEST_GUILD, description="Timeout a member") @client.tree.command(guild=TEST_GUILD, description='Timeout a member')
async def timeout(interaction: discord.Interaction, member: discord.Member): async def timeout(interaction: discord.Interaction, member: discord.Member):
# Send the modal with an instance of our `TimeoutModal` class # Send the modal with an instance of our `TimeoutModal` class
# Since modals require an interaction, they cannot be done as a response to a text command. # Since modals require an interaction, they cannot be done as a response to a text command.

3
examples/secret.py

@ -5,7 +5,8 @@ from discord.ext import commands
intents = discord.Intents.default() intents = discord.Intents.default()
bot = commands.Bot(command_prefix=commands.when_mentioned, description="Nothing to see here!", intents=intents) bot = commands.Bot(command_prefix=commands.when_mentioned, description='Nothing to see here!', intents=intents)
# the `hidden` keyword argument hides it from the help command. # the `hidden` keyword argument hides it from the help command.
@bot.group(hidden=True) @bot.group(hidden=True)

1
examples/views/counter.py

@ -22,7 +22,6 @@ class CounterBot(commands.Bot):
# Define a simple View that gives us a counter button # Define a simple View that gives us a counter button
class Counter(discord.ui.View): class Counter(discord.ui.View):
# Define the actual button # Define the actual button
# When pressed, this increments the number displayed until it hits 5. # When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green. # When it hits 5, the counter button is disabled and it turns green.

2
examples/views/dropdown.py

@ -3,12 +3,12 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
# Defines a custom Select containing colour options # Defines a custom Select containing colour options
# that the user can choose. The callback function # that the user can choose. The callback function
# of this class is called when the user changes their choice # of this class is called when the user changes their choice
class Dropdown(discord.ui.Select): class Dropdown(discord.ui.Select):
def __init__(self): def __init__(self):
# Set the options that will be presented inside the dropdown # Set the options that will be presented inside the dropdown
options = [ options = [
discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'), discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),

1
examples/views/dynamic_counter.py

@ -15,6 +15,7 @@ import re
# `counter:5:user:80088516616269824` where the first number is the current count and the # `counter:5:user:80088516616269824` where the first number is the current count and the
# second number is the user ID who owns the button. # second number is the user ID who owns the button.
# Note that custom_ids can only be up to 100 characters long. # Note that custom_ids can only be up to 100 characters long.
class DynamicCounter( class DynamicCounter(
discord.ui.DynamicItem[discord.ui.Button], discord.ui.DynamicItem[discord.ui.Button],

1
examples/views/ephemeral.py

@ -22,7 +22,6 @@ class EphemeralCounterBot(commands.Bot):
# Define a simple View that gives us a counter button # Define a simple View that gives us a counter button
class Counter(discord.ui.View): class Counter(discord.ui.View):
# Define the actual button # Define the actual button
# When pressed, this increments the number displayed until it hits 5. # When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green. # When it hits 5, the counter button is disabled and it turns green.

28
examples/views/settings.py

@ -9,24 +9,24 @@ import enum
class FruitType(enum.Enum): class FruitType(enum.Enum):
apple = "Apple" apple = 'Apple'
banana = "Banana" banana = 'Banana'
orange = "Orange" orange = 'Orange'
grape = "Grape" grape = 'Grape'
mango = "Mango" mango = 'Mango'
watermelon = "Watermelon" watermelon = 'Watermelon'
coconut = "Coconut" coconut = 'Coconut'
@property @property
def emoji(self) -> str: def emoji(self) -> str:
emojis = { emojis = {
"Apple": "🍎", 'Apple': '🍎',
"Banana": "🍌", 'Banana': '🍌',
"Orange": "🍊", 'Orange': '🍊',
"Grape": "🍇", 'Grape': '🍇',
"Mango": "🥭", 'Mango': '🥭',
"Watermelon": "🍉", 'Watermelon': '🍉',
"Coconut": "🥥", 'Coconut': '🥥',
} }
return emojis[self.value] return emojis[self.value]

1
examples/views/tic_tac_toe.py

@ -4,6 +4,7 @@ from typing import List
from discord.ext import commands from discord.ext import commands
import discord import discord
# Defines a custom button that contains the logic of the game. # Defines a custom button that contains the logic of the game.
# The ['TicTacToe'] bit is for type hinting purposes to tell your IDE or linter # The ['TicTacToe'] bit is for type hinting purposes to tell your IDE or linter
# what the type of `self.view` is. It is not required. # what the type of `self.view` is. It is not required.

9
pyproject.toml

@ -70,7 +70,7 @@ test = [
"tzdata; sys_platform == 'win32'", "tzdata; sys_platform == 'win32'",
] ]
dev = [ dev = [
"black==22.6", "ruff==0.12",
"typing_extensions>=4.3,<5", "typing_extensions>=4.3,<5",
] ]
@ -90,6 +90,13 @@ include-package-data = true
line-length = 125 line-length = 125
skip-string-normalization = true skip-string-normalization = true
[tool.ruff]
line-length = 125
[tool.ruff.format]
line-ending = "lf"
quote-style = "single"
[tool.coverage.run] [tool.coverage.run]
omit = [ omit = [
"discord/__main__.py", "discord/__main__.py",

Loading…
Cancel
Save