Browse Source

Merge branch 'master' of https://github.com/Rapptz/discord.py into recurrent_events

pull/9685/head
Developer Anonymous 11 months ago
parent
commit
368eedd841
  1. 2
      .github/workflows/lint.yml
  2. 1
      discord/__init__.py
  3. 37
      discord/abc.py
  4. 1
      discord/app_commands/__init__.py
  5. 2
      discord/app_commands/checks.py
  6. 402
      discord/app_commands/commands.py
  7. 207
      discord/app_commands/installs.py
  8. 35
      discord/app_commands/models.py
  9. 4
      discord/app_commands/namespace.py
  10. 8
      discord/app_commands/transformers.py
  11. 70
      discord/app_commands/tree.py
  12. 6
      discord/appinfo.py
  13. 15
      discord/asset.py
  14. 4
      discord/automod.py
  15. 30
      discord/channel.py
  16. 61
      discord/client.py
  17. 2
      discord/colour.py
  18. 21
      discord/components.py
  19. 47
      discord/enums.py
  20. 22
      discord/ext/commands/bot.py
  21. 6
      discord/ext/commands/cog.py
  22. 21
      discord/ext/commands/context.py
  23. 65
      discord/ext/commands/converter.py
  24. 6
      discord/ext/commands/core.py
  25. 39
      discord/ext/commands/flags.py
  26. 10
      discord/ext/commands/help.py
  27. 6
      discord/ext/commands/hybrid.py
  28. 2
      discord/file.py
  29. 227
      discord/flags.py
  30. 2
      discord/gateway.py
  31. 185
      discord/guild.py
  32. 82
      discord/http.py
  33. 78
      discord/interactions.py
  34. 10
      discord/invite.py
  35. 40
      discord/member.py
  36. 217
      discord/message.py
  37. 2
      discord/object.py
  38. 48
      discord/permissions.py
  39. 15
      discord/player.py
  40. 576
      discord/poll.py
  41. 62
      discord/raw_models.py
  42. 17
      discord/reaction.py
  43. 30
      discord/shard.py
  44. 24
      discord/sku.py
  45. 93
      discord/state.py
  46. 5
      discord/sticker.py
  47. 16
      discord/threads.py
  48. 4
      discord/types/command.py
  49. 3
      discord/types/components.py
  50. 15
      discord/types/gateway.py
  51. 11
      discord/types/guild.py
  52. 22
      discord/types/interactions.py
  53. 2
      discord/types/invite.py
  54. 5
      discord/types/member.py
  55. 45
      discord/types/message.py
  56. 88
      discord/types/poll.py
  57. 3
      discord/types/sku.py
  58. 7
      discord/types/user.py
  59. 34
      discord/ui/button.py
  60. 9
      discord/ui/dynamic.py
  61. 3
      discord/ui/modal.py
  62. 38
      discord/ui/select.py
  63. 6
      discord/ui/text_input.py
  64. 24
      discord/ui/view.py
  65. 53
      discord/user.py
  66. 14
      discord/utils.py
  67. 6
      discord/voice_client.py
  68. 177
      discord/voice_state.py
  69. 33
      discord/webhook/async_.py
  70. 36
      discord/webhook/sync.py
  71. 2
      discord/welcome_screen.py
  72. 205
      docs/api.rst
  73. 20
      docs/ext/commands/commands.rst
  74. 47
      docs/interactions/api.rst
  75. 3592
      docs/locale/ja/LC_MESSAGES/api.po
  76. 2
      docs/locale/ja/LC_MESSAGES/discord.po
  77. 2
      docs/locale/ja/LC_MESSAGES/ext/tasks/index.po
  78. 2
      docs/locale/ja/LC_MESSAGES/faq.po
  79. 2
      docs/locale/ja/LC_MESSAGES/intents.po
  80. 2
      docs/locale/ja/LC_MESSAGES/intro.po
  81. 14
      docs/locale/ja/LC_MESSAGES/logging.po
  82. 2
      docs/locale/ja/LC_MESSAGES/migrating.po
  83. 2
      docs/locale/ja/LC_MESSAGES/migrating_to_async.po
  84. 2
      docs/locale/ja/LC_MESSAGES/migrating_to_v1.po
  85. 2
      docs/locale/ja/LC_MESSAGES/quickstart.po
  86. 2
      docs/locale/ja/LC_MESSAGES/sphinx.po
  87. 2
      docs/locale/ja/LC_MESSAGES/version_guarantees.po
  88. 1814
      docs/locale/ja/LC_MESSAGES/whats_new.po
  89. 1
      docs/whats_new.rst
  90. 81
      pyproject.toml
  91. 1
      requirements.txt
  92. 130
      setup.py

2
.github/workflows/lint.yml

@ -38,7 +38,7 @@ jobs:
- name: Run Pyright - name: Run Pyright
uses: jakebailey/pyright-action@v1 uses: jakebailey/pyright-action@v1
with: with:
version: '1.1.316' version: '1.1.351'
warnings: false warnings: false
no-comments: ${{ matrix.python-version != '3.x' }} no-comments: ${{ matrix.python-version != '3.x' }}

1
discord/__init__.py

@ -69,6 +69,7 @@ from .interactions import *
from .components import * from .components import *
from .threads import * from .threads import *
from .automod import * from .automod import *
from .poll import *
class VersionInfo(NamedTuple): class VersionInfo(NamedTuple):

37
discord/abc.py

@ -92,6 +92,7 @@ if TYPE_CHECKING:
VoiceChannel, VoiceChannel,
StageChannel, StageChannel,
) )
from .poll import Poll
from .threads import Thread from .threads import Thread
from .ui.view import View from .ui.view import View
from .types.channel import ( from .types.channel import (
@ -248,6 +249,22 @@ class User(Snowflake, Protocol):
"""Optional[:class:`~discord.Asset`]: Returns an Asset that represents the user's avatar, if present.""" """Optional[:class:`~discord.Asset`]: Returns an Asset that represents the user's avatar, if present."""
raise NotImplementedError raise NotImplementedError
@property
def avatar_decoration(self) -> Optional[Asset]:
"""Optional[:class:`~discord.Asset`]: Returns an Asset that represents the user's avatar decoration, if present.
.. versionadded:: 2.4
"""
raise NotImplementedError
@property
def avatar_decoration_sku_id(self) -> Optional[int]:
"""Optional[:class:`int`]: Returns an integer that represents the user's avatar decoration SKU ID, if present.
.. versionadded:: 2.4
"""
raise NotImplementedError
@property @property
def default_avatar(self) -> Asset: def default_avatar(self) -> Asset:
""":class:`~discord.Asset`: Returns the default avatar for a given user.""" """:class:`~discord.Asset`: Returns the default avatar for a given user."""
@ -500,6 +517,13 @@ class GuildChannel:
raise TypeError('type field must be of type ChannelType') raise TypeError('type field must be of type ChannelType')
options['type'] = ch_type.value options['type'] = ch_type.value
try:
status = options.pop('status')
except KeyError:
pass
else:
await self._state.http.edit_voice_channel_status(status, channel_id=self.id, reason=reason)
if options: if options:
return await self._state.http.edit_channel(self.id, reason=reason, **options) return await self._state.http.edit_channel(self.id, reason=reason, **options)
@ -1327,6 +1351,7 @@ class Messageable:
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1347,6 +1372,7 @@ class Messageable:
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1367,6 +1393,7 @@ class Messageable:
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1387,6 +1414,7 @@ class Messageable:
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1408,6 +1436,7 @@ class Messageable:
view: Optional[View] = None, view: Optional[View] = None,
suppress_embeds: bool = False, suppress_embeds: bool = False,
silent: bool = False, silent: bool = False,
poll: Optional[Poll] = None,
) -> Message: ) -> Message:
"""|coro| """|coro|
@ -1493,6 +1522,10 @@ class Messageable:
in the UI, but will not actually send a notification. in the UI, but will not actually send a notification.
.. versionadded:: 2.2 .. versionadded:: 2.2
poll: :class:`~discord.Poll`
The poll to send with this message.
.. versionadded:: 2.4
Raises Raises
-------- --------
@ -1559,6 +1592,7 @@ class Messageable:
stickers=sticker_ids, stickers=sticker_ids,
view=view, view=view,
flags=flags, flags=flags,
poll=poll,
) as params: ) as params:
data = await state.http.send_message(channel.id, params=params) data = await state.http.send_message(channel.id, params=params)
@ -1566,6 +1600,9 @@ class Messageable:
if view and not view.is_finished(): if view and not view.is_finished():
state.store_view(view, ret.id) state.store_view(view, ret.id)
if poll:
poll._update(ret)
if delete_after is not None: if delete_after is not None:
await ret.delete(delay=delete_after) await ret.delete(delay=delete_after)
return ret return ret

1
discord/app_commands/__init__.py

@ -16,5 +16,6 @@ from .tree import *
from .namespace import * from .namespace import *
from .transformers import * from .transformers import *
from .translator import * from .translator import *
from .installs import *
from . import checks as checks from . import checks as checks
from .checks import Cooldown as Cooldown from .checks import Cooldown as Cooldown

2
discord/app_commands/checks.py

@ -186,7 +186,7 @@ class Cooldown:
:class:`Cooldown` :class:`Cooldown`
A new instance of this cooldown. A new instance of this cooldown.
""" """
return Cooldown(self.rate, self.per) return self.__class__(self.rate, self.per)
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Cooldown rate: {self.rate} per: {self.per} window: {self._window} tokens: {self._tokens}>' return f'<Cooldown rate: {self.rate} per: {self.per} window: {self._window} tokens: {self._tokens}>'

402
discord/app_commands/commands.py

