Add app_commands.guilds to set the guilds of a command in another way

This is mostly preparation for interopability with commands.Cog as this
would allow authors to specify the guilds for their cog defined
commands.
This commit is contained in:
Rapptz
2022-03-08 00:48:24 -05:00
parent 5fb1b933cf
commit 25b4bc277b
2 changed files with 62 additions and 5 deletions

View File

@@ -56,6 +56,7 @@ from ..utils import resolve_annotation, MISSING, is_inside_class
if TYPE_CHECKING:
from typing_extensions import ParamSpec, Concatenate
from ..abc import Snowflake
from .namespace import Namespace
from .models import ChoiceT
@@ -68,6 +69,7 @@ __all__ = (
'describe',
'choices',
'autocomplete',
'guilds',
)
if TYPE_CHECKING:
@@ -1067,3 +1069,49 @@ def autocomplete(**parameters: AutocompleteCallback[GroupT, ChoiceT]) -> Callabl
return inner
return decorator
def guilds(*guild_ids: Union[Snowflake, int]) -> Callable[[T], T]:
r"""Associates the given guilds with the command.
When the command instance is added to a :class:`CommandTree`, the guilds that are
specified by this decorator become the default guilds that it's added to rather
than being a global command.
.. note::
Due to an implementation quirk and Python limitation, if this is used in conjunction
with the :meth:`CommandTree.command` or :meth:`CommandTree.context_menu` decorator
then this must go below that decorator.
Example:
.. code-block:: python3
MY_GUILD_ID = discord.Object(...) # Guild ID here
@app_commands.command()
@app_commands.guilds(MY_GUILD_ID)
async def bonk(interaction: discord.Interaction):
await interaction.response.send_message('Bonk', ephemeral=True)
Parameters
-----------
\*guild_ids: Union[:class:`int`, :class:`~discord.abc.Snowflake`]
The guilds to associate this command with. The command tree will
use this as the default when added rather than adding it as a global
command.
"""
defaults: List[int] = [g if isinstance(g, int) else g.id for g in guild_ids]
def decorator(inner: T) -> T:
if isinstance(inner, Command):
inner._callback.__discord_app_commands_default_guilds__ = defaults
else:
# Runtime attribute assignment
inner.__discord_app_commands_default_guilds__ = defaults # type: ignore
return inner
return decorator