@ -49,6 +49,7 @@ import re
from copy import copy as shallow_copy from copy import copy as shallow_copy
from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale from ..enums import AppCommandOptionType, AppCommandType, ChannelType, Locale
from .installs import AppCommandContext, AppInstallationType
from .models import Choice from .models import Choice
from .transformers import annotation_to_parameter, CommandParameter, NoneType from .transformers import annotation_to_parameter, CommandParameter, NoneType
from .errors import AppCommandError, CheckFailure, CommandInvokeError, CommandSignatureMismatch, CommandAlreadyRegistered from .errors import AppCommandError, CheckFailure, CommandInvokeError, CommandSignatureMismatch, CommandAlreadyRegistered
@ -65,6 +66,8 @@ if TYPE_CHECKING:
from ..abc import Snowflake from ..abc import Snowflake
from .namespace import Namespace from .namespace import Namespace
from .models import ChoiceT from .models import ChoiceT
from .tree import CommandTree
from .._types import ClientT
# Generally, these two libraries are supposed to be separate from each other. # Generally, these two libraries are supposed to be separate from each other.
# However, for type hinting purposes it's unfortunately necessary for one to # However, for type hinting purposes it's unfortunately necessary for one to
@ -87,6 +90,12 @@ __all__ = (
'autocomplete', 'autocomplete',
'guilds', 'guilds',
'guild_only', 'guild_only',
'dm_only',
'private_channel_only',
'allowed_contexts',
'guild_install',
'user_install',
'allowed_installs',
'default_permissions', 'default_permissions',
) )
@ -618,6 +627,16 @@ class Command(Generic[GroupT, P, T]):
Whether the command should only be usable in guild contexts. Whether the command should only be usable in guild contexts.
Due to a Discord limitation, this does not work on subcommands. Due to a Discord limitation, this does not work on subcommands.
allowed_contexts: Optional[:class:`~discord.app_commands.AppCommandContext`]
The contexts that the command is allowed to be used in.
Overrides ``guild_only`` if this is set.
.. versionadded:: 2.4
allowed_installs: Optional[:class:`~discord.app_commands.AppInstallationType`]
The installation contexts that the command is allowed to be installed
on.
.. versionadded:: 2.4
nsfw: :class:`bool` nsfw: :class:`bool`
Whether the command is NSFW and should only work in NSFW channels. Whether the command is NSFW and should only work in NSFW channels.
@ -638,6 +657,8 @@ class Command(Generic[GroupT, P, T]):
nsfw: bool = False, nsfw: bool = False,
parent: Optional[Group] = None, parent: Optional[Group] = None,
guild_ids: Optional[List[int]] = None, guild_ids: Optional[List[int]] = None,
allowed_contexts: Optional[AppCommandContext] = None,
allowed_installs: Optional[AppInstallationType] = None,
auto_locale_strings: bool = True, auto_locale_strings: bool = True,
extras: Dict[Any, Any] = MISSING, extras: Dict[Any, Any] = MISSING,
): ):
@ -672,6 +693,13 @@ class Command(Generic[GroupT, P, T]):
callback, '__discord_app_commands_default_permissions__', None callback, '__discord_app_commands_default_permissions__', None
) )
self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False) self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False)
self.allowed_contexts: Optional[AppCommandContext] = allowed_contexts or getattr(
callback, '__discord_app_commands_contexts__', None
)
self.allowed_installs: Optional[AppInstallationType] = allowed_installs or getattr(
callback, '__discord_app_commands_installation_types__', None
)
self.nsfw: bool = nsfw self.nsfw: bool = nsfw
self.extras: Dict[Any, Any] = extras or {} self.extras: Dict[Any, Any] = extras or {}
@ -718,8 +746,8 @@ class Command(Generic[GroupT, P, T]):
return copy return copy
async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: async def get_translated_payload(self, tree: CommandTree[ClientT], translator: Translator) -> Dict[str, Any]:
base = self.to_dict() base = self.to_dict(tree)
name_localizations: Dict[str, str] = {} name_localizations: Dict[str, str] = {}
description_localizations: Dict[str, str] = {} description_localizations: Dict[str, str] = {}
@ -745,7 +773,7 @@ class Command(Generic[GroupT, P, T]):
] ]
return base return base
def to_dict(self) -> Dict[str, Any]: def to_dict(self, tree: CommandTree[ClientT]) -> Dict[str, Any]:
# If we have a parent then our type is a subcommand # If we have a parent then our type is a subcommand
# Otherwise, the type falls back to the specific command type (e.g. slash command or context menu) # Otherwise, the type falls back to the specific command type (e.g. slash command or context menu)
option_type = AppCommandType.chat_input.value if self.parent is None else AppCommandOptionType.subcommand.value option_type = AppCommandType.chat_input.value if self.parent is None else AppCommandOptionType.subcommand.value
@ -760,6 +788,8 @@ class Command(Generic[GroupT, P, T]):
base['nsfw'] = self.nsfw base['nsfw'] = self.nsfw
base['dm_permission'] = not self.guild_only base['dm_permission'] = not self.guild_only
base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value
base['contexts'] = tree.allowed_contexts._merge_to_array(self.allowed_contexts)
base['integration_types'] = tree.allowed_installs._merge_to_array(self.allowed_installs)
return base return base
@ -1068,7 +1098,7 @@ class Command(Generic[GroupT, P, T]):
def decorator(coro: AutocompleteCallback[GroupT, ChoiceT]) -> AutocompleteCallback[GroupT, ChoiceT]: def decorator(coro: AutocompleteCallback[GroupT, ChoiceT]) -> AutocompleteCallback[GroupT, ChoiceT]:
if not inspect.iscoroutinefunction(coro): if not inspect.iscoroutinefunction(coro):
raise TypeError('The error handler must be a coroutine.') raise TypeError('The autocomplete callback must be a coroutine function.')
try: try:
param = self._params[name] param = self._params[name]
@ -1167,6 +1197,16 @@ class ContextMenu:
guild_only: :class:`bool` guild_only: :class:`bool`
Whether the command should only be usable in guild contexts. Whether the command should only be usable in guild contexts.
Defaults to ``False``. Defaults to ``False``.
allowed_contexts: Optional[:class:`~discord.app_commands.AppCommandContext`]
The contexts that this context menu is allowed to be used in.
Overrides ``guild_only`` if set.
.. versionadded:: 2.4
allowed_installs: Optional[:class:`~discord.app_commands.AppInstallationType`]
The installation contexts that the command is allowed to be installed
on.
.. versionadded:: 2.4
nsfw: :class:`bool` nsfw: :class:`bool`
Whether the command is NSFW and should only work in NSFW channels. Whether the command is NSFW and should only work in NSFW channels.
Defaults to ``False``. Defaults to ``False``.
@ -1189,6 +1229,8 @@ class ContextMenu:
type: AppCommandType = MISSING, type: AppCommandType = MISSING,
nsfw: bool = False, nsfw: bool = False,
guild_ids: Optional[List[int]] = None, guild_ids: Optional[List[int]] = None,
allowed_contexts: Optional[AppCommandContext] = None,
allowed_installs: Optional[AppInstallationType] = None,
auto_locale_strings: bool = True, auto_locale_strings: bool = True,
extras: Dict[Any, Any] = MISSING, extras: Dict[Any, Any] = MISSING,
): ):
@ -1214,6 +1256,12 @@ class ContextMenu:
) )
self.nsfw: bool = nsfw self.nsfw: bool = nsfw
self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False) self.guild_only: bool = getattr(callback, '__discord_app_commands_guild_only__', False)
self.allowed_contexts: Optional[AppCommandContext] = allowed_contexts or getattr(
callback, '__discord_app_commands_contexts__', None
)
self.allowed_installs: Optional[AppInstallationType] = allowed_installs or getattr(
callback, '__discord_app_commands_installation_types__', None
)
self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', []) self.checks: List[Check] = getattr(callback, '__discord_app_commands_checks__', [])
self.extras: Dict[Any, Any] = extras or {} self.extras: Dict[Any, Any] = extras or {}
@ -1231,8 +1279,8 @@ class ContextMenu:
""":class:`str`: Returns the fully qualified command name.""" """:class:`str`: Returns the fully qualified command name."""
return self.name return self.name
async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: async def get_translated_payload(self, tree: CommandTree[ClientT], translator: Translator) -> Dict[str, Any]:
base = self.to_dict() base = self.to_dict(tree)
context = TranslationContext(location=TranslationContextLocation.command_name, data=self) context = TranslationContext(location=TranslationContextLocation.command_name, data=self)
if self._locale_name: if self._locale_name:
name_localizations: Dict[str, str] = {} name_localizations: Dict[str, str] = {}
@ -1244,11 +1292,13 @@ class ContextMenu:
base['name_localizations'] = name_localizations base['name_localizations'] = name_localizations
return base return base
def to_dict(self) -> Dict[str, Any]: def to_dict(self, tree: CommandTree[ClientT]) -> Dict[str, Any]:
return { return {
'name': self.name, 'name': self.name,
'type': self.type.value, 'type': self.type.value,
'dm_permission': not self.guild_only, 'dm_permission': not self.guild_only,
'contexts': tree.allowed_contexts._merge_to_array(self.allowed_contexts),
'integration_types': tree.allowed_installs._merge_to_array(self.allowed_installs),
'default_member_permissions': None if self.default_permissions is None else self.default_permissions.value, 'default_member_permissions': None if self.default_permissions is None else self.default_permissions.value,
'nsfw': self.nsfw, 'nsfw': self.nsfw,
} }
@ -1405,6 +1455,16 @@ class Group:
Whether the group should only be usable in guild contexts. Whether the group should only be usable in guild contexts.
Due to a Discord limitation, this does not work on subcommands. Due to a Discord limitation, this does not work on subcommands.
allowed_contexts: Optional[:class:`~discord.app_commands.AppCommandContext`]
The contexts that this group is allowed to be used in. Overrides
guild_only if set.
.. versionadded:: 2.4
allowed_installs: Optional[:class:`~discord.app_commands.AppInstallationType`]
The installation contexts that the command is allowed to be installed
on.
.. versionadded:: 2.4
nsfw: :class:`bool` nsfw: :class:`bool`
Whether the command is NSFW and should only work in NSFW channels. Whether the command is NSFW and should only work in NSFW channels.
@ -1424,6 +1484,8 @@ class Group:
__discord_app_commands_group_locale_description__: Optional[locale_str] = None __discord_app_commands_group_locale_description__: Optional[locale_str] = None
__discord_app_commands_group_nsfw__: bool = False __discord_app_commands_group_nsfw__: bool = False
__discord_app_commands_guild_only__: bool = MISSING __discord_app_commands_guild_only__: bool = MISSING
__discord_app_commands_contexts__: Optional[AppCommandContext] = 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[
@ -1492,6 +1554,8 @@ class Group:
parent: Optional[Group] = None, parent: Optional[Group] = None,
guild_ids: Optional[List[int]] = None, guild_ids: Optional[List[int]] = None,
guild_only: bool = MISSING, guild_only: bool = MISSING,
allowed_contexts: Optional[AppCommandContext] = MISSING,
allowed_installs: Optional[AppInstallationType] = MISSING,
nsfw: bool = MISSING, nsfw: bool = MISSING,
auto_locale_strings: bool = True, auto_locale_strings: bool = True,
default_permissions: Optional[Permissions] = MISSING, default_permissions: Optional[Permissions] = MISSING,
@ -1540,6 +1604,22 @@ class Group:
self.guild_only: bool = guild_only self.guild_only: bool = guild_only
if allowed_contexts is MISSING:
if cls.__discord_app_commands_contexts__ is MISSING:
allowed_contexts = None
else:
allowed_contexts = cls.__discord_app_commands_contexts__
self.allowed_contexts: Optional[AppCommandContext] = allowed_contexts
if allowed_installs is MISSING:
if cls.__discord_app_commands_installation_types__ is MISSING:
allowed_installs = None
else:
allowed_installs = cls.__discord_app_commands_installation_types__
self.allowed_installs: Optional[AppInstallationType] = allowed_installs
if nsfw is MISSING: if nsfw is MISSING:
nsfw = cls.__discord_app_commands_group_nsfw__ nsfw = cls.__discord_app_commands_group_nsfw__
@ -1633,8 +1713,8 @@ class Group:
return copy return copy
async def get_translated_payload(self, translator: Translator) -> Dict[str, Any]: async def get_translated_payload(self, tree: CommandTree[ClientT], translator: Translator) -> Dict[str, Any]:
base = self.to_dict() base = self.to_dict(tree)
name_localizations: Dict[str, str] = {} name_localizations: Dict[str, str] = {}
description_localizations: Dict[str, str] = {} description_localizations: Dict[str, str] = {}
@ -1654,10 +1734,10 @@ class Group:
base['name_localizations'] = name_localizations base['name_localizations'] = name_localizations
base['description_localizations'] = description_localizations base['description_localizations'] = description_localizations
base['options'] = [await child.get_translated_payload(translator) for child in self._children.values()] base['options'] = [await child.get_translated_payload(tree, translator) for child in self._children.values()]
return base return base
def to_dict(self) -> Dict[str, Any]: def to_dict(self, tree: CommandTree[ClientT]) -> Dict[str, Any]:
# If this has a parent command then it's part of a subcommand group # If this has a parent command then it's part of a subcommand group
# Otherwise, it's just a regular command # Otherwise, it's just a regular command
option_type = 1 if self.parent is None else AppCommandOptionType.subcommand_group.value option_type = 1 if self.parent is None else AppCommandOptionType.subcommand_group.value
@ -1665,13 +1745,15 @@ class Group:
'name': self.name, 'name': self.name,
'description': self.description, 'description': self.description,
'type': option_type, 'type': option_type,
'options': [child.to_dict() for child in self._children.values()], 'options': [child.to_dict(tree) for child in self._children.values()],
} }
if self.parent is None: if self.parent is None:
base['nsfw'] = self.nsfw base['nsfw'] = self.nsfw
base['dm_permission'] = not self.guild_only base['dm_permission'] = not self.guild_only
base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value base['default_member_permissions'] = None if self.default_permissions is None else self.default_permissions.value
base['contexts'] = tree.allowed_contexts._merge_to_array(self.allowed_contexts)
base['integration_types'] = tree.allowed_installs._merge_to_array(self.allowed_installs)
return base return base
@ -2290,6 +2372,12 @@ def guilds(*guild_ids: Union[Snowflake, int]) -> Callable[[T], T]:
with the :meth:`CommandTree.command` or :meth:`CommandTree.context_menu` decorator with the :meth:`CommandTree.command` or :meth:`CommandTree.context_menu` decorator
then this must go below that decorator. then this must go below that decorator.
.. note ::
Due to a Discord limitation, this decorator cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
Example: Example:
.. code-block:: python3 .. code-block:: python3
@ -2421,8 +2509,257 @@ def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
def inner(f: T) -> T: def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)): if isinstance(f, (Command, Group, ContextMenu)):
f.guild_only = True f.guild_only = True
allowed_contexts = f.allowed_contexts or AppCommandContext()
f.allowed_contexts = allowed_contexts
else: else:
f.__discord_app_commands_guild_only__ = True # type: ignore # Runtime attribute assignment f.__discord_app_commands_guild_only__ = True # type: ignore # Runtime attribute assignment
allowed_contexts = getattr(f, '__discord_app_commands_contexts__', None) or AppCommandContext()
f.__discord_app_commands_contexts__ = allowed_contexts # type: ignore # Runtime attribute assignment
allowed_contexts.guild = True
return f
# Check if called with parentheses or not
if func is None:
# Called with parentheses
return inner
else:
return inner(func)
@overload
def private_channel_only(func: None = ...) -> Callable[[T], T]:
...
@overload
def private_channel_only(func: T) -> T:
...
def private_channel_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
"""A decorator that indicates this command can only be used in the context of DMs and group DMs.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Therefore, there is no error handler called when a command is used within a guild.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.private_channel_only()
async def my_private_channel_only_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am only available in DMs and GDMs!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
f.guild_only = False
allowed_contexts = f.allowed_contexts or AppCommandContext()
f.allowed_contexts = allowed_contexts
else:
allowed_contexts = getattr(f, '__discord_app_commands_contexts__', None) or AppCommandContext()
f.__discord_app_commands_contexts__ = allowed_contexts # type: ignore # Runtime attribute assignment
allowed_contexts.private_channel = True
return f
# Check if called with parentheses or not
if func is None:
# Called with parentheses
return inner
else:
return inner(func)
@overload
def dm_only(func: None = ...) -> Callable[[T], T]:
...
@overload
def dm_only(func: T) -> T:
...
def dm_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
"""A decorator that indicates this command can only be used in the context of bot DMs.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Therefore, there is no error handler called when a command is used within a guild or group DM.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.dm_only()
async def my_dm_only_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am only available in DMs!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
f.guild_only = False
allowed_contexts = f.allowed_contexts or AppCommandContext()
f.allowed_contexts = allowed_contexts
else:
allowed_contexts = getattr(f, '__discord_app_commands_contexts__', None) or AppCommandContext()
f.__discord_app_commands_contexts__ = allowed_contexts # type: ignore # Runtime attribute assignment
allowed_contexts.dm_channel = True
return f
# Check if called with parentheses or not
if func is None:
# Called with parentheses
return inner
else:
return inner(func)
def allowed_contexts(guilds: bool = MISSING, dms: bool = MISSING, private_channels: bool = MISSING) -> Callable[[T], T]:
"""A decorator that indicates this command can only be used in certain contexts.
Valid contexts are guilds, DMs and private channels.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.allowed_contexts(guilds=True, dms=False, private_channels=True)
async def my_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am only available in guilds and private channels!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
f.guild_only = False
allowed_contexts = f.allowed_contexts or AppCommandContext()
f.allowed_contexts = allowed_contexts
else:
allowed_contexts = getattr(f, '__discord_app_commands_contexts__', None) or AppCommandContext()
f.__discord_app_commands_contexts__ = allowed_contexts # type: ignore # Runtime attribute assignment
if guilds is not MISSING:
allowed_contexts.guild = guilds
if dms is not MISSING:
allowed_contexts.dm_channel = dms
if private_channels is not MISSING:
allowed_contexts.private_channel = private_channels
return f
return inner
@overload
def guild_install(func: None = ...) -> Callable[[T], T]:
...
@overload
def guild_install(func: T) -> T:
...
def guild_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
"""A decorator that indicates this command should be installed in guilds.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.guild_install()
async def my_guild_install_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am installed in guilds by default!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
allowed_installs = f.allowed_installs or AppInstallationType()
f.allowed_installs = allowed_installs
else:
allowed_installs = getattr(f, '__discord_app_commands_installation_types__', None) or AppInstallationType()
f.__discord_app_commands_installation_types__ = allowed_installs # type: ignore # Runtime attribute assignment
allowed_installs.guild = True
return f
# Check if called with parentheses or not
if func is None:
# Called with parentheses
return inner
else:
return inner(func)
@overload
def user_install(func: None = ...) -> Callable[[T], T]:
...
@overload
def user_install(func: T) -> T:
...
def user_install(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
"""A decorator that indicates this command should be installed for users.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.user_install()
async def my_user_install_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am installed in users by default!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
allowed_installs = f.allowed_installs or AppInstallationType()
f.allowed_installs = allowed_installs
else:
allowed_installs = getattr(f, '__discord_app_commands_installation_types__', None) or AppInstallationType()
f.__discord_app_commands_installation_types__ = allowed_installs # type: ignore # Runtime attribute assignment
allowed_installs.user = True
return f return f
# Check if called with parentheses or not # Check if called with parentheses or not
@ -2433,6 +2770,47 @@ def guild_only(func: Optional[T] = None) -> Union[T, Callable[[T], T]]:
return inner(func) return inner(func)
def allowed_installs(
guilds: bool = MISSING,
users: bool = MISSING,
) -> Callable[[T], T]:
"""A decorator that indicates this command should be installed in certain contexts.
Valid contexts are guilds and users.
This is **not** implemented as a :func:`check`, and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples
---------
.. code-block:: python3
@app_commands.command()
@app_commands.allowed_installs(guilds=False, users=True)
async def my_command(interaction: discord.Interaction) -> None:
await interaction.response.send_message('I am installed in users by default!')
"""
def inner(f: T) -> T:
if isinstance(f, (Command, Group, ContextMenu)):
allowed_installs = f.allowed_installs or AppInstallationType()
f.allowed_installs = allowed_installs
else:
allowed_installs = getattr(f, '__discord_app_commands_installation_types__', None) or AppInstallationType()
f.__discord_app_commands_installation_types__ = allowed_installs # type: ignore # Runtime attribute assignment
if guilds is not MISSING:
allowed_installs.guild = guilds
if users is not MISSING:
allowed_installs.user = users
return f
return inner
def default_permissions(**perms: bool) -> Callable[[T], T]: def default_permissions(**perms: bool) -> Callable[[T], T]:
r"""A decorator that sets the default permissions needed to execute this command. r"""A decorator that sets the default permissions needed to execute this command.

207
discord/app_commands/installs.py

@ -0,0 +1,207 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, ClassVar, List, Optional, Sequence
__all__ = (
'AppInstallationType',
'AppCommandContext',
)
if TYPE_CHECKING:
from typing_extensions import Self
from ..types.interactions import InteractionContextType, InteractionInstallationType
class AppInstallationType:
r"""Represents the installation location of an application command.
.. versionadded:: 2.4
Parameters
-----------
guild: Optional[:class:`bool`]
Whether the integration is a guild install.
user: Optional[:class:`bool`]
Whether the integration is a user install.
"""
__slots__ = ('_guild', '_user')
GUILD: ClassVar[int] = 0
USER: ClassVar[int] = 1
def __init__(self, *, guild: Optional[bool] = None, user: Optional[bool] = None):
self._guild: Optional[bool] = guild
self._user: Optional[bool] = user
@property
def guild(self) -> bool:
""":class:`bool`: Whether the integration is a guild install."""
return bool(self._guild)
@guild.setter
def guild(self, value: bool) -> None:
self._guild = bool(value)
@property
def user(self) -> bool:
""":class:`bool`: Whether the integration is a user install."""
return bool(self._user)
@user.setter
def user(self, value: bool) -> None:
self._user = bool(value)
def merge(self, other: AppInstallationType) -> AppInstallationType:
# Merging is similar to AllowedMentions where `self` is the base
# and the `other` is the override preference
guild = self._guild if other._guild is None else other._guild
user = self._user if other._user is None else other._user
return AppInstallationType(guild=guild, user=user)
def _is_unset(self) -> bool:
return all(x is None for x in (self._guild, self._user))
def _merge_to_array(self, other: Optional[AppInstallationType]) -> Optional[List[InteractionInstallationType]]:
result = self.merge(other) if other is not None else self
if result._is_unset():
return None
return result.to_array()
@classmethod
def _from_value(cls, value: Sequence[InteractionInstallationType]) -> Self:
self = cls()
for x in value:
if x == cls.GUILD:
self._guild = True
elif x == cls.USER:
self._user = True
return self
def to_array(self) -> List[InteractionInstallationType]:
values = []
if self._guild:
values.append(self.GUILD)
if self._user:
values.append(self.USER)
return values
class AppCommandContext:
r"""Wraps up the Discord :class:`~discord.app_commands.Command` execution context.
.. versionadded:: 2.4
Parameters
-----------
guild: Optional[:class:`bool`]
Whether the context allows usage in a guild.
dm_channel: Optional[:class:`bool`]
Whether the context allows usage in a DM channel.
private_channel: Optional[:class:`bool`]
Whether the context allows usage in a DM or a GDM channel.
"""
GUILD: ClassVar[int] = 0
DM_CHANNEL: ClassVar[int] = 1
PRIVATE_CHANNEL: ClassVar[int] = 2
__slots__ = ('_guild', '_dm_channel', '_private_channel')
def __init__(
self,
*,
guild: Optional[bool] = None,
dm_channel: Optional[bool] = None,
private_channel: Optional[bool] = None,
):
self._guild: Optional[bool] = guild
self._dm_channel: Optional[bool] = dm_channel
self._private_channel: Optional[bool] = private_channel
@property
def guild(self) -> bool:
""":class:`bool`: Whether the context allows usage in a guild."""
return bool(self._guild)
@guild.setter
def guild(self, value: bool) -> None:
self._guild = bool(value)
@property
def dm_channel(self) -> bool:
""":class:`bool`: Whether the context allows usage in a DM channel."""
return bool(self._dm_channel)
@dm_channel.setter
def dm_channel(self, value: bool) -> None:
self._dm_channel = bool(value)
@property
def private_channel(self) -> bool:
""":class:`bool`: Whether the context allows usage in a DM or a GDM channel."""
return bool(self._private_channel)
@private_channel.setter
def private_channel(self, value: bool) -> None:
self._private_channel = bool(value)
def merge(self, other: AppCommandContext) -> AppCommandContext:
guild = self._guild if other._guild is None else other._guild
dm_channel = self._dm_channel if other._dm_channel is None else other._dm_channel
private_channel = self._private_channel if other._private_channel is None else other._private_channel
return AppCommandContext(guild=guild, dm_channel=dm_channel, private_channel=private_channel)
def _is_unset(self) -> bool:
return all(x is None for x in (self._guild, self._dm_channel, self._private_channel))
def _merge_to_array(self, other: Optional[AppCommandContext]) -> Optional[List[InteractionContextType]]:
result = self.merge(other) if other is not None else self
if result._is_unset():
return None
return result.to_array()
@classmethod
def _from_value(cls, value: Sequence[InteractionContextType]) -> Self:
self = cls()
for x in value:
if x == cls.GUILD:
self._guild = True
elif x == cls.DM_CHANNEL:
self._dm_channel = True
elif x == cls.PRIVATE_CHANNEL:
self._private_channel = True
return self
def to_array(self) -> List[InteractionContextType]:
values = []
if self._guild:
values.append(self.GUILD)
if self._dm_channel:
values.append(self.DM_CHANNEL)
if self._private_channel:
values.append(self.PRIVATE_CHANNEL)
return values

35
discord/app_commands/models.py

@ -26,9 +26,17 @@ from __future__ import annotations
from datetime import datetime from datetime import datetime
from .errors import MissingApplicationID from .errors import MissingApplicationID
from ..flags import AppCommandContext, AppInstallationType
from .translator import TranslationContextLocation, TranslationContext, locale_str, Translator from .translator import TranslationContextLocation, TranslationContext, locale_str, Translator
from ..permissions import Permissions from ..permissions import Permissions
from ..enums import AppCommandOptionType, AppCommandType, AppCommandPermissionType, ChannelType, Locale, try_enum from ..enums import (
AppCommandOptionType,
AppCommandType,
AppCommandPermissionType,
ChannelType,
Locale,
try_enum,
)
from ..mixins import Hashable from ..mixins import Hashable
from ..utils import _get_as_snowflake, parse_time, snowflake_time, MISSING from ..utils import _get_as_snowflake, parse_time, snowflake_time, MISSING
from ..object import Object from ..object import Object
@ -160,6 +168,14 @@ class AppCommand(Hashable):
The default member permissions that can run this command. The default member permissions that can run this command.
dm_permission: :class:`bool` dm_permission: :class:`bool`
A boolean that indicates whether this command can be run in direct messages. A boolean that indicates whether this command can be run in direct messages.
allowed_contexts: Optional[:class:`~discord.app_commands.AppCommandContext`]
The contexts that this command is allowed to be used in. Overrides the ``dm_permission`` attribute.
.. versionadded:: 2.4
allowed_installs: Optional[:class:`~discord.app_commands.AppInstallationType`]
The installation contexts that this command is allowed to be installed in.
.. versionadded:: 2.4
guild_id: Optional[:class:`int`] guild_id: Optional[:class:`int`]
The ID of the guild this command is registered in. A value of ``None`` The ID of the guild this command is registered in. A value of ``None``
denotes that it is a global command. denotes that it is a global command.
@ -179,6 +195,8 @@ class AppCommand(Hashable):
'options', 'options',
'default_member_permissions', 'default_member_permissions',
'dm_permission', 'dm_permission',
'allowed_contexts',
'allowed_installs',
'nsfw', 'nsfw',
'_state', '_state',
) )
@ -210,6 +228,19 @@ class AppCommand(Hashable):
dm_permission = True dm_permission = True
self.dm_permission: bool = dm_permission self.dm_permission: bool = dm_permission
allowed_contexts = data.get('contexts')
if allowed_contexts is None:
self.allowed_contexts: Optional[AppCommandContext] = None
else:
self.allowed_contexts = AppCommandContext._from_value(allowed_contexts)
allowed_installs = data.get('integration_types')
if allowed_installs is None:
self.allowed_installs: Optional[AppInstallationType] = None
else:
self.allowed_installs = AppInstallationType._from_value(allowed_installs)
self.nsfw: bool = data.get('nsfw', False) self.nsfw: bool = data.get('nsfw', False)
self.name_localizations: Dict[Locale, str] = _to_locale_dict(data.get('name_localizations') or {}) self.name_localizations: Dict[Locale, str] = _to_locale_dict(data.get('name_localizations') or {})
self.description_localizations: Dict[Locale, str] = _to_locale_dict(data.get('description_localizations') or {}) self.description_localizations: Dict[Locale, str] = _to_locale_dict(data.get('description_localizations') or {})
@ -223,6 +254,8 @@ class AppCommand(Hashable):
'description': self.description, 'description': self.description,
'name_localizations': {str(k): v for k, v in self.name_localizations.items()}, 'name_localizations': {str(k): v for k, v in self.name_localizations.items()},
'description_localizations': {str(k): v for k, v in self.description_localizations.items()}, 'description_localizations': {str(k): v for k, v in self.description_localizations.items()},
'contexts': self.allowed_contexts.to_array() if self.allowed_contexts is not None else None,
'integration_types': self.allowed_installs.to_array() if self.allowed_installs is not None else None,
'options': [opt.to_dict() for opt in self.options], 'options': [opt.to_dict() for opt in self.options],
} # type: ignore # Type checker does not understand this literal. } # type: ignore # Type checker does not understand this literal.

4
discord/app_commands/namespace.py

@ -179,7 +179,7 @@ class Namespace:
state = interaction._state state = interaction._state
members = resolved.get('members', {}) members = resolved.get('members', {})
guild_id = interaction.guild_id guild_id = interaction.guild_id
guild = state._get_or_create_unavailable_guild(guild_id) if guild_id is not None else None 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:
@ -220,7 +220,6 @@ class Namespace:
} }
) )
guild = state._get_guild(guild_id)
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:
@ -232,6 +231,7 @@ class Namespace:
# Type checker doesn't understand this due to failure to narrow # Type checker doesn't understand this due to failure to narrow
message = Message(state=state, channel=channel, data=message_data) # type: ignore message = Message(state=state, channel=channel, data=message_data) # type: ignore
message.guild = guild
key = ResolveKey(id=message_id, type=-1) key = ResolveKey(id=message_id, type=-1)
completed[key] = message completed[key] = message

8
discord/app_commands/transformers.py

@ -638,7 +638,7 @@ class BaseChannelTransformer(Transformer):
except KeyError: except KeyError:
raise TypeError('Union type of channels must be entirely made up of channels') from None raise TypeError('Union type of channels must be entirely made up of channels') from None
self._types: Tuple[Type[Any]] = channel_types self._types: Tuple[Type[Any], ...] = channel_types
self._channel_types: List[ChannelType] = types self._channel_types: List[ChannelType] = types
self._display_name = display_name self._display_name = display_name
@ -780,11 +780,11 @@ def get_supported_annotation(
# Check if there's an origin # Check if there's an origin
origin = getattr(annotation, '__origin__', None) origin = getattr(annotation, '__origin__', None)
if origin is Literal: if origin is Literal:
args = annotation.__args__ # type: ignore args = annotation.__args__
return (LiteralTransformer(args), MISSING, True) return (LiteralTransformer(args), MISSING, True)
if origin is Choice: if origin is Choice:
arg = annotation.__args__[0] # type: ignore arg = annotation.__args__[0]
return (ChoiceTransformer(arg), MISSING, True) return (ChoiceTransformer(arg), MISSING, True)
if origin is not Union: if origin is not Union:
@ -792,7 +792,7 @@ def get_supported_annotation(
raise TypeError(f'unsupported type annotation {annotation!r}') raise TypeError(f'unsupported type annotation {annotation!r}')
default = MISSING default = MISSING
args = annotation.__args__ # type: ignore args = annotation.__args__
if args[-1] is _none: if args[-1] is _none:
if len(args) == 2: if len(args) == 2:
underlying = args[0] underlying = args[0]

70
discord/app_commands/tree.py

@ -58,6 +58,7 @@ from .errors import (
CommandSyncFailure, CommandSyncFailure,
MissingApplicationID, MissingApplicationID,
) )
from .installs import AppCommandContext, AppInstallationType
from .translator import Translator, locale_str from .translator import Translator, locale_str
from ..errors import ClientException, HTTPException from ..errors import ClientException, HTTPException
from ..enums import AppCommandType, InteractionType from ..enums import AppCommandType, InteractionType
@ -121,9 +122,26 @@ class CommandTree(Generic[ClientT]):
to find the guild-specific ``/ping`` command it will fall back to the global ``/ping`` command. to find the guild-specific ``/ping`` command it will fall back to the global ``/ping`` command.
This has the potential to raise more :exc:`~discord.app_commands.CommandSignatureMismatch` errors This has the potential to raise more :exc:`~discord.app_commands.CommandSignatureMismatch` errors
than usual. Defaults to ``True``. than usual. Defaults to ``True``.
allowed_contexts: :class:`~discord.app_commands.AppCommandContext`
The default allowed contexts that applies to all commands in this tree.
Note that you can override this on a per command basis.
.. versionadded:: 2.4
allowed_installs: :class:`~discord.app_commands.AppInstallationType`
The default allowed install locations that apply to all commands in this tree.
Note that you can override this on a per command basis.
.. versionadded:: 2.4
""" """
def __init__(self, client: ClientT, *, fallback_to_global: bool = True): def __init__(
self,
client: ClientT,
*,
fallback_to_global: bool = True,
allowed_contexts: AppCommandContext = MISSING,
allowed_installs: AppInstallationType = MISSING,
):
self.client: ClientT = client self.client: ClientT = client
self._http = client.http self._http = client.http
self._state = client._connection self._state = client._connection
@ -133,6 +151,8 @@ class CommandTree(Generic[ClientT]):
self._state._command_tree = self self._state._command_tree = self
self.fallback_to_global: bool = fallback_to_global self.fallback_to_global: bool = fallback_to_global
self.allowed_contexts = AppCommandContext() if allowed_contexts is MISSING else allowed_contexts
self.allowed_installs = AppInstallationType() if allowed_installs is MISSING else allowed_installs
self._guild_commands: Dict[int, Dict[str, Union[Command, Group]]] = {} self._guild_commands: Dict[int, Dict[str, Union[Command, Group]]] = {}
self._global_commands: Dict[str, Union[Command, Group]] = {} self._global_commands: Dict[str, Union[Command, Group]] = {}
# (name, guild_id, command_type): Command # (name, guild_id, command_type): Command
@ -287,10 +307,24 @@ class CommandTree(Generic[ClientT]):
guild: Optional[:class:`~discord.abc.Snowflake`] guild: Optional[:class:`~discord.abc.Snowflake`]
The guild to add the command to. If not given or ``None`` then it The guild to add the command to. If not given or ``None`` then it
becomes a global command instead. becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
guilds: List[:class:`~discord.abc.Snowflake`] guilds: List[:class:`~discord.abc.Snowflake`]
The list of guilds to add the command to. This cannot be mixed The list of guilds to add the command to. This cannot be mixed
with the ``guild`` parameter. If no guilds are given at all with the ``guild`` parameter. If no guilds are given at all
then it becomes a global command instead. then it becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
override: :class:`bool` override: :class:`bool`
Whether to override a command with the same name. If ``False`` Whether to override a command with the same name. If ``False``
an exception is raised. Default is ``False``. an exception is raised. Default is ``False``.
@ -722,7 +756,7 @@ class CommandTree(Generic[ClientT]):
else: else:
guild_id = None if guild is None else guild.id guild_id = None if guild is None else guild.id
value = type.value value = type.value
for ((_, g, t), command) in self._context_menus.items(): for (_, g, t), command in self._context_menus.items():
if g == guild_id and t == value: if g == guild_id and t == value:
yield command yield command
@ -857,10 +891,24 @@ class CommandTree(Generic[ClientT]):
guild: Optional[:class:`~discord.abc.Snowflake`] guild: Optional[:class:`~discord.abc.Snowflake`]
The guild to add the command to. If not given or ``None`` then it The guild to add the command to. If not given or ``None`` then it
becomes a global command instead. becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
guilds: List[:class:`~discord.abc.Snowflake`] guilds: List[:class:`~discord.abc.Snowflake`]
The list of guilds to add the command to. This cannot be mixed The list of guilds to add the command to. This cannot be mixed
with the ``guild`` parameter. If no guilds are given at all with the ``guild`` parameter. If no guilds are given at all
then it becomes a global command instead. then it becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
auto_locale_strings: :class:`bool` auto_locale_strings: :class:`bool`
If this is set to ``True``, then all translatable strings will implicitly If this is set to ``True``, then all translatable strings will implicitly
be wrapped into :class:`locale_str` rather than :class:`str`. This could be wrapped into :class:`locale_str` rather than :class:`str`. This could
@ -940,10 +988,24 @@ class CommandTree(Generic[ClientT]):
guild: Optional[:class:`~discord.abc.Snowflake`] guild: Optional[:class:`~discord.abc.Snowflake`]
The guild to add the command to. If not given or ``None`` then it The guild to add the command to. If not given or ``None`` then it
becomes a global command instead. becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
guilds: List[:class:`~discord.abc.Snowflake`] guilds: List[:class:`~discord.abc.Snowflake`]
The list of guilds to add the command to. This cannot be mixed The list of guilds to add the command to. This cannot be mixed
with the ``guild`` parameter. If no guilds are given at all with the ``guild`` parameter. If no guilds are given at all
then it becomes a global command instead. then it becomes a global command instead.
.. note ::
Due to a Discord limitation, this keyword argument cannot be used in conjunction with
contexts (e.g. :func:`.app_commands.allowed_contexts`) or installation types
(e.g. :func:`.app_commands.allowed_installs`).
auto_locale_strings: :class:`bool` auto_locale_strings: :class:`bool`
If this is set to ``True``, then all translatable strings will implicitly If this is set to ``True``, then all translatable strings will implicitly
be wrapped into :class:`locale_str` rather than :class:`str`. This could be wrapped into :class:`locale_str` rather than :class:`str`. This could
@ -1058,9 +1120,9 @@ class CommandTree(Generic[ClientT]):
translator = self.translator translator = self.translator
if translator: if translator:
payload = [await command.get_translated_payload(translator) for command in commands] payload = [await command.get_translated_payload(self, translator) for command in commands]
else: else:
payload = [command.to_dict() for command in commands] payload = [command.to_dict(self) for command in commands]
try: try:
if guild is None: if guild is None:

6
discord/appinfo.py

@ -142,6 +142,10 @@ class AppInfo:
redirect_uris: List[:class:`str`] redirect_uris: List[:class:`str`]
A list of authentication redirect URIs. A list of authentication redirect URIs.
.. versionadded:: 2.4
approximate_guild_count: :class:`int`
The approximate count of the guilds the bot was added to.
.. versionadded:: 2.4 .. versionadded:: 2.4
""" """
@ -170,6 +174,7 @@ class AppInfo:
'role_connections_verification_url', 'role_connections_verification_url',
'interactions_endpoint_url', 'interactions_endpoint_url',
'redirect_uris', 'redirect_uris',
'approximate_guild_count',
) )
def __init__(self, state: ConnectionState, data: AppInfoPayload): def __init__(self, state: ConnectionState, data: AppInfoPayload):
@ -206,6 +211,7 @@ class AppInfo:
self.install_params: Optional[AppInstallParams] = AppInstallParams(params) if params else None self.install_params: Optional[AppInstallParams] = AppInstallParams(params) if params else None
self.interactions_endpoint_url: Optional[str] = data.get('interactions_endpoint_url') self.interactions_endpoint_url: Optional[str] = data.get('interactions_endpoint_url')
self.redirect_uris: List[str] = data.get('redirect_uris', []) self.redirect_uris: List[str] = data.get('redirect_uris', [])
self.approximate_guild_count: int = data.get('approximate_guild_count', 0)
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (

15
discord/asset.py

@ -246,6 +246,15 @@ class Asset(AssetMixin):
animated=animated, animated=animated,
) )
@classmethod
def _from_avatar_decoration(cls, state: _State, avatar_decoration: str) -> Self:
return cls(
state,
url=f'{cls.BASE}/avatar-decoration-presets/{avatar_decoration}.png?size=96',
key=avatar_decoration,
animated=True,
)
@classmethod @classmethod
def _from_icon(cls, state: _State, object_id: int, icon_hash: str, path: str) -> Self: def _from_icon(cls, state: _State, object_id: int, icon_hash: str, path: str) -> Self:
return cls( return cls(
@ -420,7 +429,7 @@ class Asset(AssetMixin):
url = url.with_query(url.raw_query_string) url = url.with_query(url.raw_query_string)
url = str(url) url = str(url)
return Asset(state=self._state, url=url, key=self._key, animated=self._animated) return self.__class__(state=self._state, url=url, key=self._key, animated=self._animated)
def with_size(self, size: int, /) -> Self: def with_size(self, size: int, /) -> Self:
"""Returns a new asset with the specified size. """Returns a new asset with the specified size.
@ -448,7 +457,7 @@ class Asset(AssetMixin):
raise ValueError('size must be a power of 2 between 16 and 4096') raise ValueError('size must be a power of 2 between 16 and 4096')
url = str(yarl.URL(self._url).with_query(size=size)) url = str(yarl.URL(self._url).with_query(size=size))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated) return self.__class__(state=self._state, url=url, key=self._key, animated=self._animated)
def with_format(self, format: ValidAssetFormatTypes, /) -> Self: def with_format(self, format: ValidAssetFormatTypes, /) -> Self:
"""Returns a new asset with the specified format. """Returns a new asset with the specified format.
@ -483,7 +492,7 @@ class Asset(AssetMixin):
url = yarl.URL(self._url) url = yarl.URL(self._url)
path, _ = os.path.splitext(url.path) path, _ = os.path.splitext(url.path)
url = str(url.with_path(f'{path}.{format}').with_query(url.raw_query_string)) url = str(url.with_path(f'{path}.{format}').with_query(url.raw_query_string))
return Asset(state=self._state, url=url, key=self._key, animated=self._animated) return self.__class__(state=self._state, url=url, key=self._key, animated=self._animated)
def with_static_format(self, format: ValidStaticFormatTypes, /) -> Self: def with_static_format(self, format: ValidStaticFormatTypes, /) -> Self:
"""Returns a new asset with the specified static format. """Returns a new asset with the specified static format.

4
discord/automod.py

@ -518,7 +518,7 @@ class AutoModRule:
payload['name'] = name payload['name'] = name
if event_type is not MISSING: if event_type is not MISSING:
payload['event_type'] = event_type payload['event_type'] = event_type.value
if trigger is not MISSING: if trigger is not MISSING:
trigger_metadata = trigger.to_metadata_dict() trigger_metadata = trigger.to_metadata_dict()
@ -541,7 +541,7 @@ class AutoModRule:
**payload, **payload,
) )
return AutoModRule(data=data, guild=self.guild, state=self._state) return self.__class__(data=data, guild=self.guild, state=self._state)
async def delete(self, *, reason: str = MISSING) -> None: async def delete(self, *, reason: str = MISSING) -> None:
"""|coro| """|coro|

30
discord/channel.py

@ -1370,6 +1370,7 @@ class VoiceChannel(VocalGuildChannel):
rtc_region: Optional[str] = ..., rtc_region: Optional[str] = ...,
video_quality_mode: VideoQualityMode = ..., video_quality_mode: VideoQualityMode = ...,
slowmode_delay: int = ..., slowmode_delay: int = ...,
status: Optional[str] = ...,
reason: Optional[str] = ..., reason: Optional[str] = ...,
) -> VoiceChannel: ) -> VoiceChannel:
... ...
@ -1429,6 +1430,11 @@ class VoiceChannel(VocalGuildChannel):
The camera video quality for the voice channel's participants. The camera video quality for the voice channel's participants.
.. versionadded:: 2.0 .. versionadded:: 2.0
status: Optional[:class:`str`]
The new voice channel status. It can be up to 500 characters.
Can be ``None`` to remove the status.
.. versionadded:: 2.4
Raises Raises
------ ------
@ -1696,6 +1702,7 @@ class StageChannel(VocalGuildChannel):
*, *,
name: str = ..., name: str = ...,
nsfw: bool = ..., nsfw: bool = ...,
bitrate: int = ...,
user_limit: int = ..., user_limit: int = ...,
position: int = ..., position: int = ...,
sync_permissions: int = ..., sync_permissions: int = ...,
@ -1732,6 +1739,8 @@ class StageChannel(VocalGuildChannel):
---------- ----------
name: :class:`str` name: :class:`str`
The new channel's name. The new channel's name.
bitrate: :class:`int`
The new channel's bitrate.
position: :class:`int` position: :class:`int`
The new channel's position. The new channel's position.
nsfw: :class:`bool` nsfw: :class:`bool`
@ -2910,22 +2919,21 @@ class DMChannel(discord.abc.Messageable, discord.abc.PrivateChannel, Hashable):
The user you are participating with in the direct message channel. The user you are participating with in the direct message channel.
If this channel is received through the gateway, the recipient information If this channel is received through the gateway, the recipient information
may not be always available. may not be always available.
recipients: List[:class:`User`]
The users you are participating with in the DM channel.
.. versionadded:: 2.4
me: :class:`ClientUser` me: :class:`ClientUser`
The user presenting yourself. The user presenting yourself.
id: :class:`int` id: :class:`int`
The direct message channel ID. The direct message channel ID.
""" """
__slots__ = ('id', 'recipient', 'me', '_state') __slots__ = ('id', 'recipients', 'me', '_state')
def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPayload): def __init__(self, *, me: ClientUser, state: ConnectionState, data: DMChannelPayload):
self._state: ConnectionState = state self._state: ConnectionState = state
self.recipient: Optional[User] = None self.recipients: List[User] = [state.store_user(u) for u in data.get('recipients', [])]
recipients = data.get('recipients')
if recipients is not None:
self.recipient = state.store_user(recipients[0])
self.me: ClientUser = me self.me: ClientUser = me
self.id: int = int(data['id']) self.id: int = int(data['id'])
@ -2945,11 +2953,17 @@ class DMChannel(discord.abc.Messageable, discord.abc.PrivateChannel, Hashable):
self = cls.__new__(cls) self = cls.__new__(cls)
self._state = state self._state = state
self.id = channel_id self.id = channel_id
self.recipient = None self.recipients = []
# state.user won't be None here # state.user won't be None here
self.me = state.user # type: ignore self.me = state.user # type: ignore
return self return self
@property
def recipient(self) -> Optional[User]:
if self.recipients:
return self.recipients[0]
return None
@property @property
def type(self) -> Literal[ChannelType.private]: def type(self) -> Literal[ChannelType.private]:
""":class:`ChannelType`: The channel's Discord type.""" """:class:`ChannelType`: The channel's Discord type."""

61
discord/client.py

@ -107,6 +107,7 @@ if TYPE_CHECKING:
RawThreadMembersUpdate, RawThreadMembersUpdate,
RawThreadUpdateEvent, RawThreadUpdateEvent,
RawTypingEvent, RawTypingEvent,
RawPollVoteActionEvent,
) )
from .reaction import Reaction from .reaction import Reaction
from .role import Role from .role import Role
@ -116,6 +117,7 @@ if TYPE_CHECKING:
from .ui.item import Item from .ui.item import Item
from .voice_client import VoiceProtocol from .voice_client import VoiceProtocol
from .audit_logs import AuditLogEntry from .audit_logs import AuditLogEntry
from .poll import PollAnswer
# fmt: off # fmt: off
@ -287,7 +289,7 @@ class Client:
self._enable_debug_events: bool = options.pop('enable_debug_events', False) self._enable_debug_events: bool = options.pop('enable_debug_events', False)
self._connection: ConnectionState[Self] = self._get_state(intents=intents, **options) self._connection: ConnectionState[Self] = self._get_state(intents=intents, **options)
self._connection.shard_count = self.shard_count self._connection.shard_count = self.shard_count
self._closed: bool = False self._closing_task: Optional[asyncio.Task[None]] = None
self._ready: asyncio.Event = MISSING self._ready: asyncio.Event = MISSING
self._application: Optional[AppInfo] = None self._application: Optional[AppInfo] = None
self._connection._get_websocket = self._get_websocket self._connection._get_websocket = self._get_websocket
@ -307,7 +309,10 @@ class Client:
exc_value: Optional[BaseException], exc_value: Optional[BaseException],
traceback: Optional[TracebackType], traceback: Optional[TracebackType],
) -> None: ) -> None:
if not self.is_closed(): # This avoids double-calling a user-provided .close()
if self._closing_task:
await self._closing_task
else:
await self.close() await self.close()
# internals # internals
@ -315,7 +320,7 @@ class Client:
def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket: def _get_websocket(self, guild_id: Optional[int] = None, *, shard_id: Optional[int] = None) -> DiscordWebSocket:
return self.ws return self.ws
def _get_state(self, **options: Any) -> ConnectionState: def _get_state(self, **options: Any) -> ConnectionState[Self]:
return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options) return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
def _handle_ready(self) -> None: def _handle_ready(self) -> None:
@ -726,22 +731,24 @@ class Client:
Closes the connection to Discord. Closes the connection to Discord.
""" """
if self._closed: if self._closing_task:
return return await self._closing_task
self._closed = True async def _close():
await self._connection.close()
await self._connection.close() if self.ws is not None and self.ws.open:
await self.ws.close(code=1000)
if self.ws is not None and self.ws.open: await self.http.close()
await self.ws.close(code=1000)
await self.http.close() if self._ready is not MISSING:
self._ready.clear()
if self._ready is not MISSING: self.loop = MISSING
self._ready.clear()
self.loop = MISSING self._closing_task = asyncio.create_task(_close())
await self._closing_task
def clear(self) -> None: def clear(self) -> None:
"""Clears the internal state of the bot. """Clears the internal state of the bot.
@ -750,7 +757,7 @@ class Client:
and :meth:`is_ready` both return ``False`` along with the bot's internal and :meth:`is_ready` both return ``False`` along with the bot's internal
cache cleared. cache cleared.
""" """
self._closed = False self._closing_task = None
self._ready.clear() self._ready.clear()
self._connection.clear() self._connection.clear()
self.http.clear() self.http.clear()
@ -870,7 +877,7 @@ class Client:
def is_closed(self) -> bool: def is_closed(self) -> bool:
""":class:`bool`: Indicates if the websocket connection is closed.""" """:class:`bool`: Indicates if the websocket connection is closed."""
return self._closed return self._closing_task is not None
@property @property
def activity(self) -> Optional[ActivityTypes]: def activity(self) -> Optional[ActivityTypes]:
@ -1810,6 +1817,30 @@ class Client:
) -> Tuple[Member, VoiceState, VoiceState]: ) -> Tuple[Member, VoiceState, VoiceState]:
... ...
# Polls
@overload
async def wait_for(
self,
event: Literal['poll_vote_add', 'poll_vote_remove'],
/,
*,
check: Optional[Callable[[Union[User, Member], PollAnswer], bool]] = None,
timeout: Optional[float] = None,
) -> Tuple[Union[User, Member], PollAnswer]:
...
@overload
async def wait_for(
self,
event: Literal['raw_poll_vote_add', 'raw_poll_vote_remove'],
/,
*,
check: Optional[Callable[[RawPollVoteActionEvent], bool]] = None,
timeout: Optional[float] = None,
) -> RawPollVoteActionEvent:
...
# Commands # Commands
@overload @overload

2
discord/colour.py

@ -175,7 +175,7 @@ class Colour:
return cls.from_rgb(*(int(x * 255) for x in rgb)) return cls.from_rgb(*(int(x * 255) for x in rgb))
@classmethod @classmethod
def from_str(cls, value: str) -> Self: def from_str(cls, value: str) -> Colour:
"""Constructs a :class:`Colour` from a string. """Constructs a :class:`Colour` from a string.
The following formats are accepted: The following formats are accepted:

21
discord/components.py

@ -170,6 +170,10 @@ class Button(Component):
The label of the button, if any. The label of the button, if any.
emoji: Optional[:class:`PartialEmoji`] emoji: Optional[:class:`PartialEmoji`]
The emoji of the button, if available. The emoji of the button, if available.
sku_id: Optional[:class:`int`]
The SKU ID this button sends you to, if available.
.. versionadded:: 2.4
""" """
__slots__: Tuple[str, ...] = ( __slots__: Tuple[str, ...] = (
@ -179,6 +183,7 @@ class Button(Component):
'disabled', 'disabled',
'label', 'label',
'emoji', 'emoji',
'sku_id',
) )
__repr_info__: ClassVar[Tuple[str, ...]] = __slots__ __repr_info__: ClassVar[Tuple[str, ...]] = __slots__
@ -195,6 +200,11 @@ class Button(Component):
except KeyError: except KeyError:
self.emoji = None self.emoji = None
try:
self.sku_id: Optional[int] = int(data['sku_id'])
except KeyError:
self.sku_id = None
@property @property
def type(self) -> Literal[ComponentType.button]: def type(self) -> Literal[ComponentType.button]:
""":class:`ComponentType`: The type of component.""" """:class:`ComponentType`: The type of component."""
@ -207,6 +217,9 @@ class Button(Component):
'disabled': self.disabled, 'disabled': self.disabled,
} }
if self.sku_id:
payload['sku_id'] = str(self.sku_id)
if self.label: if self.label:
payload['label'] = self.label payload['label'] = self.label
@ -318,8 +331,8 @@ class SelectOption:
Can only be up to 100 characters. Can only be up to 100 characters.
value: :class:`str` value: :class:`str`
The value of the option. This is not displayed to users. The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the If not provided when constructed then it defaults to the label.
label. Can only be up to 100 characters. Can only be up to 100 characters.
description: Optional[:class:`str`] description: Optional[:class:`str`]
An additional description of the option, if any. An additional description of the option, if any.
Can only be up to 100 characters. Can only be up to 100 characters.
@ -332,14 +345,12 @@ class SelectOption:
----------- -----------
label: :class:`str` label: :class:`str`
The label of the option. This is displayed to users. The label of the option. This is displayed to users.
Can only be up to 100 characters.
value: :class:`str` value: :class:`str`
The value of the option. This is not displayed to users. The value of the option. This is not displayed to users.
If not provided when constructed then it defaults to the If not provided when constructed then it defaults to the
label. Can only be up to 100 characters. label.
description: Optional[:class:`str`] description: Optional[:class:`str`]
An additional description of the option, if any. An additional description of the option, if any.
Can only be up to 100 characters.
default: :class:`bool` default: :class:`bool`
Whether this option is selected by default. Whether this option is selected by default.
""" """

47
discord/enums.py

@ -73,11 +73,9 @@ __all__ = (
'SKUType', 'SKUType',
'EntitlementType', 'EntitlementType',
'EntitlementOwnerType', 'EntitlementOwnerType',
'PollLayoutType',
) )
if TYPE_CHECKING:
from typing_extensions import Self
def _create_value_cls(name: str, comparable: bool): def _create_value_cls(name: str, comparable: bool):
# All the type ignores here are due to the type checker being unable to recognise # All the type ignores here are due to the type checker being unable to recognise
@ -104,7 +102,14 @@ class EnumMeta(type):
_enum_member_map_: ClassVar[Dict[str, Any]] _enum_member_map_: ClassVar[Dict[str, Any]]
_enum_value_map_: ClassVar[Dict[Any, Any]] _enum_value_map_: ClassVar[Dict[Any, Any]]
def __new__(cls, name: str, bases: Tuple[type, ...], attrs: Dict[str, Any], *, comparable: bool = False) -> Self: def __new__(
cls,
name: str,
bases: Tuple[type, ...],
attrs: Dict[str, Any],
*,
comparable: bool = False,
) -> EnumMeta:
value_mapping = {} value_mapping = {}
member_mapping = {} member_mapping = {}
member_names = [] member_names = []
@ -247,6 +252,10 @@ class MessageType(Enum):
stage_raise_hand = 30 stage_raise_hand = 30
stage_topic = 31 stage_topic = 31
guild_application_premium_subscription = 32 guild_application_premium_subscription = 32
guild_incident_alert_mode_enabled = 36
guild_incident_alert_mode_disabled = 37
guild_incident_report_raid = 38
guild_incident_report_false_alarm = 39
class SpeakingState(Enum): class SpeakingState(Enum):
@ -477,7 +486,7 @@ class AuditLogAction(Enum):
return 'thread' return 'thread'
elif v < 122: elif v < 122:
return 'integration_or_app_command' return 'integration_or_app_command'
elif v < 143: elif 139 < v < 143:
return 'auto_moderation' return 'auto_moderation'
elif v < 146: elif v < 146:
return 'user' return 'user'
@ -594,7 +603,7 @@ class InteractionResponseType(Enum):
message_update = 7 # for components message_update = 7 # for components
autocomplete_result = 8 autocomplete_result = 8
modal = 9 # for modals modal = 9 # for modals
premium_required = 10 # premium_required = 10 (deprecated)
class VideoQualityMode(Enum): class VideoQualityMode(Enum):
@ -626,6 +635,7 @@ class ButtonStyle(Enum):
success = 3 success = 3
danger = 4 danger = 4
link = 5 link = 5
premium = 6
# Aliases # Aliases
blurple = 1 blurple = 1
@ -686,6 +696,7 @@ class Locale(Enum):
italian = 'it' italian = 'it'
japanese = 'ja' japanese = 'ja'
korean = 'ko' korean = 'ko'
latin_american_spanish = 'es-419'
lithuanian = 'lt' lithuanian = 'lt'
norwegian = 'no' norwegian = 'no'
polish = 'pl' polish = 'pl'
@ -787,11 +798,20 @@ class SelectDefaultValueType(Enum):
class SKUType(Enum): class SKUType(Enum):
durable = 2
consumable = 3
subscription = 5 subscription = 5
subscription_group = 6 subscription_group = 6
class EntitlementType(Enum): class EntitlementType(Enum):
purchase = 1
premium_subscription = 2
developer_gift = 3
test_mode_purchase = 4
free_purchase = 5
user_gift = 6
premium_purchase = 7
application_subscription = 8 application_subscription = 8
@ -800,6 +820,21 @@ class EntitlementOwnerType(Enum):
user = 2 user = 2
class PollLayoutType(Enum):
default = 1
class InviteType(Enum):
guild = 0
group_dm = 1
friend = 2
class ReactionType(Enum):
normal = 0
burst = 1
def create_unknown_value(cls: Type[E], val: Any) -> E: def create_unknown_value(cls: Type[E], val: Any) -> E:
value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below value_cls = cls._enum_value_cls_ # type: ignore # This is narrowed below
name = f'unknown_{val}' name = f'unknown_{val}'

22
discord/ext/commands/bot.py

@ -166,6 +166,8 @@ class BotBase(GroupMixin[None]):
help_command: Optional[HelpCommand] = _default, help_command: Optional[HelpCommand] = _default,
tree_cls: Type[app_commands.CommandTree[Any]] = app_commands.CommandTree, tree_cls: Type[app_commands.CommandTree[Any]] = app_commands.CommandTree,
description: Optional[str] = None, description: Optional[str] = None,
allowed_contexts: app_commands.AppCommandContext = MISSING,
allowed_installs: app_commands.AppInstallationType = MISSING,
intents: discord.Intents, intents: discord.Intents,
**options: Any, **options: Any,
) -> None: ) -> None:
@ -174,6 +176,11 @@ class BotBase(GroupMixin[None]):
self.extra_events: Dict[str, List[CoroFunc]] = {} self.extra_events: Dict[str, List[CoroFunc]] = {}
# Self doesn't have the ClientT bound, but since this is a mixin it technically does # Self doesn't have the ClientT bound, but since this is a mixin it technically does
self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore self.__tree: app_commands.CommandTree[Self] = tree_cls(self) # type: ignore
if allowed_contexts is not MISSING:
self.__tree.allowed_contexts = allowed_contexts
if allowed_installs is not MISSING:
self.__tree.allowed_installs = allowed_installs
self.__cogs: Dict[str, Cog] = {} self.__cogs: Dict[str, Cog] = {}
self.__extensions: Dict[str, types.ModuleType] = {} self.__extensions: Dict[str, types.ModuleType] = {}
self._checks: List[UserCheck] = [] self._checks: List[UserCheck] = []
@ -521,7 +528,6 @@ class BotBase(GroupMixin[None]):
elif self.owner_ids: elif self.owner_ids:
return user.id in self.owner_ids return user.id in self.owner_ids
else: else:
app: discord.AppInfo = await self.application_info() # type: ignore app: discord.AppInfo = await self.application_info() # type: ignore
if app.team: if app.team:
self.owner_ids = ids = { self.owner_ids = ids = {
@ -1489,6 +1495,20 @@ class Bot(BotBase, discord.Client):
The type of application command tree to use. Defaults to :class:`~discord.app_commands.CommandTree`. The type of application command tree to use. Defaults to :class:`~discord.app_commands.CommandTree`.
.. versionadded:: 2.0 .. versionadded:: 2.0
allowed_contexts: :class:`~discord.app_commands.AppCommandContext`
The default allowed contexts that applies to all application commands
in the application command tree.
Note that you can override this on a per command basis.
.. versionadded:: 2.4
allowed_installs: :class:`~discord.app_commands.AppInstallationType`
The default allowed install locations that apply to all application commands
in the application command tree.
Note that you can override this on a per command basis.
.. versionadded:: 2.4
""" """
pass pass

6
discord/ext/commands/cog.py

@ -169,7 +169,7 @@ class CogMeta(type):
__cog_app_commands__: List[Union[app_commands.Group, app_commands.Command[Any, ..., Any]]] __cog_app_commands__: List[Union[app_commands.Group, app_commands.Command[Any, ..., Any]]]
__cog_listeners__: List[Tuple[str, str]] __cog_listeners__: List[Tuple[str, str]]
def __new__(cls, *args: Any, **kwargs: Any) -> Self: def __new__(cls, *args: Any, **kwargs: Any) -> CogMeta:
name, bases, attrs = args name, bases, attrs = args
if any(issubclass(base, app_commands.Group) for base in bases): if any(issubclass(base, app_commands.Group) for base in bases):
raise TypeError( raise TypeError(
@ -318,6 +318,8 @@ class Cog(metaclass=CogMeta):
parent=None, parent=None,
guild_ids=getattr(cls, '__discord_app_commands_default_guilds__', None), guild_ids=getattr(cls, '__discord_app_commands_default_guilds__', None),
guild_only=getattr(cls, '__discord_app_commands_guild_only__', False), guild_only=getattr(cls, '__discord_app_commands_guild_only__', False),
allowed_contexts=getattr(cls, '__discord_app_commands_contexts__', None),
allowed_installs=getattr(cls, '__discord_app_commands_installation_types__', None),
default_permissions=getattr(cls, '__discord_app_commands_default_permissions__', None), default_permissions=getattr(cls, '__discord_app_commands_default_permissions__', None),
extras=cls.__cog_group_extras__, extras=cls.__cog_group_extras__,
) )
@ -366,7 +368,7 @@ class Cog(metaclass=CogMeta):
child.wrapped = lookup[child.qualified_name] # type: ignore child.wrapped = lookup[child.qualified_name] # type: ignore
if self.__cog_app_commands_group__: if self.__cog_app_commands_group__:
children.append(app_command) # type: ignore # Somehow it thinks it can be None here children.append(app_command)
if Cog._get_overridden_method(self.cog_app_command_error) is not None: if Cog._get_overridden_method(self.cog_app_command_error) is not None:
error_handler = self.cog_app_command_error error_handler = self.cog_app_command_error

21
discord/ext/commands/context.py

@ -50,6 +50,7 @@ if TYPE_CHECKING:
from discord.message import MessageReference, PartialMessage from discord.message import MessageReference, PartialMessage
from discord.ui import View from discord.ui import View
from discord.types.interactions import ApplicationCommandInteractionData from discord.types.interactions import ApplicationCommandInteractionData
from discord.poll import Poll
from .cog import Cog from .cog import Cog
from .core import Command from .core import Command
@ -472,7 +473,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
.. versionadded:: 2.0 .. versionadded:: 2.0
""" """
if self.channel.type is ChannelType.private: if self.interaction is None and self.channel.type is ChannelType.private:
return Permissions._dm_permissions() return Permissions._dm_permissions()
if not self.interaction: if not self.interaction:
# channel and author will always match relevant types here # channel and author will always match relevant types here
@ -506,7 +507,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
.. versionadded:: 2.0 .. versionadded:: 2.0
""" """
channel = self.channel channel = self.channel
if channel.type == ChannelType.private: if self.interaction is None and channel.type == ChannelType.private:
return Permissions._dm_permissions() return Permissions._dm_permissions()
if not self.interaction: if not self.interaction:
# channel and me will always match relevant types here # channel and me will always match relevant types here
@ -641,6 +642,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -662,6 +664,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -683,6 +686,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -704,6 +708,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -826,6 +831,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -847,6 +853,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -868,6 +875,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -889,6 +897,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
ephemeral: bool = ..., ephemeral: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -911,6 +920,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
suppress_embeds: bool = False, suppress_embeds: bool = False,
ephemeral: bool = False, ephemeral: bool = False,
silent: bool = False, silent: bool = False,
poll: Poll = MISSING,
) -> Message: ) -> Message:
"""|coro| """|coro|
@ -1000,6 +1010,11 @@ class Context(discord.abc.Messageable, Generic[BotT]):
.. versionadded:: 2.2 .. versionadded:: 2.2
poll: :class:`~discord.Poll`
The poll to send with this message.
.. versionadded:: 2.4
Raises Raises
-------- --------
~discord.HTTPException ~discord.HTTPException
@ -1037,6 +1052,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
view=view, view=view,
suppress_embeds=suppress_embeds, suppress_embeds=suppress_embeds,
silent=silent, silent=silent,
poll=poll,
) # type: ignore # The overloads don't support Optional but the implementation does ) # type: ignore # The overloads don't support Optional but the implementation does
# Convert the kwargs from None to MISSING to appease the remaining implementations # Convert the kwargs from None to MISSING to appease the remaining implementations
@ -1052,6 +1068,7 @@ class Context(discord.abc.Messageable, Generic[BotT]):
'suppress_embeds': suppress_embeds, 'suppress_embeds': suppress_embeds,
'ephemeral': ephemeral, 'ephemeral': ephemeral,
'silent': silent, 'silent': silent,
'poll': poll,
} }
if self.interaction.response.is_done(): if self.interaction.response.is_done():

65
discord/ext/commands/converter.py

@ -438,19 +438,36 @@ class GuildChannelConverter(IDConverter[discord.abc.GuildChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name. 3. Lookup by channel URL.
4. Lookup by name.
.. versionadded:: 2.0 .. versionadded:: 2.0
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.abc.GuildChannel: async def convert(self, ctx: Context[BotT], argument: str) -> discord.abc.GuildChannel:
return self._resolve_channel(ctx, argument, 'channels', discord.abc.GuildChannel) return self._resolve_channel(ctx, argument, 'channels', discord.abc.GuildChannel)
@staticmethod
def _parse_from_url(argument: str) -> Optional[re.Match[str]]:
link_regex = re.compile(
r'https?://(?:(?:ptb|canary|www)\.)?discord(?:app)?\.com/channels/'
r'(?:[0-9]{15,20}|@me)'
r'/([0-9]{15,20})(?:/(?:[0-9]{15,20})/?)?$'
)
return link_regex.match(argument)
@staticmethod @staticmethod
def _resolve_channel(ctx: Context[BotT], argument: str, attribute: str, type: Type[CT]) -> CT: def _resolve_channel(ctx: Context[BotT], argument: str, attribute: str, type: Type[CT]) -> CT:
bot = ctx.bot bot = ctx.bot
match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) match = (
IDConverter._get_id_match(argument)
or re.match(r'<#([0-9]{15,20})>$', argument)
or GuildChannelConverter._parse_from_url(argument)
)
result = None result = None
guild = ctx.guild guild = ctx.guild
@ -480,7 +497,11 @@ class GuildChannelConverter(IDConverter[discord.abc.GuildChannel]):
@staticmethod @staticmethod
def _resolve_thread(ctx: Context[BotT], argument: str, attribute: str, type: Type[TT]) -> TT: def _resolve_thread(ctx: Context[BotT], argument: str, attribute: str, type: Type[TT]) -> TT:
match = IDConverter._get_id_match(argument) or re.match(r'<#([0-9]{15,20})>$', argument) match = (
IDConverter._get_id_match(argument)
or re.match(r'<#([0-9]{15,20})>$', argument)
or GuildChannelConverter._parse_from_url(argument)
)
result = None result = None
guild = ctx.guild guild = ctx.guild
@ -510,10 +531,14 @@ class TextChannelConverter(IDConverter[discord.TextChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name 3. Lookup by channel URL.
4. Lookup by name
.. versionchanged:: 1.5 .. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.TextChannel: async def convert(self, ctx: Context[BotT], argument: str) -> discord.TextChannel:
@ -530,10 +555,14 @@ class VoiceChannelConverter(IDConverter[discord.VoiceChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name 3. Lookup by channel URL.
4. Lookup by name
.. versionchanged:: 1.5 .. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.VoiceChannel: async def convert(self, ctx: Context[BotT], argument: str) -> discord.VoiceChannel:
@ -552,7 +581,11 @@ class StageChannelConverter(IDConverter[discord.StageChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name 3. Lookup by channel URL.
4. Lookup by name
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.StageChannel: async def convert(self, ctx: Context[BotT], argument: str) -> discord.StageChannel:
@ -569,7 +602,11 @@ class CategoryChannelConverter(IDConverter[discord.CategoryChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name 3. Lookup by channel URL.
4. Lookup by name
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
.. versionchanged:: 1.5 .. versionchanged:: 1.5
Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument` Raise :exc:`.ChannelNotFound` instead of generic :exc:`.BadArgument`
@ -588,9 +625,13 @@ class ThreadConverter(IDConverter[discord.Thread]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name. 3. Lookup by channel URL.
4. Lookup by name.
.. versionadded: 2.0 .. versionadded: 2.0
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.Thread: async def convert(self, ctx: Context[BotT], argument: str) -> discord.Thread:
@ -607,9 +648,13 @@ class ForumChannelConverter(IDConverter[discord.ForumChannel]):
1. Lookup by ID. 1. Lookup by ID.
2. Lookup by mention. 2. Lookup by mention.
3. Lookup by name 3. Lookup by channel URL.
4. Lookup by name
.. versionadded:: 2.0 .. versionadded:: 2.0
.. versionchanged:: 2.4
Add lookup by channel URL, accessed via "Copy Link" in the Discord client within channels.
""" """
async def convert(self, ctx: Context[BotT], argument: str) -> discord.ForumChannel: async def convert(self, ctx: Context[BotT], argument: str) -> discord.ForumChannel:
@ -1185,7 +1230,7 @@ def _convert_to_bool(argument: str) -> bool:
raise BadBoolArgument(lowered) raise BadBoolArgument(lowered)
_GenericAlias = type(List[T]) _GenericAlias = type(List[T]) # type: ignore
def is_generic_type(tp: Any, *, _GenericAlias: type = _GenericAlias) -> bool: def is_generic_type(tp: Any, *, _GenericAlias: type = _GenericAlias) -> bool:

6
discord/ext/commands/core.py

@ -461,7 +461,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
# bandaid for the fact that sometimes parent can be the bot instance # bandaid for the fact that sometimes parent can be the bot instance
parent: Optional[GroupMixin[Any]] = kwargs.get('parent') parent: Optional[GroupMixin[Any]] = kwargs.get('parent')
self.parent: Optional[GroupMixin[Any]] = parent if isinstance(parent, _BaseCommand) else None # type: ignore # Does not recognise mixin usage self.parent: Optional[GroupMixin[Any]] = parent if isinstance(parent, _BaseCommand) else None
self._before_invoke: Optional[Hook] = None self._before_invoke: Optional[Hook] = None
try: try:
@ -776,7 +776,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
command = self command = self
# command.parent is type-hinted as GroupMixin some attributes are resolved via MRO # command.parent is type-hinted as GroupMixin some attributes are resolved via MRO
while command.parent is not None: # type: ignore while command.parent is not None: # type: ignore
command = command.parent command = command.parent # type: ignore
entries.append(command.name) # type: ignore entries.append(command.name) # type: ignore
return ' '.join(reversed(entries)) return ' '.join(reversed(entries))
@ -794,7 +794,7 @@ class Command(_BaseCommand, Generic[CogT, P, T]):
entries = [] entries = []
command = self command = self
while command.parent is not None: # type: ignore while command.parent is not None: # type: ignore
command = command.parent command = command.parent # type: ignore
entries.append(command) entries.append(command)
return entries return entries

39
discord/ext/commands/flags.py

@ -79,6 +79,10 @@ class Flag:
description: :class:`str` description: :class:`str`
The description of the flag. Shown for hybrid commands when they're The description of the flag. Shown for hybrid commands when they're
used as application commands. used as application commands.
positional: :class:`bool`
Whether the flag is positional or not. There can only be one positional flag.
.. versionadded:: 2.4
""" """
name: str = MISSING name: str = MISSING
@ -89,6 +93,7 @@ class Flag:
max_args: int = MISSING max_args: int = MISSING
override: bool = MISSING override: bool = MISSING
description: str = MISSING description: str = MISSING
positional: bool = MISSING
cast_to_dict: bool = False cast_to_dict: bool = False
@property @property
@ -109,6 +114,7 @@ def flag(
override: bool = MISSING, override: bool = MISSING,
converter: Any = MISSING, converter: Any = MISSING,
description: str = MISSING, description: str = MISSING,
positional: bool = MISSING,
) -> Any: ) -> Any:
"""Override default functionality and parameters of the underlying :class:`FlagConverter` """Override default functionality and parameters of the underlying :class:`FlagConverter`
class attributes. class attributes.
@ -136,6 +142,10 @@ def flag(
description: :class:`str` description: :class:`str`
The description of the flag. Shown for hybrid commands when they're The description of the flag. Shown for hybrid commands when they're
used as application commands. used as application commands.
positional: :class:`bool`
Whether the flag is positional or not. There can only be one positional flag.
.. versionadded:: 2.4
""" """
return Flag( return Flag(
name=name, name=name,
@ -145,6 +155,7 @@ def flag(
override=override, override=override,
annotation=converter, annotation=converter,
description=description, description=description,
positional=positional,
) )
@ -171,6 +182,7 @@ def get_flags(namespace: Dict[str, Any], globals: Dict[str, Any], locals: Dict[s
flags: Dict[str, Flag] = {} flags: Dict[str, Flag] = {}
cache: Dict[str, Any] = {} cache: Dict[str, Any] = {}
names: Set[str] = set() names: Set[str] = set()
positional: Optional[Flag] = None
for name, annotation in annotations.items(): for name, annotation in annotations.items():
flag = namespace.pop(name, MISSING) flag = namespace.pop(name, MISSING)
if isinstance(flag, Flag): if isinstance(flag, Flag):
@ -183,6 +195,11 @@ def get_flags(namespace: Dict[str, Any], globals: Dict[str, Any], locals: Dict[s
if flag.name is MISSING: if flag.name is MISSING:
flag.name = name flag.name = name
if flag.positional:
if positional is not None:
raise TypeError(f"{flag.name!r} positional flag conflicts with {positional.name!r} flag.")
positional = flag
annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache) annotation = flag.annotation = resolve_annotation(flag.annotation, globals, locals, cache)
if flag.default is MISSING and hasattr(annotation, '__commands_is_flag__') and annotation._can_be_constructible(): if flag.default is MISSING and hasattr(annotation, '__commands_is_flag__') and annotation._can_be_constructible():
@ -270,6 +287,7 @@ class FlagsMeta(type):
__commands_flag_case_insensitive__: bool __commands_flag_case_insensitive__: bool
__commands_flag_delimiter__: str __commands_flag_delimiter__: str
__commands_flag_prefix__: str __commands_flag_prefix__: str
__commands_flag_positional__: Optional[Flag]
def __new__( def __new__(
cls, cls,
@ -280,7 +298,7 @@ class FlagsMeta(type):
case_insensitive: bool = MISSING, case_insensitive: bool = MISSING,
delimiter: str = MISSING, delimiter: str = MISSING,
prefix: str = MISSING, prefix: str = MISSING,
) -> Self: ) -> FlagsMeta:
attrs['__commands_is_flag__'] = True attrs['__commands_is_flag__'] = True
try: try:
@ -324,9 +342,13 @@ class FlagsMeta(type):
delimiter = attrs.setdefault('__commands_flag_delimiter__', ':') delimiter = attrs.setdefault('__commands_flag_delimiter__', ':')
prefix = attrs.setdefault('__commands_flag_prefix__', '') prefix = attrs.setdefault('__commands_flag_prefix__', '')
positional: Optional[Flag] = None
for flag_name, flag in get_flags(attrs, global_ns, local_ns).items(): for flag_name, flag in get_flags(attrs, global_ns, local_ns).items():
flags[flag_name] = flag flags[flag_name] = flag
aliases.update({alias_name: flag_name for alias_name in flag.aliases}) aliases.update({alias_name: flag_name for alias_name in flag.aliases})
if flag.positional:
positional = flag
attrs['__commands_flag_positional__'] = positional
forbidden = set(delimiter).union(prefix) forbidden = set(delimiter).union(prefix)
for flag_name in flags: for flag_name in flags:
@ -500,10 +522,25 @@ class FlagConverter(metaclass=FlagsMeta):
result: Dict[str, List[str]] = {} result: Dict[str, List[str]] = {}
flags = cls.__commands_flags__ flags = cls.__commands_flags__
aliases = cls.__commands_flag_aliases__ aliases = cls.__commands_flag_aliases__
positional_flag = cls.__commands_flag_positional__
last_position = 0 last_position = 0
last_flag: Optional[Flag] = None last_flag: Optional[Flag] = None
case_insensitive = cls.__commands_flag_case_insensitive__ case_insensitive = cls.__commands_flag_case_insensitive__
if positional_flag is not None:
match = cls.__commands_flag_regex__.search(argument)
if match is not None:
begin, end = match.span(0)
value = argument[:begin].strip()
else:
value = argument.strip()
last_position = len(argument)
if value:
name = positional_flag.name.casefold() if case_insensitive else positional_flag.name
result[name] = [value]
for match in cls.__commands_flag_regex__.finditer(argument): for match in cls.__commands_flag_regex__.finditer(argument):
begin, end = match.span(0) begin, end = match.span(0)
key = match.group('flag') key = match.group('flag')

10
discord/ext/commands/help.py

@ -297,6 +297,11 @@ class _HelpCommandImpl(Command):
# Revert `on_error` to use the original one in case of race conditions # Revert `on_error` to use the original one in case of race conditions
self.on_error = self._injected.on_help_command_error self.on_error = self._injected.on_help_command_error
def update(self, **kwargs: Any) -> None:
cog = self.cog
self.__init__(self._original, **dict(self.__original_kwargs__, **kwargs))
self.cog = cog
class HelpCommand: class HelpCommand:
r"""The base implementation for help command formatting. r"""The base implementation for help command formatting.
@ -377,9 +382,8 @@ class HelpCommand:
return obj return obj
def _add_to_bot(self, bot: BotBase) -> None: def _add_to_bot(self, bot: BotBase) -> None:
command = _HelpCommandImpl(self, **self.command_attrs) self._command_impl.update(**self.command_attrs)
bot.add_command(command) bot.add_command(self._command_impl)
self._command_impl = command
def _remove_from_bot(self, bot: BotBase) -> None: def _remove_from_bot(self, bot: BotBase) -> None:
bot.remove_command(self._command_impl.name) bot.remove_command(self._command_impl.name)

6
discord/ext/commands/hybrid.py

@ -653,6 +653,8 @@ class HybridGroup(Group[CogT, P, T]):
guild_only = getattr(self.callback, '__discord_app_commands_guild_only__', False) guild_only = getattr(self.callback, '__discord_app_commands_guild_only__', False)
default_permissions = getattr(self.callback, '__discord_app_commands_default_permissions__', None) default_permissions = getattr(self.callback, '__discord_app_commands_default_permissions__', None)
nsfw = getattr(self.callback, '__discord_app_commands_is_nsfw__', False) nsfw = getattr(self.callback, '__discord_app_commands_is_nsfw__', False)
contexts = getattr(self.callback, '__discord_app_commands_contexts__', MISSING)
installs = getattr(self.callback, '__discord_app_commands_installation_types__', MISSING)
self.app_command = app_commands.Group( self.app_command = app_commands.Group(
name=self._locale_name or self.name, name=self._locale_name or self.name,
description=self._locale_description or self.description or self.short_doc or '', description=self._locale_description or self.description or self.short_doc or '',
@ -660,6 +662,8 @@ class HybridGroup(Group[CogT, P, T]):
guild_only=guild_only, guild_only=guild_only,
default_permissions=default_permissions, default_permissions=default_permissions,
nsfw=nsfw, nsfw=nsfw,
allowed_installs=installs,
allowed_contexts=contexts,
) )
# This prevents the group from re-adding the command at __init__ # This prevents the group from re-adding the command at __init__
@ -902,7 +906,7 @@ def hybrid_command(
def decorator(func: CommandCallback[CogT, ContextT, P, T]) -> HybridCommand[CogT, P, T]: def decorator(func: CommandCallback[CogT, ContextT, P, T]) -> HybridCommand[CogT, P, T]:
if isinstance(func, Command): if isinstance(func, Command):
raise TypeError('Callback is already a command.') raise TypeError('Callback is already a command.')
return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) # type: ignore # ??? return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs)
return decorator return decorator

2
discord/file.py

@ -111,7 +111,7 @@ class File:
else: else:
filename = getattr(fp, 'name', 'untitled') filename = getattr(fp, 'name', 'untitled')
self._filename, filename_spoiler = _strip_spoiler(filename) self._filename, filename_spoiler = _strip_spoiler(filename) # type: ignore # pyright doesn't understand the above getattr
if spoiler is MISSING: if spoiler is MISSING:
spoiler = filename_spoiler spoiler = filename_spoiler

227
discord/flags.py

@ -58,8 +58,10 @@ __all__ = (
'ChannelFlags', 'ChannelFlags',
'AutoModPresets', 'AutoModPresets',
'MemberFlags', 'MemberFlags',
'AppCommandContext',
'AttachmentFlags', 'AttachmentFlags',
'RoleFlags', 'RoleFlags',
'AppInstallationType',
'SKUFlags', 'SKUFlags',
) )
@ -1255,6 +1257,57 @@ class Intents(BaseFlags):
""" """
return 1 << 21 return 1 << 21
@alias_flag_value
def polls(self):
""":class:`bool`: Whether guild and direct messages poll related events are enabled.
This is a shortcut to set or get both :attr:`guild_polls` and :attr:`dm_polls`.
This corresponds to the following events:
- :func:`on_poll_vote_add` (both guilds and DMs)
- :func:`on_poll_vote_remove` (both guilds and DMs)
- :func:`on_raw_poll_vote_add` (both guilds and DMs)
- :func:`on_raw_poll_vote_remove` (both guilds and DMs)
.. versionadded:: 2.4
"""
return (1 << 24) | (1 << 25)
@flag_value
def guild_polls(self):
""":class:`bool`: Whether guild poll related events are enabled.
See also :attr:`dm_polls` and :attr:`polls`.
This corresponds to the following events:
- :func:`on_poll_vote_add` (only for guilds)
- :func:`on_poll_vote_remove` (only for guilds)
- :func:`on_raw_poll_vote_add` (only for guilds)
- :func:`on_raw_poll_vote_remove` (only for guilds)
.. versionadded:: 2.4
"""
return 1 << 24
@flag_value
def dm_polls(self):
""":class:`bool`: Whether direct messages poll related events are enabled.
See also :attr:`guild_polls` and :attr:`polls`.
This corresponds to the following events:
- :func:`on_poll_vote_add` (only for DMs)
- :func:`on_poll_vote_remove` (only for DMs)
- :func:`on_raw_poll_vote_add` (only for DMs)
- :func:`on_raw_poll_vote_remove` (only for DMs)
.. versionadded:: 2.4
"""
return 1 << 25
@fill_with_flags() @fill_with_flags()
class MemberCacheFlags(BaseFlags): class MemberCacheFlags(BaseFlags):
@ -1660,8 +1713,24 @@ class ArrayFlags(BaseFlags):
self.value = reduce(or_, map((1).__lshift__, value), 0) >> 1 self.value = reduce(or_, map((1).__lshift__, value), 0) >> 1
return self return self
def to_array(self) -> List[int]: def to_array(self, *, offset: int = 0) -> List[int]:
return [i + 1 for i in range(self.value.bit_length()) if self.value & (1 << i)] return [i + offset for i in range(self.value.bit_length()) if self.value & (1 << i)]
@classmethod
def all(cls: Type[Self]) -> Self:
"""A factory method that creates an instance of ArrayFlags with everything enabled."""
bits = max(cls.VALID_FLAGS.values()).bit_length()
value = (1 << bits) - 1
self = cls.__new__(cls)
self.value = value
return self
@classmethod
def none(cls: Type[Self]) -> Self:
"""A factory method that creates an instance of ArrayFlags with everything disabled."""
self = cls.__new__(cls)
self.value = self.DEFAULT_VALUE
return self
@fill_with_flags() @fill_with_flags()
@ -1728,6 +1797,9 @@ class AutoModPresets(ArrayFlags):
rather than using this raw value. rather than using this raw value.
""" """
def to_array(self) -> List[int]:
return super().to_array(offset=1)
@flag_value @flag_value
def profanity(self): def profanity(self):
""":class:`bool`: Whether to use the preset profanity filter.""" """:class:`bool`: Whether to use the preset profanity filter."""
@ -1743,21 +1815,144 @@ class AutoModPresets(ArrayFlags):
""":class:`bool`: Whether to use the preset slurs filter.""" """:class:`bool`: Whether to use the preset slurs filter."""
return 1 << 2 return 1 << 2
@classmethod
def all(cls: Type[Self]) -> Self:
"""A factory method that creates a :class:`AutoModPresets` with everything enabled."""
bits = max(cls.VALID_FLAGS.values()).bit_length()
value = (1 << bits) - 1
self = cls.__new__(cls)
self.value = value
return self
@classmethod @fill_with_flags()
def none(cls: Type[Self]) -> Self: class AppCommandContext(ArrayFlags):
"""A factory method that creates a :class:`AutoModPresets` with everything disabled.""" r"""Wraps up the Discord :class:`~discord.app_commands.Command` execution context.
self = cls.__new__(cls)
self.value = self.DEFAULT_VALUE .. versionadded:: 2.4
return self
.. container:: operations
.. describe:: x == y
Checks if two AppCommandContext flags are equal.
.. describe:: x != y
Checks if two AppCommandContext flags are not equal.
.. describe:: x | y, x |= y
Returns an AppCommandContext instance with all enabled flags from
both x and y.
.. describe:: x & y, x &= y
Returns an AppCommandContext instance with only flags enabled on
both x and y.
.. describe:: x ^ y, x ^= y
Returns an AppCommandContext instance with only flags enabled on
only one of x or y, not on both.
.. describe:: ~x
Returns an AppCommandContext instance with all flags inverted from x
.. describe:: hash(x)
Return the flag's hash.
.. describe:: iter(x)
Returns an iterator of ``(name, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
.. describe:: bool(b)
Returns whether any flag is set to ``True``.
Attributes
-----------
value: :class:`int`
The raw value. You should query flags via the properties
rather than using this raw value.
"""
DEFAULT_VALUE = 3
@flag_value
def guild(self):
""":class:`bool`: Whether the context allows usage in a guild."""
return 1 << 0
@flag_value
def dm_channel(self):
""":class:`bool`: Whether the context allows usage in a DM channel."""
return 1 << 1
@flag_value
def private_channel(self):
""":class:`bool`: Whether the context allows usage in a DM or a GDM channel."""
return 1 << 2
@fill_with_flags()
class AppInstallationType(ArrayFlags):
r"""Represents the installation location of an application command.
.. versionadded:: 2.4
.. container:: operations
.. describe:: x == y
Checks if two AppInstallationType flags are equal.
.. describe:: x != y
Checks if two AppInstallationType flags are not equal.
.. describe:: x | y, x |= y
Returns an AppInstallationType instance with all enabled flags from
both x and y.
.. describe:: x & y, x &= y
Returns an AppInstallationType instance with only flags enabled on
both x and y.
.. describe:: x ^ y, x ^= y
Returns an AppInstallationType instance with only flags enabled on
only one of x or y, not on both.
.. describe:: ~x
Returns an AppInstallationType instance with all flags inverted from x
.. describe:: hash(x)
Return the flag's hash.
.. describe:: iter(x)
Returns an iterator of ``(name, value)`` pairs. This allows it
to be, for example, constructed as a dict or a list of pairs.
Note that aliases are not shown.
.. describe:: bool(b)
Returns whether any flag is set to ``True``.
Attributes
-----------
value: :class:`int`
The raw value. You should query flags via the properties
rather than using this raw value.
"""
@flag_value
def guild(self):
""":class:`bool`: Whether the integration is a guild install."""
return 1 << 0
@flag_value
def user(self):
""":class:`bool`: Whether the integration is a user install."""
return 1 << 1
@fill_with_flags() @fill_with_flags()

2
discord/gateway.py

@ -827,7 +827,7 @@ class DiscordVoiceWebSocket:
self.loop: asyncio.AbstractEventLoop = loop self.loop: asyncio.AbstractEventLoop = loop
self._keep_alive: Optional[VoiceKeepAliveHandler] = None self._keep_alive: Optional[VoiceKeepAliveHandler] = None
self._close_code: Optional[int] = None self._close_code: Optional[int] = None
self.secret_key: Optional[str] = None self.secret_key: Optional[List[int]] = None
if hook: if hook:
self._hook = hook self._hook = hook

185
discord/guild.py

@ -34,6 +34,7 @@ from typing import (
Collection, Collection,
Coroutine, Coroutine,
Dict, Dict,
Iterable,
List, List,
Mapping, Mapping,
NamedTuple, NamedTuple,
@ -109,6 +110,7 @@ if TYPE_CHECKING:
Guild as GuildPayload, Guild as GuildPayload,
RolePositionUpdate as RolePositionUpdatePayload, RolePositionUpdate as RolePositionUpdatePayload,
GuildFeature, GuildFeature,
IncidentData,
) )
from .types.threads import ( from .types.threads import (
Thread as ThreadPayload, Thread as ThreadPayload,
@ -145,6 +147,11 @@ class BanEntry(NamedTuple):
user: User user: User
class BulkBanResult(NamedTuple):
banned: List[Object]
failed: List[Object]
class _GuildLimit(NamedTuple): class _GuildLimit(NamedTuple):
emoji: int emoji: int
stickers: int stickers: int
@ -320,6 +327,7 @@ class Guild(Hashable):
'premium_progress_bar_enabled', 'premium_progress_bar_enabled',
'_safety_alerts_channel_id', '_safety_alerts_channel_id',
'max_stage_video_users', 'max_stage_video_users',
'_incidents_data',
) )
_PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = { _PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = {
@ -370,10 +378,11 @@ class Guild(Hashable):
def _clear_threads(self) -> None: def _clear_threads(self) -> None:
self._threads.clear() self._threads.clear()
def _remove_threads_by_channel(self, channel_id: int) -> None: def _remove_threads_by_channel(self, channel_id: int) -> List[Thread]:
to_remove = [k for k, t in self._threads.items() if t.parent_id == channel_id] to_remove = [t for t in self._threads.values() if t.parent_id == channel_id]
for k in to_remove: for thread in to_remove:
del self._threads[k] del self._threads[thread.id]
return to_remove
def _filter_threads(self, channel_ids: Set[int]) -> Dict[int, Thread]: def _filter_threads(self, channel_ids: Set[int]) -> Dict[int, Thread]:
to_remove: Dict[int, Thread] = {k: t for k, t in self._threads.items() if t.parent_id in channel_ids} to_remove: Dict[int, Thread] = {k: t for k, t in self._threads.items() if t.parent_id in channel_ids}
@ -423,31 +432,18 @@ class Guild(Hashable):
return member, before, after return member, before, after
def _add_role(self, role: Role, /) -> None: def _add_role(self, role: Role, /) -> None:
# roles get added to the bottom (position 1, pos 0 is @everyone)
# so since self.roles has the @everyone role, we can't increment
# its position because it's stuck at position 0. Luckily x += False
# is equivalent to adding 0. So we cast the position to a bool and
# increment it.
for r in self._roles.values():
r.position += not r.is_default()
self._roles[role.id] = role self._roles[role.id] = role
def _remove_role(self, role_id: int, /) -> Role: def _remove_role(self, role_id: int, /) -> Role:
# this raises KeyError if it fails.. # this raises KeyError if it fails..
role = self._roles.pop(role_id) return self._roles.pop(role_id)
# since it didn't, we can change the positions now
# basically the same as above except we only decrement
# the position if we're above the role we deleted.
for r in self._roles.values():
r.position -= r.position > role.position
return role
@classmethod @classmethod
def _create_unavailable(cls, *, state: ConnectionState, guild_id: int) -> Guild: def _create_unavailable(cls, *, state: ConnectionState, guild_id: int, data: Optional[Dict[str, Any]]) -> Guild:
return cls(state=state, data={'id': guild_id, 'unavailable': True}) # type: ignore if data is None:
data = {'unavailable': True}
data.update(id=guild_id)
return cls(state=state, data=data) # type: ignore
def _from_data(self, guild: GuildPayload) -> None: def _from_data(self, guild: GuildPayload) -> None:
try: try:
@ -509,6 +505,7 @@ class Guild(Hashable):
self.owner_id: Optional[int] = utils._get_as_snowflake(guild, 'owner_id') self.owner_id: Optional[int] = utils._get_as_snowflake(guild, 'owner_id')
self._large: Optional[bool] = None if self._member_count is None else self._member_count >= 250 self._large: Optional[bool] = None if self._member_count is None else self._member_count >= 250
self._afk_channel_id: Optional[int] = utils._get_as_snowflake(guild, 'afk_channel_id') self._afk_channel_id: Optional[int] = utils._get_as_snowflake(guild, 'afk_channel_id')
self._incidents_data: Optional[IncidentData] = guild.get('incidents_data')
if 'channels' in guild: if 'channels' in guild:
channels = guild['channels'] channels = guild['channels']
@ -1843,6 +1840,8 @@ class Guild(Hashable):
mfa_level: MFALevel = MISSING, mfa_level: MFALevel = MISSING,
raid_alerts_disabled: bool = MISSING, raid_alerts_disabled: bool = MISSING,
safety_alerts_channel: TextChannel = MISSING, safety_alerts_channel: TextChannel = MISSING,
invites_disabled_until: datetime.datetime = MISSING,
dms_disabled_until: datetime.datetime = MISSING,
) -> Guild: ) -> Guild:
r"""|coro| r"""|coro|
@ -1969,6 +1968,18 @@ class Guild(Hashable):
.. versionadded:: 2.3 .. versionadded:: 2.3
invites_disabled_until: Optional[:class:`datetime.datetime`]
The time when invites should be enabled again, or ``None`` to disable the action.
This must be a timezone-aware datetime object. Consider using :func:`utils.utcnow`.
.. versionadded:: 2.4
dms_disabled_until: Optional[:class:`datetime.datetime`]
The time when direct messages should be allowed again, or ``None`` to disable the action.
This must be a timezone-aware datetime object. Consider using :func:`utils.utcnow`.
.. versionadded:: 2.4
Raises Raises
------- -------
Forbidden Forbidden
@ -2157,6 +2168,30 @@ class Guild(Hashable):
await http.edit_guild_mfa_level(self.id, mfa_level=mfa_level.value) await http.edit_guild_mfa_level(self.id, mfa_level=mfa_level.value)
incident_actions_payload: IncidentData = {}
if invites_disabled_until is not MISSING:
if invites_disabled_until is None:
incident_actions_payload['invites_disabled_until'] = None
else:
if invites_disabled_until.tzinfo is None:
raise TypeError(
'invites_disabled_until must be an aware datetime. Consider using discord.utils.utcnow() or datetime.datetime.now().astimezone() for local time.'
)
incident_actions_payload['invites_disabled_until'] = invites_disabled_until.isoformat()
if dms_disabled_until is not MISSING:
if dms_disabled_until is None:
incident_actions_payload['dms_disabled_until'] = None
else:
if dms_disabled_until.tzinfo is None:
raise TypeError(
'dms_disabled_until must be an aware datetime. Consider using discord.utils.utcnow() or datetime.datetime.now().astimezone() for local time.'
)
incident_actions_payload['dms_disabled_until'] = dms_disabled_until.isoformat()
if incident_actions_payload:
await http.edit_incident_actions(self.id, payload=incident_actions_payload)
data = await http.edit_guild(self.id, reason=reason, **fields) data = await http.edit_guild(self.id, reason=reason, **fields)
return Guild(data=data, state=self._state) return Guild(data=data, state=self._state)
@ -2524,7 +2559,7 @@ class Guild(Hashable):
The inactive members are denoted if they have not logged on in The inactive members are denoted if they have not logged on in
``days`` number of days and they have no roles. ``days`` number of days and they have no roles.
You must have :attr:`~Permissions.kick_members` to do this. You must have both :attr:`~Permissions.kick_members` and :attr:`~Permissions.manage_guild` to do this.
To check how many members you would prune without actually pruning, To check how many members you would prune without actually pruning,
see the :meth:`estimate_pruned_members` function. see the :meth:`estimate_pruned_members` function.
@ -3658,7 +3693,7 @@ class Guild(Hashable):
Parameters Parameters
----------- -----------
user: :class:`abc.Snowflake` user: :class:`abc.Snowflake`
The user to kick from their guild. The user to kick from the guild.
reason: Optional[:class:`str`] reason: Optional[:class:`str`]
The reason the user got kicked. The reason the user got kicked.
@ -3690,7 +3725,7 @@ class Guild(Hashable):
Parameters Parameters
----------- -----------
user: :class:`abc.Snowflake` user: :class:`abc.Snowflake`
The user to ban from their guild. The user to ban from the guild.
delete_message_days: :class:`int` delete_message_days: :class:`int`
The number of days worth of messages to delete from the user The number of days worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 7. in the guild. The minimum is 0 and the maximum is 7.
@ -3759,6 +3794,58 @@ class Guild(Hashable):
""" """
await self._state.http.unban(user.id, self.id, reason=reason) await self._state.http.unban(user.id, self.id, reason=reason)
async def bulk_ban(
self,
users: Iterable[Snowflake],
*,
reason: Optional[str] = None,
delete_message_seconds: int = 86400,
) -> BulkBanResult:
"""|coro|
Bans multiple users from the guild.
The users must meet the :class:`abc.Snowflake` abc.
You must have :attr:`~Permissions.ban_members` and :attr:`~Permissions.manage_guild` to do this.
.. versionadded:: 2.4
Parameters
-----------
users: Iterable[:class:`abc.Snowflake`]
The users to ban from the guild, up to 200 users.
delete_message_seconds: :class:`int`
The number of seconds worth of messages to delete from the user
in the guild. The minimum is 0 and the maximum is 604800 (7 days).
Defaults to 1 day.
reason: Optional[:class:`str`]
The reason the users got banned.
Raises
-------
Forbidden
You do not have the proper permissions to ban.
HTTPException
Banning failed.
Returns
--------
:class:`BulkBanResult`
The result of the bulk ban operation.
"""
response = await self._state.http.bulk_ban(
self.id,
user_ids=[u.id for u in users],
delete_message_seconds=delete_message_seconds,
reason=reason,
)
return BulkBanResult(
banned=[Object(id=int(user_id), type=User) for user_id in response.get('banned_users', []) or []],
failed=[Object(id=int(user_id), type=User) for user_id in response.get('failed_users', []) or []],
)
@property @property
def vanity_url(self) -> Optional[str]: def vanity_url(self) -> Optional[str]:
"""Optional[:class:`str`]: The Discord vanity invite URL for this guild, if available. """Optional[:class:`str`]: The Discord vanity invite URL for this guild, if available.
@ -3776,7 +3863,7 @@ class Guild(Hashable):
The guild must have ``VANITY_URL`` in :attr:`~Guild.features`. The guild must have ``VANITY_URL`` in :attr:`~Guild.features`.
You must have :attr:`~Permissions.manage_guild` to do this.as well. You must have :attr:`~Permissions.manage_guild` to do this as well.
Raises Raises
------- -------
@ -4303,3 +4390,47 @@ class Guild(Hashable):
) )
return AutoModRule(data=data, guild=self, state=self._state) return AutoModRule(data=data, guild=self, state=self._state)
@property
def invites_paused_until(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: If invites are paused, returns when
invites will get enabled in UTC, otherwise returns None.
.. versionadded:: 2.4
"""
if not self._incidents_data:
return None
return utils.parse_time(self._incidents_data.get('invites_disabled_until'))
@property
def dms_paused_until(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: If DMs are paused, returns when DMs
will get enabled in UTC, otherwise returns None.
.. versionadded:: 2.4
"""
if not self._incidents_data:
return None
return utils.parse_time(self._incidents_data.get('dms_disabled_until'))
def invites_paused(self) -> bool:
""":class:`bool`: Whether invites are paused in the guild.
.. versionadded:: 2.4
"""
if not self.invites_paused_until:
return False
return self.invites_paused_until > utils.utcnow()
def dms_paused(self) -> bool:
""":class:`bool`: Whether DMs are paused in the guild.
.. versionadded:: 2.4
"""
if not self.dms_paused_until:
return False
return self.dms_paused_until > utils.utcnow()

82
discord/http.py

@ -68,6 +68,7 @@ if TYPE_CHECKING:
from .embeds import Embed from .embeds import Embed
from .message import Attachment from .message import Attachment
from .flags import MessageFlags from .flags import MessageFlags
from .poll import Poll
from .types import ( from .types import (
appinfo, appinfo,
@ -91,6 +92,7 @@ if TYPE_CHECKING:
sticker, sticker,
welcome_screen, welcome_screen,
sku, sku,
poll,
) )
from .types.snowflake import Snowflake, SnowflakeList from .types.snowflake import Snowflake, SnowflakeList
@ -154,6 +156,7 @@ def handle_message_parameters(
thread_name: str = MISSING, thread_name: str = MISSING,
channel_payload: Dict[str, Any] = MISSING, channel_payload: Dict[str, Any] = MISSING,
applied_tags: Optional[SnowflakeList] = MISSING, applied_tags: Optional[SnowflakeList] = MISSING,
poll: Optional[Poll] = MISSING,
) -> MultipartParameters: ) -> MultipartParameters:
if files is not MISSING and file is not MISSING: if files is not MISSING and file is not MISSING:
raise TypeError('Cannot mix file and files keyword arguments.') raise TypeError('Cannot mix file and files keyword arguments.')
@ -256,6 +259,9 @@ def handle_message_parameters(
} }
payload.update(channel_payload) payload.update(channel_payload)
if poll not in (MISSING, None):
payload['poll'] = poll._to_dict() # type: ignore
multipart = [] multipart = []
if files: if files:
multipart.append({'name': 'payload_json', 'value': utils._to_json(payload)}) multipart.append({'name': 'payload_json', 'value': utils._to_json(payload)})
@ -935,6 +941,7 @@ class HTTPClient:
emoji: str, emoji: str,
limit: int, limit: int,
after: Optional[Snowflake] = None, after: Optional[Snowflake] = None,
type: Optional[message.ReactionType] = None,
) -> Response[List[user.User]]: ) -> Response[List[user.User]]:
r = Route( r = Route(
'GET', 'GET',
@ -949,6 +956,10 @@ class HTTPClient:
} }
if after: if after:
params['after'] = after params['after'] = after
if type is not None:
params['type'] = type
return self.request(r, params=params) return self.request(r, params=params)
def clear_reactions(self, channel_id: Snowflake, message_id: Snowflake) -> Response[None]: def clear_reactions(self, channel_id: Snowflake, message_id: Snowflake) -> Response[None]:
@ -1055,6 +1066,20 @@ class HTTPClient:
r = Route('DELETE', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id) r = Route('DELETE', '/guilds/{guild_id}/bans/{user_id}', guild_id=guild_id, user_id=user_id)
return self.request(r, reason=reason) return self.request(r, reason=reason)
def bulk_ban(
self,
guild_id: Snowflake,
user_ids: List[Snowflake],
delete_message_seconds: int = 86400,
reason: Optional[str] = None,
) -> Response[guild.BulkBanUserResponse]:
r = Route('POST', '/guilds/{guild_id}/bulk-ban', guild_id=guild_id)
payload = {
'user_ids': user_ids,
'delete_message_seconds': delete_message_seconds,
}
return self.request(r, json=payload, reason=reason)
def guild_voice_state( def guild_voice_state(
self, self,
user_id: Snowflake, user_id: Snowflake,
@ -1163,6 +1188,13 @@ class HTTPClient:
payload = {k: v for k, v in options.items() if k in valid_keys} payload = {k: v for k, v in options.items() if k in valid_keys}
return self.request(r, reason=reason, json=payload) return self.request(r, reason=reason, json=payload)
def edit_voice_channel_status(
self, status: Optional[str], *, channel_id: int, reason: Optional[str] = None
) -> Response[None]:
r = Route('PUT', '/channels/{channel_id}/voice-status', channel_id=channel_id)
payload = {'status': status}
return self.request(r, reason=reason, json=payload)
def bulk_channel_update( def bulk_channel_update(
self, self,
guild_id: Snowflake, guild_id: Snowflake,
@ -1757,6 +1789,9 @@ class HTTPClient:
) -> Response[widget.WidgetSettings]: ) -> Response[widget.WidgetSettings]:
return self.request(Route('PATCH', '/guilds/{guild_id}/widget', guild_id=guild_id), json=payload, reason=reason) return self.request(Route('PATCH', '/guilds/{guild_id}/widget', guild_id=guild_id), json=payload, reason=reason)
def edit_incident_actions(self, guild_id: Snowflake, payload: guild.IncidentData) -> Response[guild.IncidentData]:
return self.request(Route('PUT', '/guilds/{guild_id}/incident-actions', guild_id=guild_id), json=payload)
# Invite management # Invite management
def create_invite( def create_invite(
@ -2453,6 +2488,16 @@ class HTTPClient:
), ),
) )
def consume_entitlement(self, application_id: Snowflake, entitlement_id: Snowflake) -> Response[None]:
return self.request(
Route(
'POST',
'/applications/{application_id}/entitlements/{entitlement_id}/consume',
application_id=application_id,
entitlement_id=entitlement_id,
),
)
def create_entitlement( def create_entitlement(
self, application_id: Snowflake, sku_id: Snowflake, owner_id: Snowflake, owner_type: sku.EntitlementOwnerType self, application_id: Snowflake, sku_id: Snowflake, owner_id: Snowflake, owner_type: sku.EntitlementOwnerType
) -> Response[sku.Entitlement]: ) -> Response[sku.Entitlement]:
@ -2502,6 +2547,43 @@ class HTTPClient:
payload = {k: v for k, v in payload.items() if k in valid_keys} payload = {k: v for k, v in payload.items() if k in valid_keys}
return self.request(Route('PATCH', '/applications/@me'), json=payload, reason=reason) return self.request(Route('PATCH', '/applications/@me'), json=payload, reason=reason)
def get_poll_answer_voters(
self,
channel_id: Snowflake,
message_id: Snowflake,
answer_id: Snowflake,
after: Optional[Snowflake] = None,
limit: Optional[int] = None,
) -> Response[poll.PollAnswerVoters]:
params = {}
if after:
params['after'] = int(after)
if limit is not None:
params['limit'] = limit
return self.request(
Route(
'GET',
'/channels/{channel_id}/polls/{message_id}/answers/{answer_id}',
channel_id=channel_id,
message_id=message_id,
answer_id=answer_id,
),
params=params,
)
def end_poll(self, channel_id: Snowflake, message_id: Snowflake) -> Response[message.Message]:
return self.request(
Route(
'POST',
'/channels/{channel_id}/polls/{message_id}/expire',
channel_id=channel_id,
message_id=message_id,
)
)
async def get_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> str: async def get_gateway(self, *, encoding: str = 'json', zlib: bool = True) -> str:
try: try:
data = await self.request(Route('GET', '/gateway')) data = await self.request(Route('GET', '/gateway'))

78
discord/interactions.py

@ -45,6 +45,7 @@ from .message import Message, Attachment
from .permissions import Permissions from .permissions import Permissions
from .http import handle_message_parameters from .http import handle_message_parameters
from .webhook.async_ import async_context, Webhook, interaction_response_params, interaction_message_response_params from .webhook.async_ import async_context, Webhook, interaction_response_params, interaction_message_response_params
from .app_commands.installs import AppCommandContext
from .app_commands.namespace import Namespace from .app_commands.namespace import Namespace
from .app_commands.translator import locale_str, TranslationContext, TranslationContextLocation from .app_commands.translator import locale_str, TranslationContext, TranslationContextLocation
from .channel import _threaded_channel_factory from .channel import _threaded_channel_factory
@ -64,6 +65,7 @@ if TYPE_CHECKING:
from .types.webhook import ( from .types.webhook import (
Webhook as WebhookPayload, Webhook as WebhookPayload,
) )
from .types.snowflake import Snowflake
from .guild import Guild from .guild import Guild
from .state import ConnectionState from .state import ConnectionState
from .file import File from .file import File
@ -76,6 +78,7 @@ if TYPE_CHECKING:
from .channel import VoiceChannel, StageChannel, TextChannel, ForumChannel, CategoryChannel, DMChannel, GroupChannel from .channel import VoiceChannel, StageChannel, TextChannel, ForumChannel, CategoryChannel, DMChannel, GroupChannel
from .threads import Thread from .threads import Thread
from .app_commands.commands import Command, ContextMenu from .app_commands.commands import Command, ContextMenu
from .poll import Poll
InteractionChannel = Union[ InteractionChannel = Union[
VoiceChannel, VoiceChannel,
@ -139,6 +142,10 @@ class Interaction(Generic[ClientT]):
command_failed: :class:`bool` command_failed: :class:`bool`
Whether the command associated with this interaction failed to execute. Whether the command associated with this interaction failed to execute.
This includes checks and execution. This includes checks and execution.
context: :class:`.AppCommandContext`
The context of the interaction.
.. versionadded:: 2.4
""" """
__slots__: Tuple[str, ...] = ( __slots__: Tuple[str, ...] = (
@ -157,6 +164,8 @@ class Interaction(Generic[ClientT]):
'command_failed', 'command_failed',
'entitlement_sku_ids', 'entitlement_sku_ids',
'entitlements', 'entitlements',
"context",
'_integration_owners',
'_permissions', '_permissions',
'_app_permissions', '_app_permissions',
'_state', '_state',
@ -194,6 +203,14 @@ class Interaction(Generic[ClientT]):
self.application_id: int = int(data['application_id']) self.application_id: int = int(data['application_id'])
self.entitlement_sku_ids: List[int] = [int(x) for x in data.get('entitlement_skus', []) or []] self.entitlement_sku_ids: List[int] = [int(x) for x in data.get('entitlement_skus', []) or []]
self.entitlements: List[Entitlement] = [Entitlement(self._state, x) for x in data.get('entitlements', [])] self.entitlements: List[Entitlement] = [Entitlement(self._state, x) for x in data.get('entitlements', [])]
# This is not entirely useful currently, unsure how to expose it in a way that it is.
self._integration_owners: Dict[int, Snowflake] = {
int(k): int(v) for k, v in data.get('authorizing_integration_owners', {}).items()
}
try:
self.context = AppCommandContext._from_value([data['context']])
except KeyError:
self.context = AppCommandContext()
self.locale: Locale = try_enum(Locale, data.get('locale', 'en-US')) self.locale: Locale = try_enum(Locale, data.get('locale', 'en-US'))
self.guild_locale: Optional[Locale] self.guild_locale: Optional[Locale]
@ -204,7 +221,10 @@ class Interaction(Generic[ClientT]):
guild = None guild = None
if self.guild_id: if self.guild_id:
guild = self._state._get_or_create_unavailable_guild(self.guild_id) # The data type is a TypedDict but it doesn't narrow to Dict[str, Any] properly
guild = self._state._get_or_create_unavailable_guild(self.guild_id, data=data.get('guild')) # type: ignore
if guild.me is None and self._client.user is not None:
guild._add_member(Member._from_client_user(user=self._client.user, guild=guild, state=self._state))
raw_channel = data.get('channel', {}) raw_channel = data.get('channel', {})
channel_id = utils._get_as_snowflake(raw_channel, 'id') channel_id = utils._get_as_snowflake(raw_channel, 'id')
@ -371,6 +391,22 @@ class Interaction(Generic[ClientT]):
""":class:`bool`: Returns ``True`` if the interaction is expired.""" """:class:`bool`: Returns ``True`` if the interaction is expired."""
return utils.utcnow() >= self.expires_at return utils.utcnow() >= self.expires_at
def is_guild_integration(self) -> bool:
""":class:`bool`: Returns ``True`` if the interaction is a guild integration.
.. versionadded:: 2.4
"""
if self.guild_id:
return self.guild_id == self._integration_owners.get(0)
return False
def is_user_integration(self) -> bool:
""":class:`bool`: Returns ``True`` if the interaction is a user integration.
.. versionadded:: 2.4
"""
return self.user.id == self._integration_owners.get(1)
async def original_response(self) -> InteractionMessage: async def original_response(self) -> InteractionMessage:
"""|coro| """|coro|
@ -727,6 +763,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,
poll: Poll = MISSING,
) -> None: ) -> None:
"""|coro| """|coro|
@ -770,6 +807,10 @@ class InteractionResponse(Generic[ClientT]):
then it is silently ignored. then it is silently ignored.
.. versionadded:: 2.1 .. versionadded:: 2.1
poll: :class:`~discord.Poll`
The poll to send with this message.
.. versionadded:: 2.4
Raises Raises
------- -------
@ -807,6 +848,7 @@ class InteractionResponse(Generic[ClientT]):
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
flags=flags, flags=flags,
view=view, view=view,
poll=poll,
) )
http = parent._state.http http = parent._state.http
@ -914,7 +956,7 @@ class InteractionResponse(Generic[ClientT]):
message_id = msg.id message_id = msg.id
# If this was invoked via an application command then we can use its original interaction ID # If this was invoked via an application command then we can use its original interaction ID
# Since this is used as a cache key for view updates # Since this is used as a cache key for view updates
original_interaction_id = msg.interaction.id if msg.interaction is not None else None original_interaction_id = msg.interaction_metadata.id if msg.interaction_metadata is not None else None
else: else:
message_id = None message_id = None
original_interaction_id = None original_interaction_id = None
@ -1008,38 +1050,6 @@ class InteractionResponse(Generic[ClientT]):
self._parent._state.store_view(modal) self._parent._state.store_view(modal)
self._response_type = InteractionResponseType.modal self._response_type = InteractionResponseType.modal
async def require_premium(self) -> None:
"""|coro|
Sends a message to the user prompting them that a premium purchase is required for this interaction.
This type of response is only available for applications that have a premium SKU set up.
Raises
-------
HTTPException
Sending the response failed.
InteractionResponded
This interaction has already been responded to before.
"""
if self._response_type:
raise InteractionResponded(self._parent)
parent = self._parent
adapter = async_context.get()
http = parent._state.http
params = interaction_response_params(InteractionResponseType.premium_required.value)
await adapter.create_interaction_response(
parent.id,
parent.token,
session=parent._session,
proxy=http.proxy,
proxy_auth=http.proxy_auth,
params=params,
)
self._response_type = InteractionResponseType.premium_required
async def autocomplete(self, choices: Sequence[Choice[ChoiceT]]) -> None: async def autocomplete(self, choices: Sequence[Choice[ChoiceT]]) -> None:
"""|coro| """|coro|

10
discord/invite.py

@ -29,7 +29,7 @@ from .asset import Asset
from .utils import parse_time, snowflake_time, _get_as_snowflake from .utils import parse_time, snowflake_time, _get_as_snowflake
from .object import Object from .object import Object
from .mixins import Hashable from .mixins import Hashable
from .enums import ChannelType, NSFWLevel, VerificationLevel, InviteTarget, try_enum from .enums import ChannelType, NSFWLevel, VerificationLevel, InviteTarget, InviteType, try_enum
from .appinfo import PartialAppInfo from .appinfo import PartialAppInfo
from .scheduled_event import ScheduledEvent from .scheduled_event import ScheduledEvent
@ -296,6 +296,10 @@ class Invite(Hashable):
Attributes Attributes
----------- -----------
type: :class:`InviteType`
The type of the invite.
.. versionadded: 2.4
max_age: Optional[:class:`int`] max_age: Optional[:class:`int`]
How long before the invite expires in seconds. How long before the invite expires in seconds.
A value of ``0`` indicates that it doesn't expire. A value of ``0`` indicates that it doesn't expire.
@ -374,6 +378,7 @@ class Invite(Hashable):
'expires_at', 'expires_at',
'scheduled_event', 'scheduled_event',
'scheduled_event_id', 'scheduled_event_id',
'type',
) )
BASE = 'https://discord.gg' BASE = 'https://discord.gg'
@ -387,6 +392,7 @@ class Invite(Hashable):
channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None, channel: Optional[Union[PartialInviteChannel, GuildChannel]] = None,
): ):
self._state: ConnectionState = state self._state: ConnectionState = state
self.type: InviteType = try_enum(InviteType, data.get('type', 0))
self.max_age: Optional[int] = data.get('max_age') self.max_age: Optional[int] = data.get('max_age')
self.code: str = data['code'] self.code: str = data['code']
self.guild: Optional[InviteGuildType] = self._resolve_guild(data.get('guild'), guild) self.guild: Optional[InviteGuildType] = self._resolve_guild(data.get('guild'), guild)
@ -496,7 +502,7 @@ class Invite(Hashable):
def __repr__(self) -> str: def __repr__(self) -> str:
return ( return (
f'<Invite code={self.code!r} guild={self.guild!r} ' f'<Invite type={self.type} code={self.code!r} guild={self.guild!r} '
f'online={self.approximate_presence_count} ' f'online={self.approximate_presence_count} '
f'members={self.approximate_member_count}>' f'members={self.approximate_member_count}>'
) )

40
discord/member.py

@ -35,7 +35,7 @@ import discord.abc
from . import utils from . import utils
from .asset import Asset from .asset import Asset
from .utils import MISSING from .utils import MISSING
from .user import BaseUser, User, _UserTag from .user import BaseUser, ClientUser, User, _UserTag
from .activity import create_activity, ActivityTypes from .activity import create_activity, ActivityTypes
from .permissions import Permissions from .permissions import Permissions
from .enums import Status, try_enum from .enums import Status, try_enum
@ -67,7 +67,7 @@ if TYPE_CHECKING:
UserWithMember as UserWithMemberPayload, UserWithMember as UserWithMemberPayload,
) )
from .types.gateway import GuildMemberUpdateEvent from .types.gateway import GuildMemberUpdateEvent
from .types.user import User as UserPayload from .types.user import User as UserPayload, AvatarDecorationData
from .abc import Snowflake from .abc import Snowflake
from .state import ConnectionState from .state import ConnectionState
from .message import Message from .message import Message
@ -323,6 +323,7 @@ class Member(discord.abc.Messageable, _UserTag):
'_state', '_state',
'_avatar', '_avatar',
'_flags', '_flags',
'_avatar_decoration_data',
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@ -342,6 +343,8 @@ class Member(discord.abc.Messageable, _UserTag):
banner: Optional[Asset] banner: Optional[Asset]
accent_color: Optional[Colour] accent_color: Optional[Colour]
accent_colour: Optional[Colour] accent_colour: Optional[Colour]
avatar_decoration: Optional[Asset]
avatar_decoration_sku_id: Optional[int]
def __init__(self, *, data: MemberWithUserPayload, guild: Guild, state: ConnectionState): def __init__(self, *, data: MemberWithUserPayload, guild: Guild, state: ConnectionState):
self._state: ConnectionState = state self._state: ConnectionState = state
@ -357,6 +360,7 @@ class Member(discord.abc.Messageable, _UserTag):
self._avatar: Optional[str] = data.get('avatar') self._avatar: Optional[str] = data.get('avatar')
self._permissions: Optional[int] self._permissions: Optional[int]
self._flags: int = data['flags'] self._flags: int = data['flags']
self._avatar_decoration_data: Optional[AvatarDecorationData] = data.get('avatar_decoration_data')
try: try:
self._permissions = int(data['permissions']) self._permissions = int(data['permissions'])
except KeyError: except KeyError:
@ -388,6 +392,15 @@ class Member(discord.abc.Messageable, _UserTag):
data['user'] = author._to_minimal_user_json() # type: ignore data['user'] = author._to_minimal_user_json() # type: ignore
return cls(data=data, guild=message.guild, state=message._state) # type: ignore return cls(data=data, guild=message.guild, state=message._state) # type: ignore
@classmethod
def _from_client_user(cls, *, user: ClientUser, guild: Guild, state: ConnectionState) -> Self:
data = {
'roles': [],
'user': user._to_minimal_user_json(),
'flags': 0,
}
return cls(data=data, guild=guild, state=state) # type: ignore
def _update_from_message(self, data: MemberPayload) -> None: def _update_from_message(self, data: MemberPayload) -> None:
self.joined_at = utils.parse_time(data.get('joined_at')) self.joined_at = utils.parse_time(data.get('joined_at'))
self.premium_since = utils.parse_time(data.get('premium_since')) self.premium_since = utils.parse_time(data.get('premium_since'))
@ -425,6 +438,7 @@ class Member(discord.abc.Messageable, _UserTag):
self._permissions = member._permissions self._permissions = member._permissions
self._state = member._state self._state = member._state
self._avatar = member._avatar self._avatar = member._avatar
self._avatar_decoration_data = member._avatar_decoration_data
# Reference will not be copied unless necessary by PRESENCE_UPDATE # Reference will not be copied unless necessary by PRESENCE_UPDATE
# See below # See below
@ -453,6 +467,7 @@ class Member(discord.abc.Messageable, _UserTag):
self._roles = utils.SnowflakeList(map(int, data['roles'])) self._roles = utils.SnowflakeList(map(int, data['roles']))
self._avatar = data.get('avatar') self._avatar = data.get('avatar')
self._flags = data.get('flags', 0) self._flags = data.get('flags', 0)
self._avatar_decoration_data = data.get('avatar_decoration_data')
def _presence_update(self, data: PartialPresenceUpdate, user: UserPayload) -> Optional[Tuple[User, User]]: def _presence_update(self, data: PartialPresenceUpdate, user: UserPayload) -> Optional[Tuple[User, User]]:
self.activities = tuple(create_activity(d, self._state) for d in data['activities']) self.activities = tuple(create_activity(d, self._state) for d in data['activities'])
@ -464,7 +479,16 @@ class Member(discord.abc.Messageable, _UserTag):
def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]: def _update_inner_user(self, user: UserPayload) -> Optional[Tuple[User, User]]:
u = self._user u = self._user
original = (u.name, u.discriminator, u._avatar, u.global_name, u._public_flags) original = (
u.name,
u.discriminator,
u._avatar,
u.global_name,
u._public_flags,
u._avatar_decoration_data['sku_id'] if u._avatar_decoration_data is not None else None,
)
decoration_payload = user.get('avatar_decoration_data')
# These keys seem to always be available # These keys seem to always be available
modified = ( modified = (
user['username'], user['username'],
@ -472,10 +496,18 @@ class Member(discord.abc.Messageable, _UserTag):
user['avatar'], user['avatar'],
user.get('global_name'), user.get('global_name'),
user.get('public_flags', 0), user.get('public_flags', 0),
decoration_payload['sku_id'] if decoration_payload is not None else None,
) )
if original != modified: if original != modified:
to_return = User._copy(self._user) to_return = User._copy(self._user)
u.name, u.discriminator, u._avatar, u.global_name, u._public_flags = modified u.name, u.discriminator, u._avatar, u.global_name, u._public_flags, u._avatar_decoration_data = (
user['username'],
user['discriminator'],
user['avatar'],
user.get('global_name'),
user.get('public_flags', 0),
decoration_payload,
)
# Signal to dispatch on_user_update # Signal to dispatch on_user_update
return to_return, u return to_return, u

217
discord/message.py

@ -56,13 +56,14 @@ from .embeds import Embed
from .member import Member from .member import Member
from .flags import MessageFlags, AttachmentFlags from .flags import MessageFlags, AttachmentFlags
from .file import File from .file import File
from .utils import escape_mentions, MISSING from .utils import escape_mentions, MISSING, deprecated
from .http import handle_message_parameters from .http import handle_message_parameters
from .guild import Guild from .guild import Guild
from .mixins import Hashable from .mixins import Hashable
from .sticker import StickerItem, GuildSticker from .sticker import StickerItem, GuildSticker
from .threads import Thread from .threads import Thread
from .channel import PartialMessageable from .channel import PartialMessageable
from .poll import Poll
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Self from typing_extensions import Self
@ -74,6 +75,7 @@ if TYPE_CHECKING:
MessageApplication as MessageApplicationPayload, MessageApplication as MessageApplicationPayload,
MessageActivity as MessageActivityPayload, MessageActivity as MessageActivityPayload,
RoleSubscriptionData as RoleSubscriptionDataPayload, RoleSubscriptionData as RoleSubscriptionDataPayload,
MessageInteractionMetadata as MessageInteractionMetadataPayload,
) )
from .types.interactions import MessageInteraction as MessageInteractionPayload from .types.interactions import MessageInteraction as MessageInteractionPayload
@ -109,6 +111,7 @@ __all__ = (
'DeletedReferencedMessage', 'DeletedReferencedMessage',
'MessageApplication', 'MessageApplication',
'RoleSubscriptionInfo', 'RoleSubscriptionInfo',
'MessageInteractionMetadata',
) )
@ -624,6 +627,123 @@ class MessageInteraction(Hashable):
return utils.snowflake_time(self.id) return utils.snowflake_time(self.id)
class MessageInteractionMetadata(Hashable):
"""Represents the interaction metadata of a :class:`Message` if
it was sent in response to an interaction.
.. versionadded:: 2.4
.. container:: operations
.. describe:: x == y
Checks if two message interactions are equal.
.. describe:: x != y
Checks if two message interactions are not equal.
.. describe:: hash(x)
Returns the message interaction's hash.
Attributes
-----------
id: :class:`int`
The interaction ID.
type: :class:`InteractionType`
The interaction type.
user: :class:`User`
The user that invoked the interaction.
original_response_message_id: Optional[:class:`int`]
The ID of the original response message if the message is a follow-up.
interacted_message_id: Optional[:class:`int`]
The ID of the message that containes the interactive components, if applicable.
modal_interaction: Optional[:class:`.MessageInteractionMetadata`]
The metadata of the modal submit interaction that triggered this interaction, if applicable.
"""
__slots__: Tuple[str, ...] = (
'id',
'type',
'user',
'original_response_message_id',
'interacted_message_id',
'modal_interaction',
'_integration_owners',
'_state',
'_guild',
)
def __init__(self, *, state: ConnectionState, guild: Optional[Guild], data: MessageInteractionMetadataPayload) -> None:
self._guild: Optional[Guild] = guild
self._state: ConnectionState = state
self.id: int = int(data['id'])
self.type: InteractionType = try_enum(InteractionType, data['type'])
self.user = state.create_user(data['user'])
self._integration_owners: Dict[int, int] = {
int(key): int(value) for key, value in data.get('authorizing_integration_owners', {}).items()
}
self.original_response_message_id: Optional[int] = None
try:
self.original_response_message_id = int(data['original_response_message_id'])
except KeyError:
pass
self.interacted_message_id: Optional[int] = None
try:
self.interacted_message_id = int(data['interacted_message_id'])
except KeyError:
pass
self.modal_interaction: Optional[MessageInteractionMetadata] = None
try:
self.modal_interaction = MessageInteractionMetadata(
state=state, guild=guild, data=data['triggering_interaction_metadata']
)
except KeyError:
pass
def __repr__(self) -> str:
return f'<MessageInteraction id={self.id} type={self.type!r} user={self.user!r}>'
@property
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The interaction's creation time in UTC."""
return utils.snowflake_time(self.id)
@property
def original_response_message(self) -> Optional[Message]:
"""Optional[:class:`~discord.Message`]: The original response message if the message
is a follow-up and is found in cache.
"""
if self.original_response_message_id:
return self._state._get_message(self.original_response_message_id)
return None
@property
def interacted_message(self) -> Optional[Message]:
"""Optional[:class:`~discord.Message`]: The message that
containes the interactive components, if applicable and is found in cache.
"""
if self.interacted_message_id:
return self._state._get_message(self.interacted_message_id)
return None
def is_guild_integration(self) -> bool:
""":class:`bool`: Returns ``True`` if the interaction is a guild integration."""
if self._guild:
return self._guild.id == self._integration_owners.get(0)
return False
def is_user_integration(self) -> bool:
""":class:`bool`: Returns ``True`` if the interaction is a user integration."""
return self.user.id == self._integration_owners.get(1)
def flatten_handlers(cls: Type[Message]) -> Type[Message]: def flatten_handlers(cls: Type[Message]) -> Type[Message]:
prefix = len('_handle_') prefix = len('_handle_')
handlers = [ handlers = [
@ -1345,6 +1465,7 @@ class PartialMessage(Hashable):
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1365,6 +1486,7 @@ class PartialMessage(Hashable):
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1385,6 +1507,7 @@ class PartialMessage(Hashable):
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1405,6 +1528,7 @@ class PartialMessage(Hashable):
view: View = ..., view: View = ...,
suppress_embeds: bool = ..., suppress_embeds: bool = ...,
silent: bool = ..., silent: bool = ...,
poll: Poll = ...,
) -> Message: ) -> Message:
... ...
@ -1439,6 +1563,30 @@ class PartialMessage(Hashable):
return await self.channel.send(content, reference=self, **kwargs) return await self.channel.send(content, reference=self, **kwargs)
async def end_poll(self) -> Message:
"""|coro|
Ends the :class:`Poll` attached to this message.
This can only be done if you are the message author.
If the poll was successfully ended, then it returns the updated :class:`Message`.
Raises
------
~discord.HTTPException
Ending the poll failed.
Returns
-------
:class:`.Message`
The updated message.
"""
data = await self._state.http.end_poll(self.channel.id, self.id)
return Message(state=self._state, channel=self.channel, data=data)
def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference: def to_reference(self, *, fail_if_not_exists: bool = True) -> MessageReference:
"""Creates a :class:`~discord.MessageReference` from the current message. """Creates a :class:`~discord.MessageReference` from the current message.
@ -1588,10 +1736,6 @@ class Message(PartialMessage, Hashable):
If :attr:`Intents.message_content` is not enabled this will always be an empty list If :attr:`Intents.message_content` is not enabled this will always be an empty list
unless the bot is mentioned or the message is a direct message. unless the bot is mentioned or the message is a direct message.
.. versionadded:: 2.0
interaction: Optional[:class:`MessageInteraction`]
The interaction that this message is a response to.
.. versionadded:: 2.0 .. versionadded:: 2.0
role_subscription: Optional[:class:`RoleSubscriptionInfo`] role_subscription: Optional[:class:`RoleSubscriptionInfo`]
The data of the role subscription purchase or renewal that prompted this The data of the role subscription purchase or renewal that prompted this
@ -1610,6 +1754,14 @@ class Message(PartialMessage, Hashable):
.. versionadded:: 2.2 .. versionadded:: 2.2
guild: Optional[:class:`Guild`] guild: Optional[:class:`Guild`]
The guild that the message belongs to, if applicable. The guild that the message belongs to, if applicable.
interaction_metadata: Optional[:class:`.MessageInteractionMetadata`]
The metadata of the interaction that this message is a response to.
.. versionadded:: 2.4
poll: Optional[:class:`Poll`]
The poll attached to this message.
.. versionadded:: 2.4
""" """
__slots__ = ( __slots__ = (
@ -1640,10 +1792,12 @@ class Message(PartialMessage, Hashable):
'activity', 'activity',
'stickers', 'stickers',
'components', 'components',
'interaction', '_interaction',
'role_subscription', 'role_subscription',
'application_id', 'application_id',
'position', 'position',
'interaction_metadata',
'poll',
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@ -1683,6 +1837,14 @@ class Message(PartialMessage, Hashable):
self.application_id: Optional[int] = utils._get_as_snowflake(data, 'application_id') self.application_id: Optional[int] = utils._get_as_snowflake(data, 'application_id')
self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])] self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])]
# This updates the poll so it has the counts, if the message
# was previously cached.
self.poll: Optional[Poll] = None
try:
self.poll = Poll._from_data(data=data['poll'], message=self, state=state)
except KeyError:
self.poll = state._get_poll(self.id)
try: try:
# if the channel doesn't have a guild attribute, we handle that # if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild self.guild = channel.guild
@ -1704,14 +1866,23 @@ class Message(PartialMessage, Hashable):
else: else:
self._thread = Thread(guild=self.guild, state=state, data=thread) self._thread = Thread(guild=self.guild, state=state, data=thread)
self.interaction: Optional[MessageInteraction] = None self._interaction: Optional[MessageInteraction] = None
# deprecated
try: try:
interaction = data['interaction'] interaction = data['interaction']
except KeyError: except KeyError:
pass pass
else: else:
self.interaction = MessageInteraction(state=state, guild=self.guild, data=interaction) self._interaction = MessageInteraction(state=state, guild=self.guild, data=interaction)
self.interaction_metadata: Optional[MessageInteractionMetadata] = None
try:
interaction_metadata = data['interaction_metadata']
except KeyError:
pass
else:
self.interaction_metadata = MessageInteractionMetadata(state=state, guild=self.guild, data=interaction_metadata)
try: try:
ref = data['message_reference'] ref = data['message_reference']
@ -1935,7 +2106,10 @@ class Message(PartialMessage, Hashable):
self.components.append(component) self.components.append(component)
def _handle_interaction(self, data: MessageInteractionPayload): def _handle_interaction(self, data: MessageInteractionPayload):
self.interaction = MessageInteraction(state=self._state, guild=self.guild, data=data) self._interaction = MessageInteraction(state=self._state, guild=self.guild, data=data)
def _handle_interaction_metadata(self, data: MessageInteractionMetadataPayload):
self.interaction_metadata = MessageInteractionMetadata(state=self._state, guild=self.guild, data=data)
def _rebind_cached_references( def _rebind_cached_references(
self, self,
@ -2061,6 +2235,17 @@ class Message(PartialMessage, Hashable):
# Fall back to guild threads in case one was created after the message # Fall back to guild threads in case one was created after the message
return self._thread or self.guild.get_thread(self.id) return self._thread or self.guild.get_thread(self.id)
@property
@deprecated('interaction_metadata')
def interaction(self) -> Optional[MessageInteraction]:
"""Optional[:class:`~discord.MessageInteraction`]: The interaction that this message is a response to.
.. versionadded:: 2.0
.. deprecated:: 2.4
This attribute is deprecated and will be removed in a future version. Use :attr:`.interaction_metadata` instead.
"""
return self._interaction
def is_system(self) -> bool: def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message. """:class:`bool`: Whether the message is a system message.
@ -2216,6 +2401,20 @@ class Message(PartialMessage, Hashable):
if self.type is MessageType.stage_topic: if self.type is MessageType.stage_topic:
return f'{self.author.name} changed Stage topic: **{self.content}**.' return f'{self.author.name} changed Stage topic: **{self.content}**.'
if self.type is MessageType.guild_incident_alert_mode_enabled:
dt = utils.parse_time(self.content)
dt_content = utils.format_dt(dt)
return f'{self.author.name} enabled security actions until {dt_content}.'
if self.type is MessageType.guild_incident_alert_mode_disabled:
return f'{self.author.name} disabled security actions.'
if self.type is MessageType.guild_incident_report_raid:
return f'{self.author.name} reported a raid in {self.guild}.'
if self.type is MessageType.guild_incident_report_false_alarm:
return f'{self.author.name} reported a false alarm in {self.guild}.'
# Fallback for unknown message types # Fallback for unknown message types
return '' return ''

2
discord/object.py

@ -102,7 +102,7 @@ class Object(Hashable):
return f'<Object id={self.id!r} type={self.type!r}>' return f'<Object id={self.id!r} type={self.type!r}>'
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
if isinstance(other, self.type): if isinstance(other, (self.type, self.__class__)):
return self.id == other.id return self.id == other.id
return NotImplemented return NotImplemented

48
discord/permissions.py

@ -187,7 +187,7 @@ class Permissions(BaseFlags):
permissions set to ``True``. permissions set to ``True``.
""" """
# Some of these are 0 because we don't want to set unnecessary bits # Some of these are 0 because we don't want to set unnecessary bits
return cls(0b0000_0000_0000_0000_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111) return cls(0b0000_0000_0000_0010_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111_1111)
@classmethod @classmethod
def _timeout_mask(cls) -> int: def _timeout_mask(cls) -> int:
@ -224,6 +224,10 @@ class Permissions(BaseFlags):
- :attr:`ban_members` - :attr:`ban_members`
- :attr:`administrator` - :attr:`administrator`
- :attr:`create_expressions` - :attr:`create_expressions`
- :attr:`moderate_members`
- :attr:`create_events`
- :attr:`manage_events`
- :attr:`view_creator_monetization_analytics`
.. versionchanged:: 1.7 .. versionchanged:: 1.7
Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_application_commands` permissions. Added :attr:`stream`, :attr:`priority_speaker` and :attr:`use_application_commands` permissions.
@ -235,8 +239,12 @@ class Permissions(BaseFlags):
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Added :attr:`use_soundboard`, :attr:`create_expressions` permissions. Added :attr:`use_soundboard`, :attr:`create_expressions` permissions.
.. versionchanged:: 2.4
Added :attr:`send_polls`, :attr:`send_voice_messages`, attr:`use_external_sounds`, and
:attr:`use_embedded_activities` permissions.
""" """
return cls(0b0000_0000_0000_0000_0000_0100_0111_1101_1011_0011_1111_0111_1111_1111_0101_0001) return cls(0b0000_0000_0000_0010_0110_0100_1111_1101_1011_0011_1111_0111_1111_1111_0101_0001)
@classmethod @classmethod
def general(cls) -> Self: def general(cls) -> Self:
@ -251,8 +259,11 @@ class Permissions(BaseFlags):
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Added :attr:`create_expressions` permission. Added :attr:`create_expressions` permission.
.. versionchanged:: 2.4
Added :attr:`view_creator_monetization_analytics` permission.
""" """
return cls(0b0000_0000_0000_0000_0000_1000_0000_0000_0111_0000_0000_1000_0000_0100_1011_0000) return cls(0b0000_0000_0000_0000_0000_1010_0000_0000_0111_0000_0000_1000_0000_0100_1011_0000)
@classmethod @classmethod
def membership(cls) -> Self: def membership(cls) -> Self:
@ -278,8 +289,11 @@ class Permissions(BaseFlags):
.. versionchanged:: 2.3 .. versionchanged:: 2.3
Added :attr:`send_voice_messages` permission. Added :attr:`send_voice_messages` permission.
.. versionchanged:: 2.4
Added :attr:`send_polls` permission.
""" """
return cls(0b0000_0000_0000_0000_0100_0000_0111_1100_1000_0000_0000_0111_1111_1000_0100_0000) return cls(0b0000_0000_0000_0010_0100_0000_0111_1100_1000_0000_0000_0111_1111_1000_0100_0000)
@classmethod @classmethod
def voice(cls) -> Self: def voice(cls) -> Self:
@ -682,6 +696,14 @@ class Permissions(BaseFlags):
""" """
return 1 << 40 return 1 << 40
@flag_value
def view_creator_monetization_analytics(self) -> int:
""":class:`bool`: Returns ``True`` if a user can view role subscription insights.
.. versionadded:: 2.4
"""
return 1 << 41
@flag_value @flag_value
def use_soundboard(self) -> int: def use_soundboard(self) -> int:
""":class:`bool`: Returns ``True`` if a user can use the soundboard. """:class:`bool`: Returns ``True`` if a user can use the soundboard.
@ -722,6 +744,22 @@ class Permissions(BaseFlags):
""" """
return 1 << 46 return 1 << 46
@flag_value
def send_polls(self) -> int:
""":class:`bool`: Returns ``True`` if a user can send poll messages.
.. versionadded:: 2.4
"""
return 1 << 49
@make_permission_alias('send_polls')
def create_polls(self) -> int:
""":class:`bool`: An alias for :attr:`send_polls`.
.. versionadded:: 2.4
"""
return 1 << 49
def _augment_from_permissions(cls): def _augment_from_permissions(cls):
cls.VALID_NAMES = set(Permissions.VALID_FLAGS) cls.VALID_NAMES = set(Permissions.VALID_FLAGS)
@ -842,6 +880,8 @@ class PermissionOverwrite:
send_voice_messages: Optional[bool] send_voice_messages: Optional[bool]
create_expressions: Optional[bool] create_expressions: Optional[bool]
create_events: Optional[bool] create_events: Optional[bool]
send_polls: Optional[bool]
create_polls: Optional[bool]
def __init__(self, **kwargs: Optional[bool]): def __init__(self, **kwargs: Optional[bool]):
self._values: Dict[str, Optional[bool]] = {} self._values: Dict[str, Optional[bool]] = {}

15
discord/player.py

@ -288,6 +288,12 @@ class FFmpegPCMAudio(FFmpegAudio):
passed to the stdin of ffmpeg. passed to the stdin of ffmpeg.
executable: :class:`str` executable: :class:`str`
The executable name (and path) to use. Defaults to ``ffmpeg``. The executable name (and path) to use. Defaults to ``ffmpeg``.
.. warning::
Since this class spawns a subprocess, care should be taken to not
pass in an arbitrary executable name when using this parameter.
pipe: :class:`bool` pipe: :class:`bool`
If ``True``, denotes that ``source`` parameter will be passed If ``True``, denotes that ``source`` parameter will be passed
to the stdin of ffmpeg. Defaults to ``False``. to the stdin of ffmpeg. Defaults to ``False``.
@ -392,6 +398,12 @@ class FFmpegOpusAudio(FFmpegAudio):
executable: :class:`str` executable: :class:`str`
The executable name (and path) to use. Defaults to ``ffmpeg``. The executable name (and path) to use. Defaults to ``ffmpeg``.
.. warning::
Since this class spawns a subprocess, care should be taken to not
pass in an arbitrary executable name when using this parameter.
pipe: :class:`bool` pipe: :class:`bool`
If ``True``, denotes that ``source`` parameter will be passed If ``True``, denotes that ``source`` parameter will be passed
to the stdin of ffmpeg. Defaults to ``False``. to the stdin of ffmpeg. Defaults to ``False``.
@ -751,7 +763,8 @@ class AudioPlayer(threading.Thread):
delay = max(0, self.DELAY + (next_time - time.perf_counter())) delay = max(0, self.DELAY + (next_time - time.perf_counter()))
time.sleep(delay) time.sleep(delay)
self.send_silence() if client.is_connected():
self.send_silence()
def run(self) -> None: def run(self) -> None:
try: try:

576
discord/poll.py

@ -0,0 +1,576 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import Optional, List, TYPE_CHECKING, Union, AsyncIterator, Dict
import datetime
from .enums import PollLayoutType, try_enum
from . import utils
from .emoji import PartialEmoji, Emoji
from .user import User
from .object import Object
from .errors import ClientException
if TYPE_CHECKING:
from typing_extensions import Self
from .message import Message
from .abc import Snowflake
from .state import ConnectionState
from .member import Member
from .types.poll import (
PollCreate as PollCreatePayload,
PollMedia as PollMediaPayload,
PollAnswerCount as PollAnswerCountPayload,
Poll as PollPayload,
PollAnswerWithID as PollAnswerWithIDPayload,
PollResult as PollResultPayload,
PollAnswer as PollAnswerPayload,
)
__all__ = (
'Poll',
'PollAnswer',
'PollMedia',
)
MISSING = utils.MISSING
PollMediaEmoji = Union[PartialEmoji, Emoji, str]
class PollMedia:
"""Represents the poll media for a poll item.
.. versionadded:: 2.4
Attributes
----------
text: :class:`str`
The displayed text.
emoji: Optional[Union[:class:`PartialEmoji`, :class:`Emoji`]]
The attached emoji for this media. This is only valid for poll answers.
"""
__slots__ = ('text', 'emoji')
def __init__(self, /, text: str, emoji: Optional[PollMediaEmoji] = None) -> None:
self.text: str = text
self.emoji: Optional[Union[PartialEmoji, Emoji]] = PartialEmoji.from_str(emoji) if isinstance(emoji, str) else emoji
def __repr__(self) -> str:
return f'<PollMedia text={self.text!r} emoji={self.emoji!r}>'
def to_dict(self) -> PollMediaPayload:
payload: PollMediaPayload = {'text': self.text}
if self.emoji is not None:
payload['emoji'] = self.emoji._to_partial().to_dict()
return payload
@classmethod
def from_dict(cls, *, data: PollMediaPayload) -> Self:
emoji = data.get('emoji')
if emoji:
return cls(text=data['text'], emoji=PartialEmoji.from_dict(emoji))
return cls(text=data['text'])
class PollAnswer:
"""Represents a poll's answer.
.. container:: operations
.. describe:: str(x)
Returns this answer's text, if any.
.. versionadded:: 2.4
Attributes
----------
id: :class:`int`
The ID of this answer.
media: :class:`PollMedia`
The display data for this answer.
self_voted: :class:`bool`
Whether the current user has voted to this answer or not.
"""
__slots__ = ('media', 'id', '_state', '_message', '_vote_count', 'self_voted', '_poll')
def __init__(
self,
*,
message: Optional[Message],
poll: Poll,
data: PollAnswerWithIDPayload,
) -> None:
self.media: PollMedia = PollMedia.from_dict(data=data['poll_media'])
self.id: int = int(data['answer_id'])
self._message: Optional[Message] = message
self._state: Optional[ConnectionState] = message._state if message else None
self._vote_count: int = 0
self.self_voted: bool = False
self._poll: Poll = poll
def _handle_vote_event(self, added: bool, self_voted: bool) -> None:
if added:
self._vote_count += 1
else:
self._vote_count -= 1
self.self_voted = self_voted
def _update_with_results(self, payload: PollAnswerCountPayload) -> None:
self._vote_count = int(payload['count'])
self.self_voted = payload['me_voted']
def __str__(self) -> str:
return self.media.text
def __repr__(self) -> str:
return f'<PollAnswer id={self.id} media={self.media!r}>'
@classmethod
def from_params(
cls,
id: int,
text: str,
emoji: Optional[PollMediaEmoji] = None,
*,
poll: Poll,
message: Optional[Message],
) -> Self:
poll_media: PollMediaPayload = {'text': text}
if emoji is not None:
emoji = PartialEmoji.from_str(emoji) if isinstance(emoji, str) else emoji._to_partial()
emoji_data = emoji.to_dict()
# No need to remove animated key as it will be ignored
poll_media['emoji'] = emoji_data
payload: PollAnswerWithIDPayload = {'answer_id': id, 'poll_media': poll_media}
return cls(data=payload, message=message, poll=poll)
@property
def text(self) -> str:
""":class:`str`: Returns this answer's displayed text."""
return self.media.text
@property
def emoji(self) -> Optional[Union[PartialEmoji, Emoji]]:
"""Optional[Union[:class:`Emoji`, :class:`PartialEmoji`]]: Returns this answer's displayed
emoji, if any.
"""
return self.media.emoji
@property
def vote_count(self) -> int:
""":class:`int`: Returns an approximate count of votes for this answer.
If the poll is finished, the count is exact.
"""
return self._vote_count
@property
def poll(self) -> Poll:
""":class:`Poll`: Returns the parent poll of this answer."""
return self._poll
def _to_dict(self) -> PollAnswerPayload:
return {
'poll_media': self.media.to_dict(),
}
async def voters(
self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None
) -> AsyncIterator[Union[User, Member]]:
"""Returns an :term:`asynchronous iterator` representing the users that have voted on this answer.
The ``after`` parameter must represent a user
and meet the :class:`abc.Snowflake` abc.
This can only be called when the parent poll was sent to a message.
Examples
--------
Usage ::
async for voter in poll_answer.voters():
print(f'{voter} has voted for {poll_answer}!')
Flattening into a list: ::
voters = [voter async for voter in poll_answer.voters()]
# voters is now a list of User
Parameters
----------
limit: Optional[:class:`int`]
The maximum number of results to return.
If not provided, returns all the users who
voted on this poll answer.
after: Optional[:class:`abc.Snowflake`]
For pagination, voters are sorted by member.
Raises
------
HTTPException
Retrieving the users failed.
Yields
------
Union[:class:`User`, :class:`Member`]
The member (if retrievable) or the user that has voted
on this poll answer. The case where it can be a :class:`Member`
is in a guild message context. Sometimes it can be a :class:`User`
if the member has left the guild or if the member is not cached.
"""
if not self._message or not self._state: # Make type checker happy
raise ClientException('You cannot fetch users to a poll not sent with a message')
if limit is None:
if not self._message.poll:
limit = 100
else:
limit = self.vote_count or 100
while limit > 0:
retrieve = min(limit, 100)
message = self._message
guild = self._message.guild
state = self._state
after_id = after.id if after else None
data = await state.http.get_poll_answer_voters(
message.channel.id, message.id, self.id, after=after_id, limit=retrieve
)
users = data['users']
if len(users) == 0:
# No more voters to fetch, terminate loop
break
limit -= len(users)
after = Object(id=int(users[-1]['id']))
if not guild or isinstance(guild, Object):
for raw_user in reversed(users):
yield User(state=self._state, data=raw_user)
continue
for raw_member in reversed(users):
member_id = int(raw_member['id'])
member = guild.get_member(member_id)
yield member or User(state=self._state, data=raw_member)
class Poll:
"""Represents a message's Poll.
.. versionadded:: 2.4
Parameters
----------
question: Union[:class:`PollMedia`, :class:`str`]
The poll's displayed question. The text can be up to 300 characters.
duration: :class:`datetime.timedelta`
The duration of the poll. Duration must be in hours.
multiple: :class:`bool`
Whether users are allowed to select more than one answer.
Defaults to ``False``.
layout_type: :class:`PollLayoutType`
The layout type of the poll. Defaults to :attr:`PollLayoutType.default`.
"""
__slots__ = (
'multiple',
'_answers',
'duration',
'layout_type',
'_question_media',
'_message',
'_expiry',
'_finalized',
'_state',
)
def __init__(
self,
question: Union[PollMedia, str],
duration: datetime.timedelta,
*,
multiple: bool = False,
layout_type: PollLayoutType = PollLayoutType.default,
) -> None:
self._question_media: PollMedia = PollMedia(text=question, emoji=None) if isinstance(question, str) else question
self._answers: Dict[int, PollAnswer] = {}
self.duration: datetime.timedelta = duration
self.multiple: bool = multiple
self.layout_type: PollLayoutType = layout_type
# NOTE: These attributes are set manually when calling
# _from_data, so it should be ``None`` now.
self._message: Optional[Message] = None
self._state: Optional[ConnectionState] = None
self._finalized: bool = False
self._expiry: Optional[datetime.datetime] = None
def _update(self, message: Message) -> None:
self._state = message._state
self._message = message
if not message.poll:
return
# The message's poll contains the more up to date data.
self._expiry = message.poll.expires_at
self._finalized = message.poll._finalized
def _update_results(self, data: PollResultPayload) -> None:
self._finalized = data['is_finalized']
for count in data['answer_counts']:
answer = self.get_answer(int(count['id']))
if not answer:
continue
answer._update_with_results(count)
def _handle_vote(self, answer_id: int, added: bool, self_voted: bool = False):
answer = self.get_answer(answer_id)
if not answer:
return
answer._handle_vote_event(added, self_voted)
@classmethod
def _from_data(cls, *, data: PollPayload, message: Message, state: ConnectionState) -> Self:
multiselect = data.get('allow_multiselect', False)
layout_type = try_enum(PollLayoutType, data.get('layout_type', 1))
question_data = data.get('question')
question = question_data.get('text')
expiry = utils.parse_time(data['expiry']) # If obtained via API, then expiry is set.
duration = expiry - message.created_at
# self.created_at = message.created_at
# duration = self.created_at - expiry
if (duration.total_seconds() / 3600) > 168: # As the duration may exceed little milliseconds then we fix it
duration = datetime.timedelta(days=7)
self = cls(
duration=duration,
multiple=multiselect,
layout_type=layout_type,
question=question,
)
self._answers = {
int(answer['answer_id']): PollAnswer(data=answer, message=message, poll=self) for answer in data['answers']
}
self._message = message
self._state = state
self._expiry = expiry
try:
self._update_results(data['results'])
except KeyError:
pass
return self
def _to_dict(self) -> PollCreatePayload:
data: PollCreatePayload = {
'allow_multiselect': self.multiple,
'question': self._question_media.to_dict(),
'duration': self.duration.total_seconds() / 3600,
'layout_type': self.layout_type.value,
'answers': [answer._to_dict() for answer in self.answers],
}
return data
def __repr__(self) -> str:
return f"<Poll duration={self.duration} question=\"{self.question}\" answers={self.answers}>"
@property
def question(self) -> str:
""":class:`str`: Returns this poll's question string."""
return self._question_media.text
@property
def answers(self) -> List[PollAnswer]:
"""List[:class:`PollAnswer`]: Returns a read-only copy of the answers."""
return list(self._answers.values())
@property
def expires_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: A datetime object representing the poll expiry.
.. note::
This will **always** be ``None`` for stateless polls.
"""
return self._expiry
@property
def created_at(self) -> Optional[datetime.datetime]:
"""Optional[:class:`datetime.datetime`]: Returns the poll's creation time.
.. note::
This will **always** be ``None`` for stateless polls.
"""
if not self._message:
return
return self._message.created_at
@property
def message(self) -> Optional[Message]:
""":class:`Message`: The message this poll is from."""
return self._message
@property
def total_votes(self) -> int:
""":class:`int`: Returns the sum of all the answer votes."""
return sum([answer.vote_count for answer in self.answers])
def is_finalised(self) -> bool:
""":class:`bool`: Returns whether the poll has finalised.
This always returns ``False`` for stateless polls.
"""
return self._finalized
is_finalized = is_finalised
def copy(self) -> Self:
"""Returns a stateless copy of this poll.
This is meant to be used when you want to edit a stateful poll.
Returns
-------
:class:`Poll`
The copy of the poll.
"""
new = self.__class__(question=self.question, duration=self.duration)
# We want to return a stateless copy of the poll, so we should not
# override new._answers as our answers may contain a state
for answer in self.answers:
new.add_answer(text=answer.text, emoji=answer.emoji)
return new
def add_answer(
self,
*,
text: str,
emoji: Optional[Union[PartialEmoji, Emoji, str]] = None,
) -> Self:
"""Appends a new answer to this poll.
Parameters
----------
text: :class:`str`
The text label for this poll answer. Can be up to 55
characters.
emoji: Union[:class:`PartialEmoji`, :class:`Emoji`, :class:`str`]
The emoji to display along the text.
Raises
------
ClientException
Cannot append answers to a poll that is active.
Returns
-------
:class:`Poll`
This poll with the new answer appended. This allows fluent-style chaining.
"""
if self._message:
raise ClientException('Cannot append answers to a poll that is active')
answer = PollAnswer.from_params(id=len(self.answers) + 1, text=text, emoji=emoji, message=self._message, poll=self)
self._answers[answer.id] = answer
return self
def get_answer(
self,
/,
id: int,
) -> Optional[PollAnswer]:
"""Returns the answer with the provided ID or ``None`` if not found.
Parameters
----------
id: :class:`int`
The ID of the answer to get.
Returns
-------
Optional[:class:`PollAnswer`]
The answer.
"""
return self._answers.get(id)
async def end(self) -> Self:
"""|coro|
Ends the poll.
Raises
------
ClientException
This poll has no attached message.
HTTPException
Ending the poll failed.
Returns
-------
:class:`Poll`
The updated poll.
"""
if not self._message or not self._state: # Make type checker happy
raise ClientException('This poll has no attached message.')
self._message = await self._message.end_poll()
return self

62
discord/raw_models.py

@ -27,12 +27,14 @@ from __future__ import annotations
import datetime import datetime
from typing import TYPE_CHECKING, Literal, Optional, Set, List, Tuple, Union from typing import TYPE_CHECKING, Literal, Optional, Set, List, Tuple, Union
from .enums import ChannelType, try_enum from .enums import ChannelType, try_enum, ReactionType
from .utils import _get_as_snowflake from .utils import _get_as_snowflake
from .app_commands import AppCommandPermissions from .app_commands import AppCommandPermissions
from .colour import Colour from .colour import Colour
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Self
from .types.gateway import ( from .types.gateway import (
MessageDeleteEvent, MessageDeleteEvent,
MessageDeleteBulkEvent as BulkMessageDeleteEvent, MessageDeleteBulkEvent as BulkMessageDeleteEvent,
@ -47,6 +49,7 @@ if TYPE_CHECKING:
ThreadMembersUpdate, ThreadMembersUpdate,
TypingStartEvent, TypingStartEvent,
GuildMemberRemoveEvent, GuildMemberRemoveEvent,
PollVoteActionEvent,
) )
from .types.command import GuildApplicationCommandPermissions from .types.command import GuildApplicationCommandPermissions
from .message import Message from .message import Message
@ -75,6 +78,7 @@ __all__ = (
'RawTypingEvent', 'RawTypingEvent',
'RawMemberRemoveEvent', 'RawMemberRemoveEvent',
'RawAppCommandPermissionsUpdateEvent', 'RawAppCommandPermissionsUpdateEvent',
'RawPollVoteActionEvent',
) )
@ -158,7 +162,7 @@ class RawMessageUpdateEvent(_RawReprMixin):
.. versionadded:: 1.7 .. versionadded:: 1.7
data: :class:`dict` data: :class:`dict`
The raw data given by the :ddocs:`gateway <topics/gateway#message-update>` The raw data given by the :ddocs:`gateway <topics/gateway-events#message-update>`
cached_message: Optional[:class:`Message`] cached_message: Optional[:class:`Message`]
The cached message, if found in the internal message cache. Represents the message before The cached message, if found in the internal message cache. Represents the message before
it is modified by the data in :attr:`RawMessageUpdateEvent.data`. it is modified by the data in :attr:`RawMessageUpdateEvent.data`.
@ -217,6 +221,10 @@ class RawReactionActionEvent(_RawReprMixin):
and if ``event_type`` is ``REACTION_ADD``. and if ``event_type`` is ``REACTION_ADD``.
.. versionadded:: 2.0 .. versionadded:: 2.0
type: :class:`ReactionType`
The type of the reaction.
.. versionadded:: 2.4
""" """
__slots__ = ( __slots__ = (
@ -230,6 +238,7 @@ class RawReactionActionEvent(_RawReprMixin):
'message_author_id', 'message_author_id',
'burst', 'burst',
'burst_colours', 'burst_colours',
'type',
) )
def __init__(self, data: ReactionActionEvent, emoji: PartialEmoji, event_type: ReactionActionType) -> None: def __init__(self, data: ReactionActionEvent, emoji: PartialEmoji, event_type: ReactionActionType) -> None:
@ -242,6 +251,7 @@ class RawReactionActionEvent(_RawReprMixin):
self.message_author_id: Optional[int] = _get_as_snowflake(data, 'message_author_id') self.message_author_id: Optional[int] = _get_as_snowflake(data, 'message_author_id')
self.burst: bool = data.get('burst', False) self.burst: bool = data.get('burst', False)
self.burst_colours: List[Colour] = [Colour.from_str(c) for c in data.get('burst_colours', [])] self.burst_colours: List[Colour] = [Colour.from_str(c) for c in data.get('burst_colours', [])]
self.type: ReactionType = try_enum(ReactionType, data['type'])
try: try:
self.guild_id: Optional[int] = int(data['guild_id']) self.guild_id: Optional[int] = int(data['guild_id'])
@ -355,7 +365,7 @@ class RawThreadUpdateEvent(_RawReprMixin):
parent_id: :class:`int` parent_id: :class:`int`
The ID of the channel the thread belongs to. The ID of the channel the thread belongs to.
data: :class:`dict` data: :class:`dict`
The raw data given by the :ddocs:`gateway <topics/gateway#thread-update>` The raw data given by the :ddocs:`gateway <topics/gateway-events#thread-update>`
thread: Optional[:class:`discord.Thread`] thread: Optional[:class:`discord.Thread`]
The thread, if it could be found in the internal cache. The thread, if it could be found in the internal cache.
""" """
@ -399,6 +409,20 @@ class RawThreadDeleteEvent(_RawReprMixin):
self.parent_id: int = int(data['parent_id']) self.parent_id: int = int(data['parent_id'])
self.thread: Optional[Thread] = None self.thread: Optional[Thread] = None
@classmethod
def _from_thread(cls, thread: Thread) -> Self:
data: ThreadDeleteEvent = {
'id': thread.id,
'type': thread.type.value,
'guild_id': thread.guild.id,
'parent_id': thread.parent_id,
}
instance = cls(data)
instance.thread = thread
return instance
class RawThreadMembersUpdate(_RawReprMixin): class RawThreadMembersUpdate(_RawReprMixin):
"""Represents the payload for a :func:`on_raw_thread_member_remove` event. """Represents the payload for a :func:`on_raw_thread_member_remove` event.
@ -414,7 +438,7 @@ class RawThreadMembersUpdate(_RawReprMixin):
member_count: :class:`int` member_count: :class:`int`
The approximate number of members in the thread. This caps at 50. The approximate number of members in the thread. This caps at 50.
data: :class:`dict` data: :class:`dict`
The raw data given by the :ddocs:`gateway <topics/gateway#thread-members-update>`. The raw data given by the :ddocs:`gateway <topics/gateway-events#thread-members-update>`.
""" """
__slots__ = ('thread_id', 'guild_id', 'member_count', 'data') __slots__ = ('thread_id', 'guild_id', 'member_count', 'data')
@ -503,3 +527,33 @@ class RawAppCommandPermissionsUpdateEvent(_RawReprMixin):
self.permissions: List[AppCommandPermissions] = [ self.permissions: List[AppCommandPermissions] = [
AppCommandPermissions(data=perm, guild=self.guild, state=state) for perm in data['permissions'] AppCommandPermissions(data=perm, guild=self.guild, state=state) for perm in data['permissions']
] ]
class RawPollVoteActionEvent(_RawReprMixin):
"""Represents the payload for a :func:`on_raw_poll_vote_add` or :func:`on_raw_poll_vote_remove`
event.
.. versionadded:: 2.4
Attributes
----------
user_id: :class:`int`
The ID of the user that added or removed a vote.
channel_id: :class:`int`
The channel ID where the poll vote action took place.
message_id: :class:`int`
The message ID that contains the poll the user added or removed their vote on.
guild_id: Optional[:class:`int`]
The guild ID where the vote got added or removed, if applicable..
answer_id: :class:`int`
The poll answer's ID the user voted on.
"""
__slots__ = ('user_id', 'channel_id', 'message_id', 'guild_id', 'answer_id')
def __init__(self, data: PollVoteActionEvent) -> None:
self.user_id: int = int(data['user_id'])
self.channel_id: int = int(data['channel_id'])
self.message_id: int = int(data['message_id'])
self.guild_id: Optional[int] = _get_as_snowflake(data, 'guild_id')
self.answer_id: int = int(data['answer_id'])

17
discord/reaction.py

@ -27,6 +27,7 @@ from typing import TYPE_CHECKING, AsyncIterator, Union, Optional
from .user import User from .user import User
from .object import Object from .object import Object
from .enums import ReactionType
# fmt: off # fmt: off
__all__ = ( __all__ = (
@ -185,7 +186,7 @@ class Reaction:
await self.message.clear_reaction(self.emoji) await self.message.clear_reaction(self.emoji)
async def users( async def users(
self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None self, *, limit: Optional[int] = None, after: Optional[Snowflake] = None, type: Optional[ReactionType] = None
) -> AsyncIterator[Union[Member, User]]: ) -> AsyncIterator[Union[Member, User]]:
"""Returns an :term:`asynchronous iterator` representing the users that have reacted to the message. """Returns an :term:`asynchronous iterator` representing the users that have reacted to the message.
@ -220,6 +221,11 @@ class Reaction:
reacted to the message. reacted to the message.
after: Optional[:class:`abc.Snowflake`] after: Optional[:class:`abc.Snowflake`]
For pagination, reactions are sorted by member. For pagination, reactions are sorted by member.
type: Optional[:class:`ReactionType`]
The type of reaction to return users from.
If not provided, Discord only returns users of reactions with type ``normal``.
.. versionadded:: 2.4
Raises Raises
-------- --------
@ -251,7 +257,14 @@ class Reaction:
state = message._state state = message._state
after_id = after.id if after else None after_id = after.id if after else None
data = await state.http.get_reaction_users(message.channel.id, message.id, emoji, retrieve, after=after_id) data = await state.http.get_reaction_users(
message.channel.id,
message.id,
emoji,
retrieve,
after=after_id,
type=type.value if type is not None else None,
)
if data: if data:
limit -= len(data) limit -= len(data)

30
discord/shard.py

@ -326,6 +326,11 @@ class AutoShardedClient(Client):
------------ ------------
shard_ids: Optional[List[:class:`int`]] shard_ids: Optional[List[:class:`int`]]
An optional list of shard_ids to launch the shards with. An optional list of shard_ids to launch the shards with.
shard_connect_timeout: Optional[:class:`float`]
The maximum number of seconds to wait before timing out when launching a shard.
Defaults to 180 seconds.
.. versionadded:: 2.4
""" """
if TYPE_CHECKING: if TYPE_CHECKING:
@ -334,6 +339,8 @@ class AutoShardedClient(Client):
def __init__(self, *args: Any, intents: Intents, **kwargs: Any) -> None: def __init__(self, *args: Any, intents: Intents, **kwargs: Any) -> None:
kwargs.pop('shard_id', None) kwargs.pop('shard_id', None)
self.shard_ids: Optional[List[int]] = kwargs.pop('shard_ids', None) self.shard_ids: Optional[List[int]] = kwargs.pop('shard_ids', None)
self.shard_connect_timeout: Optional[float] = kwargs.pop('shard_connect_timeout', 180.0)
super().__init__(*args, intents=intents, **kwargs) super().__init__(*args, intents=intents, **kwargs)
if self.shard_ids is not None: if self.shard_ids is not None:
@ -411,7 +418,7 @@ class AutoShardedClient(Client):
async def launch_shard(self, gateway: yarl.URL, shard_id: int, *, initial: bool = False) -> None: async def launch_shard(self, gateway: yarl.URL, shard_id: int, *, initial: bool = False) -> None:
try: try:
coro = DiscordWebSocket.from_client(self, initial=initial, gateway=gateway, shard_id=shard_id) coro = DiscordWebSocket.from_client(self, initial=initial, gateway=gateway, shard_id=shard_id)
ws = await asyncio.wait_for(coro, timeout=180.0) ws = await asyncio.wait_for(coro, timeout=self.shard_connect_timeout)
except Exception: except Exception:
_log.exception('Failed to connect for shard_id: %s. Retrying...', shard_id) _log.exception('Failed to connect for shard_id: %s. Retrying...', shard_id)
await asyncio.sleep(5.0) await asyncio.sleep(5.0)
@ -474,18 +481,21 @@ class AutoShardedClient(Client):
Closes the connection to Discord. Closes the connection to Discord.
""" """
if self.is_closed(): if self._closing_task:
return return await self._closing_task
async def _close():
await self._connection.close()
self._closed = True to_close = [asyncio.ensure_future(shard.close(), loop=self.loop) for shard in self.__shards.values()]
await self._connection.close() if to_close:
await asyncio.wait(to_close)
to_close = [asyncio.ensure_future(shard.close(), loop=self.loop) for shard in self.__shards.values()] await self.http.close()
if to_close: self.__queue.put_nowait(EventItem(EventType.clean_close, None, None))
await asyncio.wait(to_close)
await self.http.close() self._closing_task = asyncio.create_task(_close())
self.__queue.put_nowait(EventItem(EventType.clean_close, None, None)) await self._closing_task
async def change_presence( async def change_presence(
self, self,

24
discord/sku.py

@ -126,6 +126,8 @@ class Entitlement:
A UTC date which entitlement is no longer valid. Not present when using test entitlements. A UTC date which entitlement is no longer valid. Not present when using test entitlements.
guild_id: Optional[:class:`int`] guild_id: Optional[:class:`int`]
The ID of the guild that is granted access to the entitlement The ID of the guild that is granted access to the entitlement
consumed: :class:`bool`
For consumable items, whether the entitlement has been consumed.
""" """
__slots__ = ( __slots__ = (
@ -139,6 +141,7 @@ class Entitlement:
'starts_at', 'starts_at',
'ends_at', 'ends_at',
'guild_id', 'guild_id',
'consumed',
) )
def __init__(self, state: ConnectionState, data: EntitlementPayload): def __init__(self, state: ConnectionState, data: EntitlementPayload):
@ -152,6 +155,7 @@ class Entitlement:
self.starts_at: Optional[datetime] = utils.parse_time(data.get('starts_at', None)) self.starts_at: Optional[datetime] = utils.parse_time(data.get('starts_at', None))
self.ends_at: Optional[datetime] = utils.parse_time(data.get('ends_at', None)) self.ends_at: Optional[datetime] = utils.parse_time(data.get('ends_at', None))
self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id') self.guild_id: Optional[int] = utils._get_as_snowflake(data, 'guild_id')
self.consumed: bool = data.get('consumed', False)
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Entitlement id={self.id} type={self.type!r} user_id={self.user_id}>' return f'<Entitlement id={self.id} type={self.type!r} user_id={self.user_id}>'
@ -179,6 +183,26 @@ class Entitlement:
return False return False
return utils.utcnow() >= self.ends_at return utils.utcnow() >= self.ends_at
async def consume(self) -> None:
"""|coro|
Marks a one-time purchase entitlement as consumed.
Raises
-------
MissingApplicationID
The application ID could not be found.
NotFound
The entitlement could not be found.
HTTPException
Consuming the entitlement failed.
"""
if self.application_id is None:
raise MissingApplicationID
await self._state.http.consume_entitlement(self.application_id, self.id)
async def delete(self) -> None: async def delete(self) -> None:
"""|coro| """|coro|

93
discord/state.py

@ -89,6 +89,7 @@ if TYPE_CHECKING:
from .ui.item import Item from .ui.item import Item
from .ui.dynamic import DynamicItem from .ui.dynamic import DynamicItem
from .app_commands import CommandTree, Translator from .app_commands import CommandTree, Translator
from .poll import Poll
from .types.automod import AutoModerationRule, AutoModerationActionExecution from .types.automod import AutoModerationRule, AutoModerationActionExecution
from .types.snowflake import Snowflake from .types.snowflake import Snowflake
@ -110,12 +111,14 @@ class ChunkRequest:
def __init__( def __init__(
self, self,
guild_id: int, guild_id: int,
shard_id: int,
loop: asyncio.AbstractEventLoop, loop: asyncio.AbstractEventLoop,
resolver: Callable[[int], Any], resolver: Callable[[int], Any],
*, *,
cache: bool = True, cache: bool = True,
) -> None: ) -> None:
self.guild_id: int = guild_id self.guild_id: int = guild_id
self.shard_id: int = shard_id
self.resolver: Callable[[int], Any] = resolver self.resolver: Callable[[int], Any] = resolver
self.loop: asyncio.AbstractEventLoop = loop self.loop: asyncio.AbstractEventLoop = loop
self.cache: bool = cache self.cache: bool = cache
@ -315,6 +318,16 @@ class ConnectionState(Generic[ClientT]):
for key in removed: for key in removed:
del self._chunk_requests[key] del self._chunk_requests[key]
def clear_chunk_requests(self, shard_id: int | None) -> None:
removed = []
for key, request in self._chunk_requests.items():
if shard_id is None or request.shard_id == shard_id:
request.done()
removed.append(key)
for key in removed:
del self._chunk_requests[key]
def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None: def call_handlers(self, key: str, *args: Any, **kwargs: Any) -> None:
try: try:
func = self.handlers[key] func = self.handlers[key]
@ -417,8 +430,8 @@ class ConnectionState(Generic[ClientT]):
# the keys of self._guilds are ints # the keys of self._guilds are ints
return self._guilds.get(guild_id) # type: ignore return self._guilds.get(guild_id) # type: ignore
def _get_or_create_unavailable_guild(self, guild_id: int) -> Guild: def _get_or_create_unavailable_guild(self, guild_id: int, *, data: Optional[Dict[str, Any]] = None) -> Guild:
return self._guilds.get(guild_id) or Guild._create_unavailable(state=self, guild_id=guild_id) return self._guilds.get(guild_id) or Guild._create_unavailable(state=self, guild_id=guild_id, data=data)
def _add_guild(self, guild: Guild) -> None: def _add_guild(self, guild: Guild) -> None:
self._guilds[guild.id] = guild self._guilds[guild.id] = guild
@ -497,6 +510,12 @@ class ConnectionState(Generic[ClientT]):
def _get_message(self, msg_id: Optional[int]) -> Optional[Message]: def _get_message(self, msg_id: Optional[int]) -> Optional[Message]:
return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None return utils.find(lambda m: m.id == msg_id, reversed(self._messages)) if self._messages else None
def _get_poll(self, msg_id: Optional[int]) -> Optional[Poll]:
message = self._get_message(msg_id)
if not message:
return
return message.poll
def _add_guild_from_data(self, data: GuildPayload) -> Guild: def _add_guild_from_data(self, data: GuildPayload) -> Guild:
guild = Guild(data=data, state=self) guild = Guild(data=data, state=self)
self._add_guild(guild) self._add_guild(guild)
@ -521,6 +540,13 @@ class ConnectionState(Generic[ClientT]):
return channel or PartialMessageable(state=self, guild_id=guild_id, id=channel_id), guild return channel or PartialMessageable(state=self, guild_id=guild_id, id=channel_id), guild
def _update_poll_counts(self, message: Message, answer_id: int, added: bool, self_voted: bool = False) -> Optional[Poll]:
poll = message.poll
if not poll:
return
poll._handle_vote(answer_id, added, self_voted)
return poll
async def chunker( async def chunker(
self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, nonce: Optional[str] = None self, guild_id: int, query: str = '', limit: int = 0, presences: bool = False, *, nonce: Optional[str] = None
) -> None: ) -> None:
@ -535,7 +561,7 @@ class ConnectionState(Generic[ClientT]):
if ws is None: if ws is None:
raise RuntimeError('Somehow do not have a websocket for this guild_id') raise RuntimeError('Somehow do not have a websocket for this guild_id')
request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache) request = ChunkRequest(guild.id, guild.shard_id, self.loop, self._get_guild, cache=cache)
self._chunk_requests[request.nonce] = request self._chunk_requests[request.nonce] = request
try: try:
@ -602,6 +628,7 @@ class ConnectionState(Generic[ClientT]):
self._ready_state: asyncio.Queue[Guild] = asyncio.Queue() self._ready_state: asyncio.Queue[Guild] = asyncio.Queue()
self.clear(views=False) self.clear(views=False)
self.clear_chunk_requests(None)
self.user = user = ClientUser(state=self, data=data['user']) self.user = user = ClientUser(state=self, data=data['user'])
self._users[user.id] = user # type: ignore self._users[user.id] = user # type: ignore
@ -818,6 +845,12 @@ class ConnectionState(Generic[ClientT]):
guild._scheduled_events.pop(s.id) guild._scheduled_events.pop(s.id)
self.dispatch('scheduled_event_delete', s) self.dispatch('scheduled_event_delete', s)
threads = guild._remove_threads_by_channel(channel_id)
for thread in threads:
self.dispatch('thread_delete', thread)
self.dispatch('raw_thread_delete', RawThreadDeleteEvent._from_thread(thread))
def parse_channel_update(self, data: gw.ChannelUpdateEvent) -> None: def parse_channel_update(self, data: gw.ChannelUpdateEvent) -> None:
channel_type = try_enum(ChannelType, data.get('type')) channel_type = try_enum(ChannelType, data.get('type'))
channel_id = int(data['id']) channel_id = int(data['id'])
@ -1204,7 +1237,9 @@ class ConnectionState(Generic[ClientT]):
cache = cache or self.member_cache_flags.joined cache = cache or self.member_cache_flags.joined
request = self._chunk_requests.get(guild.id) request = self._chunk_requests.get(guild.id)
if request is None: if request is None:
self._chunk_requests[guild.id] = request = ChunkRequest(guild.id, self.loop, self._get_guild, cache=cache) self._chunk_requests[guild.id] = request = ChunkRequest(
guild.id, guild.shard_id, self.loop, self._get_guild, cache=cache
)
await self.chunker(guild.id, nonce=request.nonce) await self.chunker(guild.id, nonce=request.nonce)
if wait: if wait:
@ -1571,7 +1606,8 @@ class ConnectionState(Generic[ClientT]):
if channel is not None: if channel is not None:
if isinstance(channel, DMChannel): if isinstance(channel, DMChannel):
channel.recipient = raw.user if raw.user is not None and raw.user not in channel.recipients:
channel.recipients.append(raw.user)
elif guild is not None: elif guild is not None:
raw.user = guild.get_member(raw.user_id) raw.user = guild.get_member(raw.user_id)
@ -1597,6 +1633,52 @@ class ConnectionState(Generic[ClientT]):
entitlement = Entitlement(data=data, state=self) entitlement = Entitlement(data=data, state=self)
self.dispatch('entitlement_delete', entitlement) self.dispatch('entitlement_delete', entitlement)
def parse_message_poll_vote_add(self, data: gw.PollVoteActionEvent) -> None:
raw = RawPollVoteActionEvent(data)
self.dispatch('raw_poll_vote_add', raw)
message = self._get_message(raw.message_id)
guild = self._get_guild(raw.guild_id)
if guild:
user = guild.get_member(raw.user_id)
else:
user = self.get_user(raw.user_id)
if message and user:
poll = self._update_poll_counts(message, raw.answer_id, True, raw.user_id == self.self_id)
if not poll:
_log.warning(
'POLL_VOTE_ADD referencing message with ID: %s does not have a poll. Discarding.', raw.message_id
)
return
self.dispatch('poll_vote_add', user, poll.get_answer(raw.answer_id))
def parse_message_poll_vote_remove(self, data: gw.PollVoteActionEvent) -> None:
raw = RawPollVoteActionEvent(data)
self.dispatch('raw_poll_vote_remove', raw)
message = self._get_message(raw.message_id)
guild = self._get_guild(raw.guild_id)
if guild:
user = guild.get_member(raw.user_id)
else:
user = self.get_user(raw.user_id)
if message and user:
poll = self._update_poll_counts(message, raw.answer_id, False, raw.user_id == self.self_id)
if not poll:
_log.warning(
'POLL_VOTE_REMOVE referencing message with ID: %s does not have a poll. Discarding.', raw.message_id
)
return
self.dispatch('poll_vote_remove', user, poll.get_answer(raw.answer_id))
def _get_reaction_user(self, channel: MessageableChannel, user_id: int) -> Optional[Union[User, Member]]: def _get_reaction_user(self, channel: MessageableChannel, user_id: int) -> Optional[Union[User, Member]]:
if isinstance(channel, (TextChannel, Thread, VoiceChannel)): if isinstance(channel, (TextChannel, Thread, VoiceChannel)):
return channel.guild.get_member(user_id) return channel.guild.get_member(user_id)
@ -1751,6 +1833,7 @@ class AutoShardedConnectionState(ConnectionState[ClientT]):
if shard_id in self._ready_tasks: if shard_id in self._ready_tasks:
self._ready_tasks[shard_id].cancel() self._ready_tasks[shard_id].cancel()
self.clear_chunk_requests(shard_id)
if shard_id not in self._ready_states: if shard_id not in self._ready_states:
self._ready_states[shard_id] = asyncio.Queue() self._ready_states[shard_id] = asyncio.Queue()

5
discord/sticker.py

@ -277,7 +277,10 @@ class Sticker(_StickerTag):
self.name: str = data['name'] self.name: str = data['name']
self.description: str = data['description'] self.description: str = data['description']
self.format: StickerFormatType = try_enum(StickerFormatType, data['format_type']) self.format: StickerFormatType = try_enum(StickerFormatType, data['format_type'])
self.url: str = f'{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}' if self.format is StickerFormatType.gif:
self.url: str = f'https://media.discordapp.net/stickers/{self.id}.gif'
else:
self.url: str = f'{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}'
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Sticker id={self.id} name={self.name!r}>' return f'<Sticker id={self.id} name={self.name!r}>'

16
discord/threads.py

@ -121,6 +121,10 @@ class Thread(Messageable, Hashable):
This is always ``True`` for public threads. This is always ``True`` for public threads.
archiver_id: Optional[:class:`int`] archiver_id: Optional[:class:`int`]
The user's ID that archived this thread. The user's ID that archived this thread.
.. note::
Due to an API change, the ``archiver_id`` will always be ``None`` and can only be obtained via the audit log.
auto_archive_duration: :class:`int` auto_archive_duration: :class:`int`
The duration in minutes until the thread is automatically hidden from the channel list. The duration in minutes until the thread is automatically hidden from the channel list.
Usually a value of 60, 1440, 4320 and 10080. Usually a value of 60, 1440, 4320 and 10080.
@ -846,13 +850,21 @@ class Thread(Messageable, Hashable):
members = await self._state.http.get_thread_members(self.id) members = await self._state.http.get_thread_members(self.id)
return [ThreadMember(parent=self, data=data) for data in members] return [ThreadMember(parent=self, data=data) for data in members]
async def delete(self) -> None: async def delete(self, *, reason: Optional[str] = None) -> None:
"""|coro| """|coro|
Deletes this thread. Deletes this thread.
You must have :attr:`~Permissions.manage_threads` to delete threads. You must have :attr:`~Permissions.manage_threads` to delete threads.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this thread.
Shows up on the audit log.
.. versionadded:: 2.4
Raises Raises
------- -------
Forbidden Forbidden
@ -860,7 +872,7 @@ class Thread(Messageable, Hashable):
HTTPException HTTPException
Deleting the thread failed. Deleting the thread failed.
""" """
await self._state.http.delete_channel(self.id) await self._state.http.delete_channel(self.id, reason=reason)
def get_partial_message(self, message_id: int, /) -> PartialMessage: def get_partial_message(self, message_id: int, /) -> PartialMessage:
"""Creates a :class:`PartialMessage` from the message ID. """Creates a :class:`PartialMessage` from the message ID.

4
discord/types/command.py

@ -29,9 +29,11 @@ from typing_extensions import NotRequired, Required
from .channel import ChannelType from .channel import ChannelType
from .snowflake import Snowflake from .snowflake import Snowflake
from .interactions import InteractionContextType
ApplicationCommandType = Literal[1, 2, 3] ApplicationCommandType = Literal[1, 2, 3]
ApplicationCommandOptionType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] ApplicationCommandOptionType = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
ApplicationIntegrationType = Literal[0, 1]
class _BaseApplicationCommandOption(TypedDict): class _BaseApplicationCommandOption(TypedDict):
@ -141,6 +143,8 @@ class _BaseApplicationCommand(TypedDict):
id: Snowflake id: Snowflake
application_id: Snowflake application_id: Snowflake
name: str name: str
contexts: List[InteractionContextType]
integration_types: List[ApplicationIntegrationType]
dm_permission: NotRequired[Optional[bool]] dm_permission: NotRequired[Optional[bool]]
default_member_permissions: NotRequired[Optional[str]] default_member_permissions: NotRequired[Optional[str]]
nsfw: NotRequired[bool] nsfw: NotRequired[bool]

3
discord/types/components.py

@ -31,7 +31,7 @@ from .emoji import PartialEmoji
from .channel import ChannelType from .channel import ChannelType
ComponentType = Literal[1, 2, 3, 4] ComponentType = Literal[1, 2, 3, 4]
ButtonStyle = Literal[1, 2, 3, 4, 5] ButtonStyle = Literal[1, 2, 3, 4, 5, 6]
TextStyle = Literal[1, 2] TextStyle = Literal[1, 2]
DefaultValueType = Literal['user', 'role', 'channel'] DefaultValueType = Literal['user', 'role', 'channel']
@ -49,6 +49,7 @@ class ButtonComponent(TypedDict):
disabled: NotRequired[bool] disabled: NotRequired[bool]
emoji: NotRequired[PartialEmoji] emoji: NotRequired[PartialEmoji]
label: NotRequired[str] label: NotRequired[str]
sku_id: NotRequired[str]
class SelectOption(TypedDict): class SelectOption(TypedDict):

15
discord/types/gateway.py

@ -37,11 +37,11 @@ from .invite import InviteTargetType
from .emoji import Emoji, PartialEmoji from .emoji import Emoji, PartialEmoji
from .member import MemberWithUser from .member import MemberWithUser
from .snowflake import Snowflake from .snowflake import Snowflake
from .message import Message from .message import Message, ReactionType
from .sticker import GuildSticker from .sticker import GuildSticker
from .appinfo import GatewayAppInfo, PartialAppInfo from .appinfo import GatewayAppInfo, PartialAppInfo
from .guild import Guild, UnavailableGuild from .guild import Guild, UnavailableGuild
from .user import User from .user import User, AvatarDecorationData
from .threads import Thread, ThreadMember from .threads import Thread, ThreadMember
from .scheduled_event import GuildScheduledEvent from .scheduled_event import GuildScheduledEvent
from .audit_log import AuditLogEntry from .audit_log import AuditLogEntry
@ -104,6 +104,7 @@ class MessageReactionAddEvent(TypedDict):
message_author_id: NotRequired[Snowflake] message_author_id: NotRequired[Snowflake]
burst: bool burst: bool
burst_colors: NotRequired[List[str]] burst_colors: NotRequired[List[str]]
type: ReactionType
class MessageReactionRemoveEvent(TypedDict): class MessageReactionRemoveEvent(TypedDict):
@ -113,6 +114,7 @@ class MessageReactionRemoveEvent(TypedDict):
emoji: PartialEmoji emoji: PartialEmoji
guild_id: NotRequired[Snowflake] guild_id: NotRequired[Snowflake]
burst: bool burst: bool
type: ReactionType
class MessageReactionRemoveAllEvent(TypedDict): class MessageReactionRemoveAllEvent(TypedDict):
@ -228,6 +230,7 @@ class GuildMemberUpdateEvent(TypedDict):
mute: NotRequired[bool] mute: NotRequired[bool]
pending: NotRequired[bool] pending: NotRequired[bool]
communication_disabled_until: NotRequired[str] communication_disabled_until: NotRequired[str]
avatar_decoration_data: NotRequired[AvatarDecorationData]
class GuildEmojisUpdateEvent(TypedDict): class GuildEmojisUpdateEvent(TypedDict):
@ -351,3 +354,11 @@ class GuildAuditLogEntryCreate(AuditLogEntry):
EntitlementCreateEvent = EntitlementUpdateEvent = EntitlementDeleteEvent = Entitlement EntitlementCreateEvent = EntitlementUpdateEvent = EntitlementDeleteEvent = Entitlement
class PollVoteActionEvent(TypedDict):
user_id: Snowflake
channel_id: Snowflake
message_id: Snowflake
guild_id: NotRequired[Snowflake]
answer_id: int

11
discord/types/guild.py

@ -49,6 +49,11 @@ class UnavailableGuild(TypedDict):
unavailable: NotRequired[bool] unavailable: NotRequired[bool]
class IncidentData(TypedDict):
invites_disabled_until: NotRequired[Optional[str]]
dms_disabled_until: NotRequired[Optional[str]]
DefaultMessageNotificationLevel = Literal[0, 1] DefaultMessageNotificationLevel = Literal[0, 1]
ExplicitContentFilterLevel = Literal[0, 1, 2] ExplicitContentFilterLevel = Literal[0, 1, 2]
MFALevel = Literal[0, 1] MFALevel = Literal[0, 1]
@ -97,6 +102,7 @@ class _BaseGuildPreview(UnavailableGuild):
stickers: List[GuildSticker] stickers: List[GuildSticker]
features: List[GuildFeature] features: List[GuildFeature]
description: Optional[str] description: Optional[str]
incidents_data: Optional[IncidentData]
class _GuildPreviewUnique(TypedDict): class _GuildPreviewUnique(TypedDict):
@ -179,3 +185,8 @@ class _RolePositionRequired(TypedDict):
class RolePositionUpdate(_RolePositionRequired, total=False): class RolePositionUpdate(_RolePositionRequired, total=False):
position: Optional[Snowflake] position: Optional[Snowflake]
class BulkBanUserResponse(TypedDict):
banned_users: Optional[List[Snowflake]]
failed_users: Optional[List[Snowflake]]

22
discord/types/interactions.py

@ -35,12 +35,15 @@ from .message import Attachment
from .role import Role from .role import Role
from .snowflake import Snowflake from .snowflake import Snowflake
from .user import User from .user import User
from .guild import GuildFeature
if TYPE_CHECKING: if TYPE_CHECKING:
from .message import Message from .message import Message
InteractionType = Literal[1, 2, 3, 4, 5] InteractionType = Literal[1, 2, 3, 4, 5]
InteractionContextType = Literal[0, 1, 2]
InteractionInstallationType = Literal[0, 1]
class _BasePartialChannel(TypedDict): class _BasePartialChannel(TypedDict):
@ -68,6 +71,12 @@ class ResolvedData(TypedDict, total=False):
attachments: Dict[str, Attachment] attachments: Dict[str, Attachment]
class PartialInteractionGuild(TypedDict):
id: Snowflake
locale: str
features: List[GuildFeature]
class _BaseApplicationCommandInteractionDataOption(TypedDict): class _BaseApplicationCommandInteractionDataOption(TypedDict):
name: str name: str
@ -204,6 +213,7 @@ class _BaseInteraction(TypedDict):
token: str token: str
version: Literal[1] version: Literal[1]
guild_id: NotRequired[Snowflake] guild_id: NotRequired[Snowflake]
guild: NotRequired[PartialInteractionGuild]
channel_id: NotRequired[Snowflake] channel_id: NotRequired[Snowflake]
channel: Union[GuildChannel, InteractionDMChannel, GroupDMChannel] channel: Union[GuildChannel, InteractionDMChannel, GroupDMChannel]
app_permissions: NotRequired[str] app_permissions: NotRequired[str]
@ -211,6 +221,8 @@ class _BaseInteraction(TypedDict):
guild_locale: NotRequired[str] guild_locale: NotRequired[str]
entitlement_sku_ids: NotRequired[List[Snowflake]] entitlement_sku_ids: NotRequired[List[Snowflake]]
entitlements: NotRequired[List[Entitlement]] entitlements: NotRequired[List[Entitlement]]
authorizing_integration_owners: Dict[Literal['0', '1'], Snowflake]
context: NotRequired[InteractionContextType]
class PingInteraction(_BaseInteraction): class PingInteraction(_BaseInteraction):
@ -241,3 +253,13 @@ class MessageInteraction(TypedDict):
name: str name: str
user: User user: User
member: NotRequired[Member] member: NotRequired[Member]
class MessageInteractionMetadata(TypedDict):
id: Snowflake
type: InteractionType
user: User
authorizing_integration_owners: Dict[Literal['0', '1'], Snowflake]
original_response_message_id: NotRequired[Snowflake]
interacted_message_id: NotRequired[Snowflake]
triggering_interaction_metadata: NotRequired[MessageInteractionMetadata]

2
discord/types/invite.py

@ -35,6 +35,7 @@ from .user import PartialUser
from .appinfo import PartialAppInfo from .appinfo import PartialAppInfo
InviteTargetType = Literal[1, 2] InviteTargetType = Literal[1, 2]
InviteType = Literal[0, 1, 2]
class _InviteMetadata(TypedDict, total=False): class _InviteMetadata(TypedDict, total=False):
@ -63,6 +64,7 @@ class Invite(IncompleteInvite, total=False):
target_type: InviteTargetType target_type: InviteTargetType
target_application: PartialAppInfo target_application: PartialAppInfo
guild_scheduled_event: GuildScheduledEvent guild_scheduled_event: GuildScheduledEvent
type: InviteType
class InviteWithCounts(Invite, _GuildPreviewUnique): class InviteWithCounts(Invite, _GuildPreviewUnique):

5
discord/types/member.py

@ -24,7 +24,8 @@ DEALINGS IN THE SOFTWARE.
from typing import Optional, TypedDict from typing import Optional, TypedDict
from .snowflake import SnowflakeList from .snowflake import SnowflakeList
from .user import User from .user import User, AvatarDecorationData
from typing_extensions import NotRequired
class Nickname(TypedDict): class Nickname(TypedDict):
@ -47,6 +48,7 @@ class Member(PartialMember, total=False):
pending: bool pending: bool
permissions: str permissions: str
communication_disabled_until: str communication_disabled_until: str
avatar_decoration_data: NotRequired[AvatarDecorationData]
class _OptionalMemberWithUser(PartialMember, total=False): class _OptionalMemberWithUser(PartialMember, total=False):
@ -56,6 +58,7 @@ class _OptionalMemberWithUser(PartialMember, total=False):
pending: bool pending: bool
permissions: str permissions: str
communication_disabled_until: str communication_disabled_until: str
avatar_decoration_data: NotRequired[AvatarDecorationData]
class MemberWithUser(_OptionalMemberWithUser): class MemberWithUser(_OptionalMemberWithUser):

45
discord/types/message.py

@ -34,9 +34,10 @@ from .emoji import PartialEmoji
from .embed import Embed from .embed import Embed
from .channel import ChannelType from .channel import ChannelType
from .components import Component from .components import Component
from .interactions import MessageInteraction from .interactions import MessageInteraction, MessageInteractionMetadata
from .sticker import StickerItem from .sticker import StickerItem
from .threads import Thread from .threads import Thread
from .poll import Poll
class PartialMessage(TypedDict): class PartialMessage(TypedDict):
@ -56,6 +57,9 @@ class ReactionCountDetails(TypedDict):
normal: int normal: int
ReactionType = Literal[0, 1]
class Reaction(TypedDict): class Reaction(TypedDict):
count: int count: int
me: bool me: bool
@ -113,7 +117,40 @@ class RoleSubscriptionData(TypedDict):
MessageType = Literal[ MessageType = Literal[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
14,
15,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
36,
37,
38,
39,
] ]
@ -130,6 +167,7 @@ class Message(PartialMessage):
attachments: List[Attachment] attachments: List[Attachment]
embeds: List[Embed] embeds: List[Embed]
pinned: bool pinned: bool
poll: NotRequired[Poll]
type: MessageType type: MessageType
member: NotRequired[Member] member: NotRequired[Member]
mention_channels: NotRequired[List[ChannelMention]] mention_channels: NotRequired[List[ChannelMention]]
@ -143,7 +181,8 @@ class Message(PartialMessage):
flags: NotRequired[int] flags: NotRequired[int]
sticker_items: NotRequired[List[StickerItem]] sticker_items: NotRequired[List[StickerItem]]
referenced_message: NotRequired[Optional[Message]] referenced_message: NotRequired[Optional[Message]]
interaction: NotRequired[MessageInteraction] interaction: NotRequired[MessageInteraction] # deprecated, use interaction_metadata
interaction_metadata: NotRequired[MessageInteractionMetadata]
components: NotRequired[List[Component]] components: NotRequired[List[Component]]
position: NotRequired[int] position: NotRequired[int]
role_subscription_data: NotRequired[RoleSubscriptionData] role_subscription_data: NotRequired[RoleSubscriptionData]

88
discord/types/poll.py

@ -0,0 +1,88 @@
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
from typing import List, TypedDict, Optional, Literal, TYPE_CHECKING
from typing_extensions import NotRequired
from .snowflake import Snowflake
if TYPE_CHECKING:
from .user import User
from .emoji import PartialEmoji
LayoutType = Literal[1] # 1 = Default
class PollMedia(TypedDict):
text: str
emoji: NotRequired[Optional[PartialEmoji]]
class PollAnswer(TypedDict):
poll_media: PollMedia
class PollAnswerWithID(PollAnswer):
answer_id: int
class PollAnswerCount(TypedDict):
id: Snowflake
count: int
me_voted: bool
class PollAnswerVoters(TypedDict):
users: List[User]
class PollResult(TypedDict):
is_finalized: bool
answer_counts: List[PollAnswerCount]
class PollCreate(TypedDict):
allow_multiselect: bool
answers: List[PollAnswer]
duration: float
layout_type: LayoutType
question: PollMedia
# We don't subclass Poll as it will
# still have the duration field, which
# is converted into expiry when poll is
# fetched from a message or returned
# by a `send` method in a Messageable
class Poll(TypedDict):
allow_multiselect: bool
answers: List[PollAnswerWithID]
expiry: str
layout_type: LayoutType
question: PollMedia
results: PollResult

3
discord/types/sku.py

@ -46,7 +46,8 @@ class Entitlement(TypedDict):
deleted: bool deleted: bool
starts_at: NotRequired[str] starts_at: NotRequired[str]
ends_at: NotRequired[str] ends_at: NotRequired[str]
guild_id: Optional[str] guild_id: NotRequired[str]
consumed: NotRequired[bool]
EntitlementOwnerType = Literal[1, 2] EntitlementOwnerType = Literal[1, 2]

7
discord/types/user.py

@ -24,6 +24,12 @@ DEALINGS IN THE SOFTWARE.
from .snowflake import Snowflake from .snowflake import Snowflake
from typing import Literal, Optional, TypedDict from typing import Literal, Optional, TypedDict
from typing_extensions import NotRequired
class AvatarDecorationData(TypedDict):
asset: str
sku_id: Snowflake
class PartialUser(TypedDict): class PartialUser(TypedDict):
@ -32,6 +38,7 @@ class PartialUser(TypedDict):
discriminator: str discriminator: str
avatar: Optional[str] avatar: Optional[str]
global_name: Optional[str] global_name: Optional[str]
avatar_decoration_data: NotRequired[AvatarDecorationData]
PremiumType = Literal[0, 1, 2, 3] PremiumType = Literal[0, 1, 2, 3]

34
discord/ui/button.py

@ -61,12 +61,14 @@ class Button(Item[V]):
custom_id: Optional[:class:`str`] custom_id: Optional[:class:`str`]
The ID of the button that gets received during an interaction. The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID. If this button is for a URL, it does not have a custom ID.
Can only be up to 100 characters.
url: Optional[:class:`str`] url: Optional[:class:`str`]
The URL this button sends you to. The URL this button sends you to.
disabled: :class:`bool` disabled: :class:`bool`
Whether the button is disabled or not. Whether the button is disabled or not.
label: Optional[:class:`str`] label: Optional[:class:`str`]
The label of the button, if any. The label of the button, if any.
Can only be up to 80 characters.
emoji: Optional[Union[:class:`.PartialEmoji`, :class:`.Emoji`, :class:`str`]] emoji: Optional[Union[:class:`.PartialEmoji`, :class:`.Emoji`, :class:`str`]]
The emoji of the button, if available. The emoji of the button, if available.
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -75,6 +77,10 @@ class Button(Item[V]):
like to control the relative positioning of the row then passing an index is advised. like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed). ordering. The row number must be between 0 and 4 (i.e. zero indexed).
sku_id: Optional[:class:`int`]
The SKU ID this button sends you to. Can't be combined with ``url``.
.. versionadded:: 2.4
""" """
__item_repr_attributes__: Tuple[str, ...] = ( __item_repr_attributes__: Tuple[str, ...] = (
@ -84,6 +90,7 @@ class Button(Item[V]):
'label', 'label',
'emoji', 'emoji',
'row', 'row',
'sku_id',
) )
def __init__( def __init__(
@ -96,6 +103,7 @@ class Button(Item[V]):
url: Optional[str] = None, url: Optional[str] = None,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None, emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
row: Optional[int] = None, row: Optional[int] = None,
sku_id: Optional[int] = None,
): ):
super().__init__() super().__init__()
if custom_id is not None and url is not None: if custom_id is not None and url is not None:
@ -111,6 +119,9 @@ class Button(Item[V]):
if url is not None: if url is not None:
style = ButtonStyle.link style = ButtonStyle.link
if sku_id is not None:
style = ButtonStyle.premium
if emoji is not None: if emoji is not None:
if isinstance(emoji, str): if isinstance(emoji, str):
emoji = PartialEmoji.from_str(emoji) emoji = PartialEmoji.from_str(emoji)
@ -126,6 +137,7 @@ class Button(Item[V]):
label=label, label=label,
style=style, style=style,
emoji=emoji, emoji=emoji,
sku_id=sku_id,
) )
self.row = row self.row = row
@ -200,6 +212,19 @@ class Button(Item[V]):
else: else:
self._underlying.emoji = None self._underlying.emoji = None
@property
def sku_id(self) -> Optional[int]:
"""Optional[:class:`int`]: The SKU ID this button sends you to.
.. versionadded:: 2.4
"""
return self._underlying.sku_id
@sku_id.setter
def sku_id(self, value: Optional[int]) -> None:
self.style = ButtonStyle.premium
self._underlying.sku_id = value
@classmethod @classmethod
def from_component(cls, button: ButtonComponent) -> Self: def from_component(cls, button: ButtonComponent) -> Self:
return cls( return cls(
@ -210,6 +235,7 @@ class Button(Item[V]):
url=button.url, url=button.url,
emoji=button.emoji, emoji=button.emoji,
row=None, row=None,
sku_id=button.sku_id,
) )
@property @property
@ -239,6 +265,7 @@ def button(
style: ButtonStyle = ButtonStyle.secondary, style: ButtonStyle = ButtonStyle.secondary,
emoji: Optional[Union[str, Emoji, PartialEmoji]] = None, emoji: Optional[Union[str, Emoji, PartialEmoji]] = None,
row: Optional[int] = None, row: Optional[int] = None,
sku_id: Optional[int] = None,
) -> Callable[[ItemCallbackType[V, Button[V]]], Button[V]]: ) -> Callable[[ItemCallbackType[V, Button[V]]], Button[V]]:
"""A decorator that attaches a button to a component. """A decorator that attaches a button to a component.
@ -258,9 +285,11 @@ def button(
------------ ------------
label: Optional[:class:`str`] label: Optional[:class:`str`]
The label of the button, if any. The label of the button, if any.
Can only be up to 80 characters.
custom_id: Optional[:class:`str`] custom_id: Optional[:class:`str`]
The ID of the button that gets received during an interaction. The ID of the button that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts. It is recommended not to set this parameter to prevent conflicts.
Can only be up to 100 characters.
style: :class:`.ButtonStyle` style: :class:`.ButtonStyle`
The style of the button. Defaults to :attr:`.ButtonStyle.grey`. The style of the button. Defaults to :attr:`.ButtonStyle.grey`.
disabled: :class:`bool` disabled: :class:`bool`
@ -274,6 +303,10 @@ def button(
like to control the relative positioning of the row then passing an index is advised. like to control the relative positioning of the row then passing an index is advised.
For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic For example, row=1 will show up before row=2. Defaults to ``None``, which is automatic
ordering. The row number must be between 0 and 4 (i.e. zero indexed). ordering. The row number must be between 0 and 4 (i.e. zero indexed).
sku_id: Optional[:class:`int`]
The SKU ID this button sends you to. Can't be combined with ``url``.
.. versionadded:: 2.4
""" """
def decorator(func: ItemCallbackType[V, Button[V]]) -> ItemCallbackType[V, Button[V]]: def decorator(func: ItemCallbackType[V, Button[V]]) -> ItemCallbackType[V, Button[V]]:
@ -289,6 +322,7 @@ def button(
'label': label, 'label': label,
'emoji': emoji, 'emoji': emoji,
'row': row, 'row': row,
'sku_id': sku_id,
} }
return func return func

9
discord/ui/dynamic.py

@ -104,7 +104,8 @@ class DynamicItem(Generic[BaseT], Item['View']):
) -> None: ) -> None:
super().__init__() super().__init__()
self.item: BaseT = item self.item: BaseT = item
self.row = row if row is not None:
self.row = row
if not self.item.is_dispatchable(): if not self.item.is_dispatchable():
raise TypeError('item must be dispatchable, e.g. not a URL button') raise TypeError('item must be dispatchable, e.g. not a URL button')
@ -207,3 +208,9 @@ class DynamicItem(Generic[BaseT], Item['View']):
from the ``match`` object. from the ``match`` object.
""" """
raise NotImplementedError raise NotImplementedError
async def callback(self, interaction: Interaction[ClientT]) -> Any:
return await self.item.callback(interaction)
async def interaction_check(self, interaction: Interaction[ClientT], /) -> bool:
return await self.item.interaction_check(interaction)

3
discord/ui/modal.py

@ -77,7 +77,8 @@ class Modal(View):
Parameters Parameters
----------- -----------
title: :class:`str` title: :class:`str`
The title of the modal. Can only be up to 45 characters. The title of the modal.
Can only be up to 45 characters.
timeout: Optional[:class:`float`] timeout: Optional[:class:`float`]
Timeout in seconds from last interaction with the UI before no longer accepting input. Timeout in seconds from last interaction with the UI before no longer accepting input.
If ``None`` then there is no timeout. If ``None`` then there is no timeout.

38
discord/ui/select.py

@ -69,7 +69,7 @@ __all__ = (
) )
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import TypeAlias, Self, TypeGuard from typing_extensions import TypeAlias, TypeGuard
from .view import View from .view import View
from ..types.components import SelectMenu as SelectMenuPayload from ..types.components import SelectMenu as SelectMenuPayload
@ -342,7 +342,7 @@ class BaseSelect(Item[V]):
return True return True
@classmethod @classmethod
def from_component(cls, component: SelectMenu) -> Self: def from_component(cls, component: SelectMenu) -> BaseSelect[V]:
type_to_cls: Dict[ComponentType, Type[BaseSelect[Any]]] = { type_to_cls: Dict[ComponentType, Type[BaseSelect[Any]]] = {
ComponentType.string_select: Select, ComponentType.string_select: Select,
ComponentType.user_select: UserSelect, ComponentType.user_select: UserSelect,
@ -366,8 +366,10 @@ class Select(BaseSelect[V]):
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
min_values: :class:`int` min_values: :class:`int`
The minimum number of items that must be chosen for this select menu. The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 0 and 25. Defaults to 1 and must be between 0 and 25.
@ -376,6 +378,7 @@ class Select(BaseSelect[V]):
Defaults to 1 and must be between 1 and 25. Defaults to 1 and must be between 1 and 25.
options: List[:class:`discord.SelectOption`] options: List[:class:`discord.SelectOption`]
A list of options that can be selected in this menu. A list of options that can be selected in this menu.
Can only contain up to 25 items.
disabled: :class:`bool` disabled: :class:`bool`
Whether the select is disabled or not. Whether the select is disabled or not.
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -455,7 +458,8 @@ class Select(BaseSelect[V]):
Can only be up to 100 characters. Can only be up to 100 characters.
value: :class:`str` value: :class:`str`
The value of the option. This is not displayed to users. The value of the option. This is not displayed to users.
If not given, defaults to the label. Can only be up to 100 characters. If not given, defaults to the label.
Can only be up to 100 characters.
description: Optional[:class:`str`] description: Optional[:class:`str`]
An additional description of the option, if any. An additional description of the option, if any.
Can only be up to 100 characters. Can only be up to 100 characters.
@ -515,8 +519,10 @@ class UserSelect(BaseSelect[V]):
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
min_values: :class:`int` min_values: :class:`int`
The minimum number of items that must be chosen for this select menu. The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 0 and 25. Defaults to 1 and must be between 0 and 25.
@ -527,6 +533,7 @@ class UserSelect(BaseSelect[V]):
Whether the select is disabled or not. Whether the select is disabled or not.
default_values: Sequence[:class:`~discord.abc.Snowflake`] default_values: Sequence[:class:`~discord.abc.Snowflake`]
A list of objects representing the users that should be selected by default. A list of objects representing the users that should be selected by default.
Number of items must be in range of ``min_values`` and ``max_values``.
.. versionadded:: 2.4 .. versionadded:: 2.4
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -604,8 +611,10 @@ class RoleSelect(BaseSelect[V]):
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
min_values: :class:`int` min_values: :class:`int`
The minimum number of items that must be chosen for this select menu. The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 0 and 25. Defaults to 1 and must be between 0 and 25.
@ -616,6 +625,7 @@ class RoleSelect(BaseSelect[V]):
Whether the select is disabled or not. Whether the select is disabled or not.
default_values: Sequence[:class:`~discord.abc.Snowflake`] default_values: Sequence[:class:`~discord.abc.Snowflake`]
A list of objects representing the roles that should be selected by default. A list of objects representing the roles that should be selected by default.
Number of items must be in range of ``min_values`` and ``max_values``.
.. versionadded:: 2.4 .. versionadded:: 2.4
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -688,8 +698,10 @@ class MentionableSelect(BaseSelect[V]):
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
min_values: :class:`int` min_values: :class:`int`
The minimum number of items that must be chosen for this select menu. The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 0 and 25. Defaults to 1 and must be between 0 and 25.
@ -701,6 +713,7 @@ class MentionableSelect(BaseSelect[V]):
default_values: Sequence[:class:`~discord.abc.Snowflake`] default_values: Sequence[:class:`~discord.abc.Snowflake`]
A list of objects representing the users/roles that should be selected by default. A list of objects representing the users/roles that should be selected by default.
if :class:`.Object` is passed, then the type must be specified in the constructor. if :class:`.Object` is passed, then the type must be specified in the constructor.
Number of items must be in range of ``min_values`` and ``max_values``.
.. versionadded:: 2.4 .. versionadded:: 2.4
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -778,10 +791,12 @@ class ChannelSelect(BaseSelect[V]):
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
channel_types: List[:class:`~discord.ChannelType`] channel_types: List[:class:`~discord.ChannelType`]
The types of channels to show in the select menu. Defaults to all channels. The types of channels to show in the select menu. Defaults to all channels.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
min_values: :class:`int` min_values: :class:`int`
The minimum number of items that must be chosen for this select menu. The minimum number of items that must be chosen for this select menu.
Defaults to 1 and must be between 0 and 25. Defaults to 1 and must be between 0 and 25.
@ -792,6 +807,7 @@ class ChannelSelect(BaseSelect[V]):
Whether the select is disabled or not. Whether the select is disabled or not.
default_values: Sequence[:class:`~discord.abc.Snowflake`] default_values: Sequence[:class:`~discord.abc.Snowflake`]
A list of objects representing the channels that should be selected by default. A list of objects representing the channels that should be selected by default.
Number of items must be in range of ``min_values`` and ``max_values``.
.. versionadded:: 2.4 .. versionadded:: 2.4
row: Optional[:class:`int`] row: Optional[:class:`int`]
@ -871,7 +887,7 @@ class ChannelSelect(BaseSelect[V]):
@overload @overload
def select( def select(
*, *,
cls: Type[SelectT] = Select[V], cls: Type[SelectT] = Select[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = ..., channel_types: List[ChannelType] = ...,
placeholder: Optional[str] = ..., placeholder: Optional[str] = ...,
@ -887,7 +903,7 @@ def select(
@overload @overload
def select( def select(
*, *,
cls: Type[UserSelectT] = UserSelect[V], cls: Type[UserSelectT] = UserSelect[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = ..., channel_types: List[ChannelType] = ...,
placeholder: Optional[str] = ..., placeholder: Optional[str] = ...,
@ -904,7 +920,7 @@ def select(
@overload @overload
def select( def select(
*, *,
cls: Type[RoleSelectT] = RoleSelect[V], cls: Type[RoleSelectT] = RoleSelect[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = ..., channel_types: List[ChannelType] = ...,
placeholder: Optional[str] = ..., placeholder: Optional[str] = ...,
@ -921,7 +937,7 @@ def select(
@overload @overload
def select( def select(
*, *,
cls: Type[ChannelSelectT] = ChannelSelect[V], cls: Type[ChannelSelectT] = ChannelSelect[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = ..., channel_types: List[ChannelType] = ...,
placeholder: Optional[str] = ..., placeholder: Optional[str] = ...,
@ -938,7 +954,7 @@ def select(
@overload @overload
def select( def select(
*, *,
cls: Type[MentionableSelectT] = MentionableSelect[V], cls: Type[MentionableSelectT] = MentionableSelect[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = MISSING, channel_types: List[ChannelType] = MISSING,
placeholder: Optional[str] = ..., placeholder: Optional[str] = ...,
@ -954,7 +970,7 @@ def select(
def select( def select(
*, *,
cls: Type[BaseSelectT] = Select[V], cls: Type[BaseSelectT] = Select[Any],
options: List[SelectOption] = MISSING, options: List[SelectOption] = MISSING,
channel_types: List[ChannelType] = MISSING, channel_types: List[ChannelType] = MISSING,
placeholder: Optional[str] = None, placeholder: Optional[str] = None,
@ -1011,9 +1027,11 @@ def select(
get overridden. get overridden.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text that is shown if nothing is selected, if any. The placeholder text that is shown if nothing is selected, if any.
Can only be up to 150 characters.
custom_id: :class:`str` custom_id: :class:`str`
The ID of the select menu that gets received during an interaction. The ID of the select menu that gets received during an interaction.
It is recommended not to set this parameter to prevent conflicts. It is recommended not to set this parameter to prevent conflicts.
Can only be up to 100 characters.
row: Optional[:class:`int`] row: Optional[:class:`int`]
The relative row this select menu belongs to. A Discord component can only have 5 The relative row this select menu belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd rows. By default, items are arranged automatically into those 5 rows. If you'd
@ -1029,6 +1047,7 @@ def select(
options: List[:class:`discord.SelectOption`] options: List[:class:`discord.SelectOption`]
A list of options that can be selected in this menu. This can only be used with A list of options that can be selected in this menu. This can only be used with
:class:`Select` instances. :class:`Select` instances.
Can only contain up to 25 items.
channel_types: List[:class:`~discord.ChannelType`] channel_types: List[:class:`~discord.ChannelType`]
The types of channels to show in the select menu. Defaults to all channels. This can only be used The types of channels to show in the select menu. Defaults to all channels. This can only be used
with :class:`ChannelSelect` instances. with :class:`ChannelSelect` instances.
@ -1037,6 +1056,7 @@ def select(
default_values: Sequence[:class:`~discord.abc.Snowflake`] default_values: Sequence[:class:`~discord.abc.Snowflake`]
A list of objects representing the default values for the select menu. This cannot be used with regular :class:`Select` instances. A list of objects representing the default values for the select menu. This cannot be used with regular :class:`Select` instances.
If ``cls`` is :class:`MentionableSelect` and :class:`.Object` is passed, then the type must be specified in the constructor. If ``cls`` is :class:`MentionableSelect` and :class:`.Object` is passed, then the type must be specified in the constructor.
Number of items must be in range of ``min_values`` and ``max_values``.
.. versionadded:: 2.4 .. versionadded:: 2.4
""" """

6
discord/ui/text_input.py

@ -65,21 +65,27 @@ class TextInput(Item[V]):
------------ ------------
label: :class:`str` label: :class:`str`
The label to display above the text input. The label to display above the text input.
Can only be up to 45 characters.
custom_id: :class:`str` custom_id: :class:`str`
The ID of the text input that gets received during an interaction. The ID of the text input that gets received during an interaction.
If not given then one is generated for you. If not given then one is generated for you.
Can only be up to 100 characters.
style: :class:`discord.TextStyle` style: :class:`discord.TextStyle`
The style of the text input. The style of the text input.
placeholder: Optional[:class:`str`] placeholder: Optional[:class:`str`]
The placeholder text to display when the text input is empty. The placeholder text to display when the text input is empty.
Can only be up to 100 characters.
default: Optional[:class:`str`] default: Optional[:class:`str`]
The default value of the text input. The default value of the text input.
Can only be up to 4000 characters.
required: :class:`bool` required: :class:`bool`
Whether the text input is required. Whether the text input is required.
min_length: Optional[:class:`int`] min_length: Optional[:class:`int`]
The minimum length of the text input. The minimum length of the text input.
Must be between 0 and 4000.
max_length: Optional[:class:`int`] max_length: Optional[:class:`int`]
The maximum length of the text input. The maximum length of the text input.
Must be between 1 and 4000.
row: Optional[:class:`int`] row: Optional[:class:`int`]
The relative row this text input belongs to. A Discord component can only have 5 The relative row this text input belongs to. A Discord component can only have 5
rows. By default, items are arranged automatically into those 5 rows. If you'd rows. By default, items are arranged automatically into those 5 rows. If you'd

24
discord/ui/view.py

@ -320,7 +320,7 @@ class View:
or the row the item is trying to be added to is full. or the row the item is trying to be added to is full.
""" """
if len(self._children) > 25: if len(self._children) >= 25:
raise ValueError('maximum number of children exceeded') raise ValueError('maximum number of children exceeded')
if not isinstance(item, Item): if not isinstance(item, Item):
@ -613,18 +613,17 @@ class ViewStore:
if interaction.message is None: if interaction.message is None:
return return
view = View.from_message(interaction.message) view = View.from_message(interaction.message, timeout=None)
base_item_index: Optional[int] = None try:
for index, child in enumerate(view._children): base_item_index, base_item = next(
if child.type.value == component_type and getattr(child, 'custom_id', None) == custom_id: (index, child)
base_item_index = index for index, child in enumerate(view._children)
break if child.type.value == component_type and getattr(child, 'custom_id', None) == custom_id
)
if base_item_index is None: except StopIteration:
return return
base_item = view._children[base_item_index]
try: try:
item = await factory.from_custom_id(interaction, base_item, match) item = await factory.from_custom_id(interaction, base_item, match)
except Exception: except Exception:
@ -634,6 +633,7 @@ class ViewStore:
# Swap the item in the view with our new dynamic item # Swap the item in the view with our new dynamic item
view._children[base_item_index] = item view._children[base_item_index] = item
item._view = view item._view = view
item._rendered_row = base_item._rendered_row
item._refresh_state(interaction, interaction.data) # type: ignore item._refresh_state(interaction, interaction.data) # type: ignore
try: try:
@ -667,8 +667,8 @@ class ViewStore:
msg = interaction.message msg = interaction.message
if msg is not None: if msg is not None:
message_id = msg.id message_id = msg.id
if msg.interaction: if msg.interaction_metadata:
interaction_id = msg.interaction.id interaction_id = msg.interaction_metadata.id
key = (component_type, custom_id) key = (component_type, custom_id)

53
discord/user.py

@ -31,7 +31,7 @@ from .asset import Asset
from .colour import Colour from .colour import Colour
from .enums import DefaultAvatar from .enums import DefaultAvatar
from .flags import PublicUserFlags from .flags import PublicUserFlags
from .utils import snowflake_time, _bytes_to_base64_data, MISSING from .utils import snowflake_time, _bytes_to_base64_data, MISSING, _get_as_snowflake
if TYPE_CHECKING: if TYPE_CHECKING:
from typing_extensions import Self from typing_extensions import Self
@ -43,10 +43,7 @@ if TYPE_CHECKING:
from .message import Message from .message import Message
from .state import ConnectionState from .state import ConnectionState
from .types.channel import DMChannel as DMChannelPayload from .types.channel import DMChannel as DMChannelPayload
from .types.user import ( from .types.user import PartialUser as PartialUserPayload, User as UserPayload, AvatarDecorationData
PartialUser as PartialUserPayload,
User as UserPayload,
)
__all__ = ( __all__ = (
@ -73,6 +70,7 @@ class BaseUser(_UserTag):
'system', 'system',
'_public_flags', '_public_flags',
'_state', '_state',
'_avatar_decoration_data',
) )
if TYPE_CHECKING: if TYPE_CHECKING:
@ -87,6 +85,7 @@ class BaseUser(_UserTag):
_banner: Optional[str] _banner: Optional[str]
_accent_colour: Optional[int] _accent_colour: Optional[int]
_public_flags: int _public_flags: int
_avatar_decoration_data: Optional[AvatarDecorationData]
def __init__(self, *, state: ConnectionState, data: Union[UserPayload, PartialUserPayload]) -> None: def __init__(self, *, state: ConnectionState, data: Union[UserPayload, PartialUserPayload]) -> None:
self._state = state self._state = state
@ -123,6 +122,7 @@ class BaseUser(_UserTag):
self._public_flags = data.get('public_flags', 0) self._public_flags = data.get('public_flags', 0)
self.bot = data.get('bot', False) self.bot = data.get('bot', False)
self.system = data.get('system', False) self.system = data.get('system', False)
self._avatar_decoration_data = data.get('avatar_decoration_data')
@classmethod @classmethod
def _copy(cls, user: Self) -> Self: def _copy(cls, user: Self) -> Self:
@ -138,6 +138,7 @@ class BaseUser(_UserTag):
self.bot = user.bot self.bot = user.bot
self._state = user._state self._state = user._state
self._public_flags = user._public_flags self._public_flags = user._public_flags
self._avatar_decoration_data = user._avatar_decoration_data
return self return self
@ -187,6 +188,30 @@ class BaseUser(_UserTag):
""" """
return self.avatar or self.default_avatar return self.avatar or self.default_avatar
@property
def avatar_decoration(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns an :class:`Asset` for the avatar decoration the user has.
If the user has not set an avatar decoration, ``None`` is returned.
.. versionadded:: 2.4
"""
if self._avatar_decoration_data is not None:
return Asset._from_avatar_decoration(self._state, self._avatar_decoration_data['asset'])
return None
@property
def avatar_decoration_sku_id(self) -> Optional[int]:
"""Optional[:class:`int`]: Returns the SKU ID of the avatar decoration the user has.
If the user has not set an avatar decoration, ``None`` is returned.
.. versionadded:: 2.4
"""
if self._avatar_decoration_data is not None:
return _get_as_snowflake(self._avatar_decoration_data, 'sku_id')
return None
@property @property
def banner(self) -> Optional[Asset]: def banner(self) -> Optional[Asset]:
"""Optional[:class:`Asset`]: Returns the user's banner asset, if available. """Optional[:class:`Asset`]: Returns the user's banner asset, if available.
@ -373,7 +398,9 @@ class ClientUser(BaseUser):
self._flags = data.get('flags', 0) self._flags = data.get('flags', 0)
self.mfa_enabled = data.get('mfa_enabled', False) self.mfa_enabled = data.get('mfa_enabled', False)
async def edit(self, *, username: str = MISSING, avatar: Optional[bytes] = MISSING) -> ClientUser: async def edit(
self, *, username: str = MISSING, avatar: Optional[bytes] = MISSING, banner: Optional[bytes] = MISSING
) -> ClientUser:
"""|coro| """|coro|
Edits the current profile of the client. Edits the current profile of the client.
@ -385,7 +412,6 @@ class ClientUser(BaseUser):
then the file must be opened via ``open('some_filename', 'rb')`` and then the file must be opened via ``open('some_filename', 'rb')`` and
the :term:`py:bytes-like object` is given through the use of ``fp.read()``. the :term:`py:bytes-like object` is given through the use of ``fp.read()``.
The only image formats supported for uploading is JPEG and PNG.
.. versionchanged:: 2.0 .. versionchanged:: 2.0
The edit is no longer in-place, instead the newly edited client user is returned. The edit is no longer in-place, instead the newly edited client user is returned.
@ -401,6 +427,13 @@ class ClientUser(BaseUser):
avatar: Optional[:class:`bytes`] avatar: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the image to upload. A :term:`py:bytes-like object` representing the image to upload.
Could be ``None`` to denote no avatar. Could be ``None`` to denote no avatar.
Only image formats supported for uploading are JPEG, PNG, GIF, and WEBP.
banner: Optional[:class:`bytes`]
A :term:`py:bytes-like object` representing the image to upload.
Could be ``None`` to denote no banner.
Only image formats supported for uploading are JPEG, PNG, GIF and WEBP.
.. versionadded:: 2.4
Raises Raises
------ ------
@ -424,6 +457,12 @@ class ClientUser(BaseUser):
else: else:
payload['avatar'] = None payload['avatar'] = None
if banner is not MISSING:
if banner is not None:
payload['banner'] = _bytes_to_base64_data(banner)
else:
payload['banner'] = None
data: UserPayload = await self._state.http.edit_profile(payload) data: UserPayload = await self._state.http.edit_profile(payload)
return ClientUser(state=self._state, data=data) return ClientUser(state=self._state, data=data)

14
discord/utils.py

@ -68,6 +68,7 @@ import re
import os import os
import sys import sys
import types import types
import typing
import warnings import warnings
import logging import logging
@ -721,7 +722,7 @@ async def sane_wait_for(futures: Iterable[Awaitable[T]], *, timeout: Optional[fl
def get_slots(cls: Type[Any]) -> Iterator[str]: def get_slots(cls: Type[Any]) -> Iterator[str]:
for mro in reversed(cls.__mro__): for mro in reversed(cls.__mro__):
try: try:
yield from mro.__slots__ # type: ignore yield from mro.__slots__
except AttributeError: except AttributeError:
continue continue
@ -1080,6 +1081,7 @@ def as_chunks(iterator: _Iter[T], max_size: int) -> _Iter[List[T]]:
PY_310 = sys.version_info >= (3, 10) PY_310 = sys.version_info >= (3, 10)
PY_312 = sys.version_info >= (3, 12)
def flatten_literal_params(parameters: Iterable[Any]) -> Tuple[Any, ...]: def flatten_literal_params(parameters: Iterable[Any]) -> Tuple[Any, ...]:
@ -1118,6 +1120,16 @@ def evaluate_annotation(
cache[tp] = evaluated cache[tp] = evaluated
return evaluated return evaluated
if PY_312 and getattr(tp.__repr__, '__objclass__', None) is typing.TypeAliasType: # type: ignore
temp_locals = dict(**locals, **{t.__name__: t for t in tp.__type_params__})
annotation = evaluate_annotation(tp.__value__, globals, temp_locals, cache.copy())
if hasattr(tp, '__args__'):
annotation = annotation[tp.__args__]
return annotation
if hasattr(tp, '__supertype__'):
return evaluate_annotation(tp.__supertype__, globals, locals, cache)
if hasattr(tp, '__metadata__'): if hasattr(tp, '__metadata__'):
# Annotated[X, Y] can access Y via __metadata__ # Annotated[X, Y] can access Y via __metadata__
metadata = tp.__metadata__[0] metadata = tp.__metadata__[0]

6
discord/voice_client.py

@ -125,7 +125,7 @@ class VoiceProtocol:
Parameters Parameters
------------ ------------
data: :class:`dict` data: :class:`dict`
The raw :ddocs:`voice server update payload <topics/gateway#voice-server-update>`. The raw :ddocs:`voice server update payload <topics/gateway-events#voice-server-update>`.
""" """
raise NotImplementedError raise NotImplementedError
@ -337,7 +337,7 @@ class VoiceClient(VoiceProtocol):
Disconnects this voice client from voice. Disconnects this voice client from voice.
""" """
self.stop() self.stop()
await self._connection.disconnect(force=force) await self._connection.disconnect(force=force, wait=True)
self.cleanup() self.cleanup()
async def move_to(self, channel: Optional[abc.Snowflake], *, timeout: Optional[float] = 30.0) -> None: async def move_to(self, channel: Optional[abc.Snowflake], *, timeout: Optional[float] = 30.0) -> None:
@ -567,6 +567,6 @@ class VoiceClient(VoiceProtocol):
try: try:
self._connection.send_packet(packet) self._connection.send_packet(packet)
except OSError: except OSError:
_log.info('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp) _log.debug('A packet has been dropped (seq: %s, timestamp: %s)', self.sequence, self.timestamp)
self.checked_add('timestamp', opus.Encoder.SAMPLES_PER_FRAME, 4294967295) self.checked_add('timestamp', opus.Encoder.SAMPLES_PER_FRAME, 4294967295)

177
discord/voice_state.py

@ -45,11 +45,6 @@ import asyncio
import logging import logging
import threading import threading
try:
from asyncio import timeout as atimeout # type: ignore
except ImportError:
from async_timeout import timeout as atimeout # type: ignore
from typing import TYPE_CHECKING, Optional, Dict, List, Callable, Coroutine, Any, Tuple from typing import TYPE_CHECKING, Optional, Dict, List, Callable, Coroutine, Any, Tuple
from .enums import Enum from .enums import Enum
@ -81,9 +76,10 @@ _log = logging.getLogger(__name__)
class SocketReader(threading.Thread): class SocketReader(threading.Thread):
def __init__(self, state: VoiceConnectionState) -> None: def __init__(self, state: VoiceConnectionState, *, start_paused: bool = True) -> None:
super().__init__(daemon=True, name=f'voice-socket-reader:{id(self):#x}') super().__init__(daemon=True, name=f'voice-socket-reader:{id(self):#x}')
self.state: VoiceConnectionState = state self.state: VoiceConnectionState = state
self.start_paused = start_paused
self._callbacks: List[SocketReaderCallback] = [] self._callbacks: List[SocketReaderCallback] = []
self._running = threading.Event() self._running = threading.Event()
self._end = threading.Event() self._end = threading.Event()
@ -130,6 +126,8 @@ class SocketReader(threading.Thread):
def run(self) -> None: def run(self) -> None:
self._end.clear() self._end.clear()
self._running.set() self._running.set()
if self.start_paused:
self.pause()
try: try:
self._do_run() self._do_run()
except Exception: except Exception:
@ -148,7 +146,10 @@ class SocketReader(threading.Thread):
# Since this socket is a non blocking socket, select has to be used to wait on it for reading. # Since this socket is a non blocking socket, select has to be used to wait on it for reading.
try: try:
readable, _, _ = select.select([self.state.socket], [], [], 30) readable, _, _ = select.select([self.state.socket], [], [], 30)
except (ValueError, TypeError): except (ValueError, TypeError, OSError) as e:
_log.debug(
"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
@ -212,6 +213,7 @@ class VoiceConnectionState:
self._expecting_disconnect: bool = False self._expecting_disconnect: bool = False
self._connected = threading.Event() self._connected = threading.Event()
self._state_event = asyncio.Event() self._state_event = asyncio.Event()
self._disconnected = asyncio.Event()
self._runner: Optional[asyncio.Task] = None self._runner: Optional[asyncio.Task] = None
self._connector: Optional[asyncio.Task] = None self._connector: Optional[asyncio.Task] = None
self._socket_reader = SocketReader(self) self._socket_reader = SocketReader(self)
@ -254,8 +256,10 @@ class VoiceConnectionState:
channel_id = data['channel_id'] channel_id = data['channel_id']
if channel_id is None: if channel_id is None:
self._disconnected.set()
# If we know we're going to get a voice_state_update where we have no channel due to # If we know we're going to get a voice_state_update where we have no channel due to
# being in the reconnect flow, we ignore it. Otherwise, it probably wasn't from us. # being in the reconnect or disconnect flow, we ignore it. Otherwise, it probably wasn't from us.
if self._expecting_disconnect: if self._expecting_disconnect:
self._expecting_disconnect = False self._expecting_disconnect = False
else: else:
@ -264,26 +268,31 @@ class VoiceConnectionState:
return return
channel_id = int(channel_id)
self.session_id = data['session_id'] self.session_id = data['session_id']
# we got the event while connecting # we got the event while connecting
if self.state in (ConnectionFlowState.set_guild_voice_state, ConnectionFlowState.got_voice_server_update): if self.state in (ConnectionFlowState.set_guild_voice_state, ConnectionFlowState.got_voice_server_update):
if self.state is ConnectionFlowState.set_guild_voice_state: if self.state is ConnectionFlowState.set_guild_voice_state:
self.state = ConnectionFlowState.got_voice_state_update self.state = ConnectionFlowState.got_voice_state_update
# we moved ourselves
if channel_id != self.voice_client.channel.id:
self._update_voice_channel(channel_id)
else: else:
self.state = ConnectionFlowState.got_both_voice_updates self.state = ConnectionFlowState.got_both_voice_updates
return return
if self.state is ConnectionFlowState.connected: if self.state is ConnectionFlowState.connected:
self.voice_client.channel = channel_id and self.guild.get_channel(int(channel_id)) # type: ignore self._update_voice_channel(channel_id)
elif self.state is not ConnectionFlowState.disconnected: elif self.state is not ConnectionFlowState.disconnected:
if channel_id != self.voice_client.channel.id: if channel_id != self.voice_client.channel.id:
# For some unfortunate reason we were moved during the connection flow # For some unfortunate reason we were moved during the connection flow
_log.info('Handling channel move while connecting...') _log.info('Handling channel move while connecting...')
self.voice_client.channel = channel_id and self.guild.get_channel(int(channel_id)) # type: ignore self._update_voice_channel(channel_id)
await self.soft_disconnect(with_state=ConnectionFlowState.got_voice_state_update) await self.soft_disconnect(with_state=ConnectionFlowState.got_voice_state_update)
await self.connect( await self.connect(
reconnect=self.reconnect, reconnect=self.reconnect,
@ -297,6 +306,10 @@ class VoiceConnectionState:
_log.debug('Ignoring unexpected voice_state_update event') _log.debug('Ignoring unexpected voice_state_update event')
async def voice_server_update(self, data: VoiceServerUpdatePayload) -> None: async def voice_server_update(self, data: VoiceServerUpdatePayload) -> None:
previous_token = self.token
previous_server_id = self.server_id
previous_endpoint = self.endpoint
self.token = data['token'] self.token = data['token']
self.server_id = int(data['guild_id']) self.server_id = int(data['guild_id'])
endpoint = data.get('endpoint') endpoint = data.get('endpoint')
@ -330,6 +343,10 @@ class VoiceConnectionState:
self.state = ConnectionFlowState.got_voice_server_update self.state = ConnectionFlowState.got_voice_server_update
elif self.state is not ConnectionFlowState.disconnected: elif self.state is not ConnectionFlowState.disconnected:
# eventual consistency
if previous_token == self.token and previous_server_id == self.server_id and previous_token == self.token:
return
_log.debug('Unexpected server update event, attempting to handle') _log.debug('Unexpected server update event, attempting to handle')
await self.soft_disconnect(with_state=ConnectionFlowState.got_voice_server_update) await self.soft_disconnect(with_state=ConnectionFlowState.got_voice_server_update)
@ -378,69 +395,91 @@ class VoiceConnectionState:
await self.disconnect() await self.disconnect()
raise raise
async def _connect(self, reconnect: bool, timeout: float, self_deaf: bool, self_mute: bool, resume: bool) -> None: async def _inner_connect(self, reconnect: bool, self_deaf: bool, self_mute: bool, resume: bool) -> None:
_log.info('Connecting to voice...') for i in range(5):
_log.info('Starting voice handshake... (connection attempt %d)', i + 1)
async with atimeout(timeout): await self._voice_connect(self_deaf=self_deaf, self_mute=self_mute)
for i in range(5): # Setting this unnecessarily will break reconnecting
_log.info('Starting voice handshake... (connection attempt %d)', i + 1) if self.state is ConnectionFlowState.disconnected:
self.state = ConnectionFlowState.set_guild_voice_state
await self._voice_connect(self_deaf=self_deaf, self_mute=self_mute) await self._wait_for_state(ConnectionFlowState.got_both_voice_updates)
# Setting this unnecessarily will break reconnecting
if self.state is ConnectionFlowState.disconnected:
self.state = ConnectionFlowState.set_guild_voice_state
await self._wait_for_state(ConnectionFlowState.got_both_voice_updates) _log.info('Voice handshake complete. Endpoint found: %s', self.endpoint)
_log.info('Voice handshake complete. Endpoint found: %s', self.endpoint) try:
self.ws = await self._connect_websocket(resume)
await self._handshake_websocket()
break
except ConnectionClosed:
if reconnect:
wait = 1 + i * 2.0
_log.exception('Failed to connect to voice... Retrying in %ss...', wait)
await self.disconnect(cleanup=False)
await asyncio.sleep(wait)
continue
else:
await self.disconnect()
raise
try: async def _connect(self, reconnect: bool, timeout: float, self_deaf: bool, self_mute: bool, resume: bool) -> None:
self.ws = await self._connect_websocket(resume) _log.info('Connecting to voice...')
await self._handshake_websocket()
break
except ConnectionClosed:
if reconnect:
wait = 1 + i * 2.0
_log.exception('Failed to connect to voice... Retrying in %ss...', wait)
await self.disconnect(cleanup=False)
await asyncio.sleep(wait)
continue
else:
await self.disconnect()
raise
await asyncio.wait_for(
self._inner_connect(reconnect=reconnect, self_deaf=self_deaf, self_mute=self_mute, resume=resume),
timeout=timeout,
)
_log.info('Voice connection complete.') _log.info('Voice connection complete.')
if not self._runner: if not self._runner:
self._runner = self.voice_client.loop.create_task(self._poll_voice_ws(reconnect), name='Voice websocket poller') self._runner = self.voice_client.loop.create_task(self._poll_voice_ws(reconnect), name='Voice websocket poller')
async def disconnect(self, *, force: bool = True, cleanup: bool = True) -> None: async def disconnect(self, *, force: bool = True, cleanup: bool = True, wait: bool = False) -> None:
if not force and not self.is_connected(): if not force and not self.is_connected():
return return
try: try:
await self._voice_disconnect()
if self.ws: if self.ws:
await self.ws.close() await self.ws.close()
await self._voice_disconnect()
except Exception: except Exception:
_log.debug('Ignoring exception disconnecting from voice', exc_info=True) _log.debug('Ignoring exception disconnecting from voice', exc_info=True)
finally: finally:
self.ip = MISSING
self.port = MISSING
self.state = ConnectionFlowState.disconnected self.state = ConnectionFlowState.disconnected
self._socket_reader.pause() self._socket_reader.pause()
# Stop threads before we unlock waiters so they end properly
if cleanup:
self._socket_reader.stop()
self.voice_client.stop()
# Flip the connected event to unlock any waiters # Flip the connected event to unlock any waiters
self._connected.set() self._connected.set()
self._connected.clear() self._connected.clear()
if cleanup:
self._socket_reader.stop()
self.voice_client.cleanup()
if self.socket: if self.socket:
self.socket.close() self.socket.close()
self.ip = MISSING
self.port = MISSING
# Skip this part if disconnect was called from the poll loop task
if wait and not self._inside_runner():
# Wait for the voice_state_update event confirming the bot left the voice channel.
# This prevents a race condition caused by disconnecting and immediately connecting again.
# The new VoiceConnectionState object receives the voice_state_update event containing channel=None while still
# connecting leaving it in a bad state. Since there's no nice way to transfer state to the new one, we have to do this.
try:
await asyncio.wait_for(self._disconnected.wait(), timeout=self.timeout)
except TimeoutError:
_log.debug('Timed out waiting for voice disconnection confirmation')
except asyncio.CancelledError:
pass
if cleanup:
self.voice_client.cleanup()
async def soft_disconnect(self, *, with_state: ConnectionFlowState = ConnectionFlowState.got_both_voice_updates) -> None: async def soft_disconnect(self, *, with_state: ConnectionFlowState = ConnectionFlowState.got_both_voice_updates) -> None:
_log.debug('Soft disconnecting from voice') _log.debug('Soft disconnecting from voice')
# Stop the websocket reader because closing the websocket will trigger an unwanted reconnect # Stop the websocket reader because closing the websocket will trigger an unwanted reconnect
@ -454,20 +493,26 @@ class VoiceConnectionState:
except Exception: except Exception:
_log.debug('Ignoring exception soft disconnecting from voice', exc_info=True) _log.debug('Ignoring exception soft disconnecting from voice', exc_info=True)
finally: finally:
self.ip = MISSING
self.port = MISSING
self.state = with_state self.state = with_state
self._socket_reader.pause() self._socket_reader.pause()
if self.socket: if self.socket:
self.socket.close() self.socket.close()
self.ip = MISSING
self.port = MISSING
async def move_to(self, channel: Optional[abc.Snowflake], timeout: Optional[float]) -> None: async def move_to(self, channel: Optional[abc.Snowflake], timeout: Optional[float]) -> None:
if channel is None: if channel is None:
await self.disconnect() # This function should only be called externally so its ok to wait for the disconnect.
await self.disconnect(wait=True)
return
if self.voice_client.channel and channel.id == self.voice_client.channel.id:
return return
previous_state = self.state previous_state = self.state
# this is only an outgoing ws request # this is only an outgoing ws request
# if it fails, nothing happens and nothing changes (besides self.state) # if it fails, nothing happens and nothing changes (besides self.state)
await self._move_to(channel) await self._move_to(channel)
@ -479,7 +524,6 @@ class VoiceConnectionState:
_log.warning('Timed out trying to move to channel %s in guild %s', channel.id, self.guild.id) _log.warning('Timed out trying to move to channel %s in guild %s', channel.id, self.guild.id)
if self.state is last_state: if self.state is last_state:
_log.debug('Reverting to previous state %s', previous_state.name) _log.debug('Reverting to previous state %s', previous_state.name)
self.state = previous_state self.state = previous_state
def wait(self, timeout: Optional[float] = None) -> bool: def wait(self, timeout: Optional[float] = None) -> bool:
@ -502,6 +546,9 @@ class VoiceConnectionState:
_log.debug('Unregistering socket listener callback %s', callback) _log.debug('Unregistering socket listener callback %s', callback)
self._socket_reader.unregister(callback) self._socket_reader.unregister(callback)
def _inside_runner(self) -> bool:
return self._runner is not None and asyncio.current_task() == self._runner
async def _wait_for_state( async def _wait_for_state(
self, state: ConnectionFlowState, *other_states: ConnectionFlowState, timeout: Optional[float] = None self, state: ConnectionFlowState, *other_states: ConnectionFlowState, timeout: Optional[float] = None
) -> None: ) -> None:
@ -524,6 +571,7 @@ class VoiceConnectionState:
self.state = ConnectionFlowState.disconnected self.state = ConnectionFlowState.disconnected
await self.voice_client.channel.guild.change_voice_state(channel=None) await self.voice_client.channel.guild.change_voice_state(channel=None)
self._expecting_disconnect = True self._expecting_disconnect = True
self._disconnected.clear()
async def _connect_websocket(self, resume: bool) -> DiscordVoiceWebSocket: async def _connect_websocket(self, resume: bool) -> DiscordVoiceWebSocket:
ws = await DiscordVoiceWebSocket.from_connection_state(self, resume=resume, hook=self.hook) ws = await DiscordVoiceWebSocket.from_connection_state(self, resume=resume, hook=self.hook)
@ -557,16 +605,28 @@ class VoiceConnectionState:
# 4014 - we were externally disconnected (voice channel deleted, we were moved, etc) # 4014 - we were externally disconnected (voice channel deleted, we were moved, etc)
# 4015 - voice server has crashed # 4015 - voice server has crashed
if exc.code in (1000, 4015): if exc.code in (1000, 4015):
_log.info('Disconnecting from voice normally, close code %d.', exc.code) # Don't call disconnect a second time if the websocket closed from a disconnect call
await self.disconnect() if not self._expecting_disconnect:
_log.info('Disconnecting from voice normally, close code %d.', exc.code)
await self.disconnect()
break break
if exc.code == 4014: if exc.code == 4014:
# We were disconnected by discord
# This condition is a race between the main ws event and the voice ws closing
if self._disconnected.is_set():
_log.info('Disconnected from voice by discord, close code %d.', exc.code)
await self.disconnect()
break
# We may have been moved to a different channel
_log.info('Disconnected from voice by force... potentially reconnecting.') _log.info('Disconnected from voice by force... potentially reconnecting.')
successful = await self._potential_reconnect() successful = await self._potential_reconnect()
if not successful: if not successful:
_log.info('Reconnect was unsuccessful, disconnecting from voice normally...') _log.info('Reconnect was unsuccessful, disconnecting from voice normally...')
await self.disconnect() # Don't bother to disconnect if already disconnected
if self.state is not ConnectionFlowState.disconnected:
await self.disconnect()
break break
else: else:
continue continue
@ -598,10 +658,18 @@ class VoiceConnectionState:
async def _potential_reconnect(self) -> bool: async def _potential_reconnect(self) -> bool:
try: try:
await self._wait_for_state( await self._wait_for_state(
ConnectionFlowState.got_voice_server_update, ConnectionFlowState.got_both_voice_updates, timeout=self.timeout ConnectionFlowState.got_voice_server_update,
ConnectionFlowState.got_both_voice_updates,
ConnectionFlowState.disconnected,
timeout=self.timeout,
) )
except asyncio.TimeoutError: except asyncio.TimeoutError:
return False return False
else:
if self.state is ConnectionFlowState.disconnected:
return False
previous_ws = self.ws
try: try:
self.ws = await self._connect_websocket(False) self.ws = await self._connect_websocket(False)
await self._handshake_websocket() await self._handshake_websocket()
@ -609,7 +677,12 @@ class VoiceConnectionState:
return False return False
else: else:
return True return True
finally:
await previous_ws.close()
async def _move_to(self, channel: abc.Snowflake) -> None: async def _move_to(self, channel: abc.Snowflake) -> None:
await self.voice_client.channel.guild.change_voice_state(channel=channel) await self.voice_client.channel.guild.change_voice_state(channel=channel)
self.state = ConnectionFlowState.set_guild_voice_state self.state = ConnectionFlowState.set_guild_voice_state
def _update_voice_channel(self, channel_id: Optional[int]) -> None:
self.voice_client.channel = channel_id and self.guild.get_channel(channel_id) # type: ignore

33
discord/webhook/async_.py

@ -72,6 +72,7 @@ if TYPE_CHECKING:
from ..channel import VoiceChannel from ..channel import VoiceChannel
from ..abc import Snowflake from ..abc import Snowflake
from ..ui.view import View from ..ui.view import View
from ..poll import Poll
import datetime import datetime
from ..types.webhook import ( from ..types.webhook import (
Webhook as WebhookPayload, Webhook as WebhookPayload,
@ -541,6 +542,7 @@ def interaction_message_response_params(
view: Optional[View] = MISSING, view: Optional[View] = MISSING,
allowed_mentions: Optional[AllowedMentions] = MISSING, allowed_mentions: Optional[AllowedMentions] = MISSING,
previous_allowed_mentions: Optional[AllowedMentions] = None, previous_allowed_mentions: Optional[AllowedMentions] = None,
poll: Poll = MISSING,
) -> MultipartParameters: ) -> MultipartParameters:
if files is not MISSING and file is not MISSING: if files is not MISSING and file is not MISSING:
raise TypeError('Cannot mix file and files keyword arguments.') raise TypeError('Cannot mix file and files keyword arguments.')
@ -608,6 +610,9 @@ def interaction_message_response_params(
data['attachments'] = attachments_payload data['attachments'] = attachments_payload
if poll is not MISSING:
data['poll'] = poll._to_dict()
multipart = [] multipart = []
if files: if files:
data = {'type': type, 'data': data} data = {'type': type, 'data': data}
@ -716,6 +721,11 @@ class _WebhookState:
return self._parent._get_guild(guild_id) return self._parent._get_guild(guild_id)
return None return None
def _get_poll(self, msg_id: Optional[int]) -> Optional[Poll]:
if self._parent is not None:
return self._parent._get_poll(msg_id)
return None
def store_user(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> BaseUser: def store_user(self, data: Union[UserPayload, PartialUserPayload], *, cache: bool = True) -> BaseUser:
if self._parent is not None: if self._parent is not None:
return self._parent.store_user(data, cache=cache) return self._parent.store_user(data, cache=cache)
@ -1155,7 +1165,7 @@ class Webhook(BaseWebhook):
self.proxy_auth: Optional[aiohttp.BasicAuth] = proxy_auth self.proxy_auth: Optional[aiohttp.BasicAuth] = proxy_auth
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Webhook id={self.id!r}>' return f'<Webhook id={self.id!r} type={self.type!r} name={self.name!r}>'
@property @property
def url(self) -> str: def url(self) -> str:
@ -1305,9 +1315,10 @@ class Webhook(BaseWebhook):
'user': { 'user': {
'username': user.name, 'username': user.name,
'discriminator': user.discriminator, 'discriminator': user.discriminator,
'global_name': user.global_name,
'id': user.id, 'id': user.id,
'avatar': user._avatar, 'avatar': user._avatar,
'avatar_decoration_data': user._avatar_decoration_data,
'global_name': user.global_name,
}, },
} }
@ -1595,6 +1606,8 @@ class Webhook(BaseWebhook):
wait: Literal[True], wait: Literal[True],
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> WebhookMessage: ) -> WebhookMessage:
... ...
@ -1618,6 +1631,8 @@ class Webhook(BaseWebhook):
wait: Literal[False] = ..., wait: Literal[False] = ...,
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> None: ) -> None:
... ...
@ -1641,6 +1656,7 @@ class Webhook(BaseWebhook):
suppress_embeds: bool = False, suppress_embeds: bool = False,
silent: bool = False, silent: bool = False,
applied_tags: List[ForumTag] = MISSING, applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> Optional[WebhookMessage]: ) -> Optional[WebhookMessage]:
"""|coro| """|coro|
@ -1731,6 +1747,15 @@ class Webhook(BaseWebhook):
.. versionadded:: 2.4 .. versionadded:: 2.4
poll: :class:`Poll`
The poll to send with this message.
.. warning::
When sending a Poll via webhook, you cannot manually end it.
.. versionadded:: 2.4
Raises Raises
-------- --------
HTTPException HTTPException
@ -1808,6 +1833,7 @@ class Webhook(BaseWebhook):
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions, previous_allowed_mentions=previous_mentions,
applied_tags=applied_tag_ids, applied_tags=applied_tag_ids,
poll=poll,
) as params: ) as params:
adapter = async_context.get() adapter = async_context.get()
thread_id: Optional[int] = None thread_id: Optional[int] = None
@ -1835,6 +1861,9 @@ class Webhook(BaseWebhook):
message_id = None if msg is None else msg.id message_id = None if msg is None else msg.id
self._state.store_view(view, message_id) self._state.store_view(view, message_id)
if poll is not MISSING and msg:
poll._update(msg)
return msg return msg
async def fetch_message(self, id: int, /, *, thread: Snowflake = MISSING) -> WebhookMessage: async def fetch_message(self, id: int, /, *, thread: Snowflake = MISSING) -> WebhookMessage:

36
discord/webhook/sync.py

@ -44,7 +44,7 @@ from .. import utils
from ..errors import HTTPException, Forbidden, NotFound, DiscordServerError from ..errors import HTTPException, Forbidden, NotFound, DiscordServerError
from ..message import Message, MessageFlags from ..message import Message, MessageFlags
from ..http import Route, handle_message_parameters from ..http import Route, handle_message_parameters
from ..channel import PartialMessageable from ..channel import PartialMessageable, ForumTag
from .async_ import BaseWebhook, _WebhookState from .async_ import BaseWebhook, _WebhookState
@ -61,6 +61,7 @@ if TYPE_CHECKING:
from ..file import File from ..file import File
from ..embeds import Embed from ..embeds import Embed
from ..poll import Poll
from ..mentions import AllowedMentions from ..mentions import AllowedMentions
from ..message import Attachment from ..message import Attachment
from ..abc import Snowflake from ..abc import Snowflake
@ -71,6 +72,7 @@ if TYPE_CHECKING:
from ..types.message import ( from ..types.message import (
Message as MessagePayload, Message as MessagePayload,
) )
from ..types.snowflake import SnowflakeList
BE = TypeVar('BE', bound=BaseException) BE = TypeVar('BE', bound=BaseException)
@ -608,7 +610,7 @@ class SyncWebhook(BaseWebhook):
self.session: Session = session self.session: Session = session
def __repr__(self) -> str: def __repr__(self) -> str:
return f'<Webhook id={self.id!r}>' return f'<Webhook id={self.id!r} type={self.type!r} name={self.name!r}>'
@property @property
def url(self) -> str: def url(self) -> str:
@ -870,6 +872,8 @@ class SyncWebhook(BaseWebhook):
wait: Literal[True], wait: Literal[True],
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> SyncWebhookMessage: ) -> SyncWebhookMessage:
... ...
@ -891,6 +895,8 @@ class SyncWebhook(BaseWebhook):
wait: Literal[False] = ..., wait: Literal[False] = ...,
suppress_embeds: bool = MISSING, suppress_embeds: bool = MISSING,
silent: bool = MISSING, silent: bool = MISSING,
applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> None: ) -> None:
... ...
@ -911,6 +917,8 @@ class SyncWebhook(BaseWebhook):
wait: bool = False, wait: bool = False,
suppress_embeds: bool = False, suppress_embeds: bool = False,
silent: bool = False, silent: bool = False,
applied_tags: List[ForumTag] = MISSING,
poll: Poll = MISSING,
) -> Optional[SyncWebhookMessage]: ) -> Optional[SyncWebhookMessage]:
"""Sends a message using the webhook. """Sends a message using the webhook.
@ -975,6 +983,14 @@ class SyncWebhook(BaseWebhook):
in the UI, but will not actually send a notification. in the UI, but will not actually send a notification.
.. versionadded:: 2.2 .. versionadded:: 2.2
poll: :class:`Poll`
The poll to send with this message.
.. warning::
When sending a Poll via webhook, you cannot manually end it.
.. versionadded:: 2.4
Raises Raises
-------- --------
@ -1014,6 +1030,11 @@ class SyncWebhook(BaseWebhook):
if thread_name is not MISSING and thread is not MISSING: if thread_name is not MISSING and thread is not MISSING:
raise TypeError('Cannot mix thread_name and thread keyword arguments.') raise TypeError('Cannot mix thread_name and thread keyword arguments.')
if applied_tags is MISSING:
applied_tag_ids = MISSING
else:
applied_tag_ids: SnowflakeList = [tag.id for tag in applied_tags]
with handle_message_parameters( with handle_message_parameters(
content=content, content=content,
username=username, username=username,
@ -1027,6 +1048,8 @@ class SyncWebhook(BaseWebhook):
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
previous_allowed_mentions=previous_mentions, previous_allowed_mentions=previous_mentions,
flags=flags, flags=flags,
applied_tags=applied_tag_ids,
poll=poll,
) as params: ) as params:
adapter: WebhookAdapter = _get_webhook_adapter() adapter: WebhookAdapter = _get_webhook_adapter()
thread_id: Optional[int] = None thread_id: Optional[int] = None
@ -1044,8 +1067,15 @@ class SyncWebhook(BaseWebhook):
wait=wait, wait=wait,
) )
msg = None
if wait: if wait:
return self._create_message(data, thread=thread) msg = self._create_message(data, thread=thread)
if poll is not MISSING and msg:
poll._update(msg)
return msg
def fetch_message(self, id: int, /, *, thread: Snowflake = MISSING) -> SyncWebhookMessage: def fetch_message(self, id: int, /, *, thread: Snowflake = MISSING) -> SyncWebhookMessage:
"""Retrieves a single :class:`~discord.SyncWebhookMessage` owned by this webhook. """Retrieves a single :class:`~discord.SyncWebhookMessage` owned by this webhook.

2
discord/welcome_screen.py

@ -214,4 +214,4 @@ class WelcomeScreen:
fields['enabled'] = enabled fields['enabled'] = enabled
data = await self._state.http.edit_welcome_screen(self._guild.id, reason=reason, **fields) data = await self._state.http.edit_welcome_screen(self._guild.id, reason=reason, **fields)
return WelcomeScreen(data=data, guild=self._guild) return self.__class__(data=data, guild=self._guild)

205
docs/api.rst

@ -1008,7 +1008,7 @@ Messages
will return a :class:`Message` object that represents the message before the content was modified. will return a :class:`Message` object that represents the message before the content was modified.
Due to the inherently raw nature of this event, the data parameter coincides with Due to the inherently raw nature of this event, the data parameter coincides with
the raw data given by the :ddocs:`gateway <topics/gateway#message-update>`. the raw data given by the :ddocs:`gateway <topics/gateway-events#message-update>`.
Since the data payload can be partial, care must be taken when accessing stuff in the dictionary. Since the data payload can be partial, care must be taken when accessing stuff in the dictionary.
One example of a common case of partial data is when the ``'content'`` key is inaccessible. This One example of a common case of partial data is when the ``'content'`` key is inaccessible. This
@ -1047,6 +1047,47 @@ Messages
:param payload: The raw event payload data. :param payload: The raw event payload data.
:type payload: :class:`RawBulkMessageDeleteEvent` :type payload: :class:`RawBulkMessageDeleteEvent`
Polls
~~~~~~
.. function:: on_poll_vote_add(user, answer)
on_poll_vote_remove(user, answer)
Called when a :class:`Poll` gains or loses a vote. If the ``user`` or ``answer``'s poll
parent message are not cached then this event will not be called.
This requires :attr:`Intents.message_content` and :attr:`Intents.polls` to be enabled.
.. note::
If the poll allows multiple answers and the user removes or adds multiple votes, this
event will be called as many times as votes that are added or removed.
.. versionadded:: 2.4
:param user: The user that performed the action.
:type user: Union[:class:`User`, :class:`Member`]
:param answer: The answer the user voted or removed their vote from.
:type answer: :class:`PollAnswer`
.. function:: on_raw_poll_vote_add(payload)
on_raw_poll_vote_remove(payload)
Called when a :class:`Poll` gains or loses a vote. Unlike :func:`on_poll_vote_add` and :func:`on_poll_vote_remove`
this is called regardless of the state of the internal user and message cache.
This requires :attr:`Intents.message_content` and :attr:`Intents.polls` to be enabled.
.. note::
If the poll allows multiple answers and the user removes or adds multiple votes, this
event will be called as many times as votes that are added or removed.
.. versionadded:: 2.4
:param payload: The raw event payload data.
:type payload: :class:`RawPollVoteActionEvent`
Reactions Reactions
~~~~~~~~~~ ~~~~~~~~~~
@ -1745,6 +1786,30 @@ of :class:`enum.Enum`.
.. versionadded:: 2.2 .. versionadded:: 2.2
.. attribute:: guild_incident_alert_mode_enabled
The system message sent when security actions is enabled.
.. versionadded:: 2.4
.. attribute:: guild_incident_alert_mode_disabled
The system message sent when security actions is disabled.
.. versionadded:: 2.4
.. attribute:: guild_incident_report_raid
The system message sent when a raid is reported.
.. versionadded:: 2.4
.. attribute:: guild_incident_report_false_alarm
The system message sent when a false alarm is reported.
.. versionadded:: 2.4
.. class:: UserFlags .. class:: UserFlags
Represents Discord User flags. Represents Discord User flags.
@ -3212,6 +3277,12 @@ of :class:`enum.Enum`.
The ``ko`` locale. The ``ko`` locale.
.. attribute:: latin_american_spanish
The ``es-419`` locale.
.. versionadded:: 2.4
.. attribute:: lithuanian .. attribute:: lithuanian
The ``lt`` locale. The ``lt`` locale.
@ -3476,6 +3547,14 @@ of :class:`enum.Enum`.
.. versionadded:: 2.4 .. versionadded:: 2.4
.. attribute:: durable
The SKU is a durable one-time purchase.
.. attribute:: consumable
The SKU is a consumable one-time purchase.
.. attribute:: subscription .. attribute:: subscription
The SKU is a recurring subscription. The SKU is a recurring subscription.
@ -3491,6 +3570,34 @@ of :class:`enum.Enum`.
.. versionadded:: 2.4 .. versionadded:: 2.4
.. attribute:: purchase
The entitlement was purchased by the user.
.. attribute:: premium_subscription
The entitlement is for a nitro subscription.
.. attribute:: developer_gift
The entitlement was gifted by the developer.
.. attribute:: test_mode_purchase
The entitlement was purchased by a developer in application test mode.
.. attribute:: free_purchase
The entitlement was granted, when the SKU was free.
.. attribute:: user_gift
The entitlement was gifted by a another user.
.. attribute:: premium_purchase
The entitlement was claimed for free by a nitro subscriber.
.. attribute:: application_subscription .. attribute:: application_subscription
The entitlement was purchased as an app subscription. The entitlement was purchased as an app subscription.
@ -3511,6 +3618,51 @@ of :class:`enum.Enum`.
The entitlement owner is a user. The entitlement owner is a user.
.. class:: PollLayoutType
Represents how a poll answers are shown.
.. versionadded:: 2.4
.. attribute:: default
The default layout.
.. class:: InviteType
Represents the type of an invite.
.. versionadded:: 2.4
.. attribute:: guild
The invite is a guild invite.
.. attribute:: group_dm
The invite is a group DM invite.
.. attribute:: friend
The invite is a friend invite.
.. class:: ReactionType
Represents the type of a reaction.
.. versionadded:: 2.4
.. attribute:: normal
A normal reaction.
.. attribute:: burst
A burst reaction, also known as a "super reaction".
.. _discord-api-audit-logs: .. _discord-api-audit-logs:
Audit Log Data Audit Log Data
@ -4461,6 +4613,25 @@ Guild
:type: :class:`User` :type: :class:`User`
.. class:: BulkBanResult
A namedtuple which represents the result returned from :meth:`~Guild.bulk_ban`.
.. versionadded:: 2.4
.. attribute:: banned
The list of users that were banned. The inner :class:`Object` of the list
has the :attr:`Object.type` set to :class:`User`.
:type: List[:class:`Object`]
.. attribute:: failed
The list of users that could not be banned. The inner :class:`Object` of the list
has the :attr:`Object.type` set to :class:`User`.
:type: List[:class:`Object`]
ScheduledEvent ScheduledEvent
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
@ -4922,6 +5093,14 @@ RawAppCommandPermissionsUpdateEvent
.. autoclass:: RawAppCommandPermissionsUpdateEvent() .. autoclass:: RawAppCommandPermissionsUpdateEvent()
:members: :members:
RawPollVoteActionEvent
~~~~~~~~~~~~~~~~~~~~~~
.. attributetable:: RawPollVoteActionEvent
.. autoclass:: RawPollVoteActionEvent()
:members:
PartialWebhookGuild PartialWebhookGuild
~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~
@ -4938,6 +5117,14 @@ PartialWebhookChannel
.. autoclass:: PartialWebhookChannel() .. autoclass:: PartialWebhookChannel()
:members: :members:
PollAnswer
~~~~~~~~~~
.. attributetable:: PollAnswer
.. autoclass:: PollAnswer()
:members:
.. _discord_api_data: .. _discord_api_data:
Data Classes Data Classes
@ -5203,6 +5390,22 @@ ForumTag
.. autoclass:: ForumTag .. autoclass:: ForumTag
:members: :members:
Poll
~~~~
.. attributetable:: Poll
.. autoclass:: Poll
:members:
PollMedia
~~~~~~~~~
.. attributetable:: PollMedia
.. autoclass:: PollMedia
:members:
Exceptions Exceptions
------------ ------------

20
docs/ext/commands/commands.rst

@ -778,6 +778,19 @@ This tells the parser that the ``members`` attribute is mapped to a flag named `
the default value is an empty list. For greater customisability, the default can either be a value or a callable the default value is an empty list. For greater customisability, the default can either be a value or a callable
that takes the :class:`~ext.commands.Context` as a sole parameter. This callable can either be a function or a coroutine. that takes the :class:`~ext.commands.Context` as a sole parameter. This callable can either be a function or a coroutine.
A positional flag can be defined by setting the :attr:`~ext.commands.Flag.positional` attribute to ``True``. This
tells the parser that the content provided before the parsing occurs is part of the flag. This is useful for commands that
require a parameter to be used first and the flags are optional, such as the following:
.. code-block:: python3
class BanFlags(commands.FlagConverter):
members: List[discord.Member] = commands.flag(name='member', positional=True, default=lambda ctx: [])
reason: Optional[str] = None
.. note::
Only one positional flag is allowed in a flag converter.
In order to customise the flag syntax we also have a few options that can be passed to the class parameter list: In order to customise the flag syntax we also have a few options that can be passed to the class parameter list:
.. code-block:: python3 .. code-block:: python3
@ -797,11 +810,16 @@ In order to customise the flag syntax we also have a few options that can be pas
nsfw: Optional[bool] nsfw: Optional[bool]
slowmode: Optional[int] slowmode: Optional[int]
# Hello there --bold True
class Greeting(commands.FlagConverter):
text: str = commands.flag(positional=True)
bold: bool = False
.. note:: .. note::
Despite the similarities in these examples to command like arguments, the syntax and parser is not Despite the similarities in these examples to command like arguments, the syntax and parser is not
a command line parser. The syntax is mainly inspired by Discord's search bar input and as a result a command line parser. The syntax is mainly inspired by Discord's search bar input and as a result
all flags need a corresponding value. all flags need a corresponding value unless part of a positional flag.
Flag converters will only raise :exc:`~ext.commands.FlagError` derived exceptions. If an error is raised while Flag converters will only raise :exc:`~ext.commands.FlagError` derived exceptions. If an error is raised while
converting a flag, :exc:`~ext.commands.BadFlagArgument` is raised instead and the original exception converting a flag, :exc:`~ext.commands.BadFlagArgument` is raised instead and the original exception

47
docs/interactions/api.rst

@ -45,6 +45,14 @@ MessageInteraction
.. autoclass:: MessageInteraction() .. autoclass:: MessageInteraction()
:members: :members:
MessageInteractionMetadata
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. attributetable:: MessageInteractionMetadata
.. autoclass:: MessageInteractionMetadata()
:members:
Component Component
~~~~~~~~~~ ~~~~~~~~~~
@ -129,6 +137,22 @@ AppCommandPermissions
.. autoclass:: discord.app_commands.AppCommandPermissions() .. autoclass:: discord.app_commands.AppCommandPermissions()
:members: :members:
AppCommandContext
~~~~~~~~~~~~~~~~~
.. attributetable:: discord.app_commands.AppCommandContext
.. autoclass:: discord.app_commands.AppCommandContext
:members:
AppInstallationType
~~~~~~~~~~~~~~~~~~~~
.. attributetable:: discord.app_commands.AppInstallationType
.. autoclass:: discord.app_commands.AppInstallationType
:members:
GuildAppCommandPermissions GuildAppCommandPermissions
~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -310,7 +334,12 @@ Enumerations
.. attribute:: link .. attribute:: link
Represents a link button. Represents a link button.
.. attribute:: premium
Represents a gradient button denoting that buying a SKU is
required to perform this action.
.. versionadded:: 2.4
.. attribute:: blurple .. attribute:: blurple
An alias for :attr:`primary`. An alias for :attr:`primary`.
@ -642,6 +671,24 @@ Decorators
.. autofunction:: discord.app_commands.guild_only .. autofunction:: discord.app_commands.guild_only
:decorator: :decorator:
.. autofunction:: discord.app_commands.dm_only
:decorator:
.. autofunction:: discord.app_commands.private_channel_only
:decorator:
.. autofunction:: discord.app_commands.allowed_contexts
:decorator:
.. autofunction:: discord.app_commands.user_install
:decorator:
.. autofunction:: discord.app_commands.guild_install
:decorator:
.. autofunction:: discord.app_commands.allowed_installs
:decorator:
.. autofunction:: discord.app_commands.default_permissions .. autofunction:: discord.app_commands.default_permissions
:decorator: :decorator:

3592
docs/locale/ja/LC_MESSAGES/api.po

File diff suppressed because it is too large

2
docs/locale/ja/LC_MESSAGES/discord.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/ext/tasks/index.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/faq.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/intents.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/intro.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

14
docs/locale/ja/LC_MESSAGES/logging.po

@ -2,8 +2,8 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2024-03-26 03:41+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"
@ -46,18 +46,22 @@ msgid "This is recommended, especially at verbose levels such as ``DEBUG``, as t
msgstr "特に、 ``DEBUG`` といった冗長なイベントレベルを設定している場合、プログラムの標準エラー出力をつまらせてしまう原因になるため、ファイルへの出力が推奨されます。" msgstr "特に、 ``DEBUG`` といった冗長なイベントレベルを設定している場合、プログラムの標準エラー出力をつまらせてしまう原因になるため、ファイルへの出力が推奨されます。"
#: ../../logging.rst:46 #: ../../logging.rst:46
msgid "If you want the logging configuration the library provides to affect all loggers rather than just the ``discord`` logger, you can pass ``root_logger=True`` inside :meth:`Client.run`:"
msgstr ""
#: ../../logging.rst:52
msgid "If you want to setup logging using the library provided configuration without using :meth:`Client.run`, you can use :func:`discord.utils.setup_logging`:" msgid "If you want to setup logging using the library provided configuration without using :meth:`Client.run`, you can use :func:`discord.utils.setup_logging`:"
msgstr ":meth:`Client.run` を使用せずにライブラリ提供の構成を使用して logging を設定したい場合は、 :func:`discord.utils.setup_logging` を使用できます。" msgstr ":meth:`Client.run` を使用せずにライブラリ提供の構成を使用して logging を設定したい場合は、 :func:`discord.utils.setup_logging` を使用できます。"
#: ../../logging.rst:57 #: ../../logging.rst:63
msgid "More advanced setups are possible with the :mod:`logging` module. The example below configures a rotating file handler that outputs DEBUG output for everything the library outputs, except for HTTP requests:" msgid "More advanced setups are possible with the :mod:`logging` module. The example below configures a rotating file handler that outputs DEBUG output for everything the library outputs, except for HTTP requests:"
msgstr ":mod:`logging` モジュールを使用するとより高度なセットアップが行えます。以下の例では、HTTPリクエスト以外のすべてのライブラリの出力に対しDEBUG出力を使用するローテーションを行うファイルハンドラを構成します。" msgstr ":mod:`logging` モジュールを使用するとより高度なセットアップが行えます。以下の例では、HTTPリクエスト以外のすべてのライブラリの出力に対しDEBUG出力を使用するローテーションを行うファイルハンドラを構成します。"
#: ../../logging.rst:85 #: ../../logging.rst:91
msgid "For more information, check the documentation and tutorial of the :mod:`logging` module." msgid "For more information, check the documentation and tutorial of the :mod:`logging` module."
msgstr "詳細は、:mod:`logging` モジュールのドキュメントを参照してください。" msgstr "詳細は、:mod:`logging` モジュールのドキュメントを参照してください。"
#: ../../logging.rst:89 #: ../../logging.rst:95
msgid "The library now provides a default logging configuration." msgid "The library now provides a default logging configuration."
msgstr "ライブラリがデフォルト logging 構成を提供するようになりました。" msgstr "ライブラリがデフォルト logging 構成を提供するようになりました。"

2
docs/locale/ja/LC_MESSAGES/migrating.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/migrating_to_async.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/migrating_to_v1.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/quickstart.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/sphinx.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

2
docs/locale/ja/LC_MESSAGES/version_guarantees.po

@ -3,7 +3,7 @@ msgstr ""
"Project-Id-Version: discordpy\n" "Project-Id-Version: discordpy\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-06-21 01:17+0000\n" "POT-Creation-Date: 2023-06-21 01:17+0000\n"
"PO-Revision-Date: 2023-10-30 15:32\n" "PO-Revision-Date: 2024-04-17 02:43\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: Japanese\n" "Language-Team: Japanese\n"
"MIME-Version: 1.0\n" "MIME-Version: 1.0\n"

1814
docs/locale/ja/LC_MESSAGES/whats_new.po

File diff suppressed because it is too large

1
docs/whats_new.rst

@ -23,7 +23,6 @@ Bug Fixes
- Fix :attr:`Intents.emoji` and :attr:`Intents.emojis_and_stickers` having swapped alias values (:issue:`9471`). - Fix :attr:`Intents.emoji` and :attr:`Intents.emojis_and_stickers` having swapped alias values (:issue:`9471`).
- Fix ``NameError`` when using :meth:`abc.GuildChannel.create_invite` (:issue:`9505`). - Fix ``NameError`` when using :meth:`abc.GuildChannel.create_invite` (:issue:`9505`).
- Fix crash when disconnecting during the middle of a ``HELLO`` packet when using :class:`AutoShardedClient`. - Fix crash when disconnecting during the middle of a ``HELLO`` packet when using :class:`AutoShardedClient`.
- Fix overly eager escape behaviour for lists and header markdown in :func:`utils.escape_markdown` (:issue:`9516`).
- Fix voice websocket not being closed before being replaced by a new one (:issue:`9518`). - Fix voice websocket not being closed before being replaced by a new one (:issue:`9518`).
- |commands| Fix the wrong :meth:`~ext.commands.HelpCommand.on_help_command_error` being called when ejected from a cog. - |commands| Fix the wrong :meth:`~ext.commands.HelpCommand.on_help_command_error` being called when ejected from a cog.
- |commands| Fix ``=None`` being displayed in :attr:`~ext.commands.Command.signature`. - |commands| Fix ``=None`` being displayed in :attr:`~ext.commands.Command.signature`.

81
pyproject.toml

@ -1,7 +1,84 @@
[build-system] [build-system]
requires = ["setuptools", "wheel"] requires = ["setuptools"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project]
name = "discord.py"
description = "A Python wrapper for the Discord API"
readme = { file = "README.rst", content-type = "text/x-rst" }
license = { file = "LICENSE" }
requires-python = ">=3.8"
authors = [{ name = "Rapptz" }]
classifiers = [
"Development Status :: 5 - Production/Stable",
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Topic :: Internet",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: Utilities",
"Typing :: Typed",
]
dynamic = ["version", "dependencies"]
[project.urls]
Documentation = "https://discordpy.readthedocs.io/en/latest/"
"Issue tracker" = "https://github.com/Rapptz/discord.py/issues"
[tool.setuptools.dynamic]
dependencies = { file = "requirements.txt" }
[project.optional-dependencies]
voice = ["PyNaCl>=1.3.0,<1.6"]
docs = [
"sphinx==4.4.0",
"sphinxcontrib_trio==1.1.2",
# TODO: bump these when migrating to a newer Sphinx version
"sphinxcontrib-websupport==1.2.4",
"sphinxcontrib-applehelp==1.0.4",
"sphinxcontrib-devhelp==1.0.2",
"sphinxcontrib-htmlhelp==2.0.1",
"sphinxcontrib-jsmath==1.0.1",
"sphinxcontrib-qthelp==1.0.3",
"sphinxcontrib-serializinghtml==1.1.5",
"typing-extensions>=4.3,<5",
"sphinx-inline-tabs==2023.4.21",
]
speed = [
"orjson>=3.5.4",
"aiodns>=1.1",
"Brotli",
"cchardet==2.1.7; python_version < '3.10'",
]
test = [
"coverage[toml]",
"pytest",
"pytest-asyncio",
"pytest-cov",
"pytest-mock",
"typing-extensions>=4.3,<5",
"tzdata; sys_platform == 'win32'",
]
[tool.setuptools]
packages = [
"discord",
"discord.types",
"discord.ui",
"discord.webhook",
"discord.app_commands",
"discord.ext.commands",
"discord.ext.tasks",
]
include-package-data = true
[tool.black] [tool.black]
line-length = 125 line-length = 125
skip-string-normalization = true skip-string-normalization = true
@ -16,7 +93,7 @@ omit = [
[tool.coverage.report] [tool.coverage.report]
exclude_lines = [ exclude_lines = [
"pragma: no cover", "pragma: no cover",
"@overload" "@overload",
] ]
[tool.isort] [tool.isort]

1
requirements.txt

@ -1,2 +1 @@
aiohttp>=3.7.4,<4 aiohttp>=3.7.4,<4
async-timeout>=4.0,<5.0; python_version<"3.11"

130
setup.py

@ -1,105 +1,31 @@
from setuptools import setup from setuptools import setup
import re import re
requirements = [] def derive_version() -> str:
with open('requirements.txt') as f: version = ''
requirements = f.read().splitlines() with open('discord/__init__.py') as f:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1)
version = ''
with open('discord/__init__.py') as f: if not version:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', f.read(), re.MULTILINE).group(1) raise RuntimeError('version is not set')
if not version: if version.endswith(('a', 'b', 'rc')):
raise RuntimeError('version is not set') # append version identifier based on commit count
try:
if version.endswith(('a', 'b', 'rc')): import subprocess
# append version identifier based on commit count
try: p = subprocess.Popen(['git', 'rev-list', '--count', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
import subprocess out, err = p.communicate()
if out:
p = subprocess.Popen(['git', 'rev-list', '--count', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) version += out.decode('utf-8').strip()
out, err = p.communicate() p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if out: out, err = p.communicate()
version += out.decode('utf-8').strip() if out:
p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) version += '+g' + out.decode('utf-8').strip()
out, err = p.communicate() except Exception:
if out: pass
version += '+g' + out.decode('utf-8').strip()
except Exception: return version
pass
readme = '' setup(version=derive_version())
with open('README.rst') as f:
readme = f.read()
extras_require = {
'voice': ['PyNaCl>=1.3.0,<1.6'],
'docs': [
'sphinx==4.4.0',
'sphinxcontrib_trio==1.1.2',
'sphinxcontrib-websupport',
'typing-extensions>=4.3,<5',
'sphinx-inline-tabs',
],
'speed': [
'orjson>=3.5.4',
'aiodns>=1.1',
'Brotli',
'cchardet==2.1.7; python_version < "3.10"',
],
'test': [
'coverage[toml]',
'pytest',
'pytest-asyncio',
'pytest-cov',
'pytest-mock',
'typing-extensions>=4.3,<5',
'tzdata; sys_platform == "win32"',
],
}
packages = [
'discord',
'discord.types',
'discord.ui',
'discord.webhook',
'discord.app_commands',
'discord.ext.commands',
'discord.ext.tasks',
]
setup(
name='discord.py',
author='Rapptz',
url='https://github.com/Rapptz/discord.py',
project_urls={
'Documentation': 'https://discordpy.readthedocs.io/en/latest/',
'Issue tracker': 'https://github.com/Rapptz/discord.py/issues',
},
version=version,
packages=packages,
license='MIT',
description='A Python wrapper for the Discord API',
long_description=readme,
long_description_content_type='text/x-rst',
include_package_data=True,
install_requires=requirements,
extras_require=extras_require,
python_requires='>=3.8.0',
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Intended Audience :: Developers',
'Natural Language :: English',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Topic :: Internet',
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities',
'Typing :: Typed',
],
)

Loading…
Cancel
Save