Source code for discord.commands.permissions

# SPDX-License-Identifier: MIT

from typing import Callable

from ..permissions import Permissions
from .core import ApplicationCommand

__all__ = ("default_permissions", "guild_only", "is_nsfw")


[docs]def default_permissions(**perms: bool) -> Callable: """A decorator that limits the usage of a slash command to members with certain permissions. The permissions passed in must be exactly like the properties shown under :class:`.discord.Permissions`. .. note:: These permissions can be updated by server administrators per-guild. As such, these are only "defaults", as the name suggests. If you want to make sure that a user **always** has the specified permissions regardless, you should use an internal check such as :func:`~.ext.commands.has_permissions`. Parameters ---------- **perms: Dict[:class:`str`, :class:`bool`] An argument list of permissions to check for. Example ------- .. code-block:: python3 from discord import default_permissions @bot.slash_command() @default_permissions(manage_messages=True) async def test(ctx): await ctx.respond('You can manage messages.') """ invalid = set(perms) - set(Permissions.VALID_FLAGS) if invalid: raise TypeError(f"Invalid permission(s): {', '.join(invalid)}") def inner(command: Callable): if isinstance(command, ApplicationCommand): if command.parent is not None: raise RuntimeError( "Permission restrictions can only be set on top-level commands" ) command.default_member_permissions = Permissions(**perms) else: command.__default_member_permissions__ = Permissions(**perms) return command return inner
[docs]def guild_only() -> Callable: """A decorator that limits the usage of a slash command to guild contexts. The command won't be able to be used in private message channels. Example ------- .. code-block:: python3 from discord import guild_only @bot.slash_command() @guild_only() async def test(ctx): await ctx.respond("You're in a guild.") """ def inner(command: Callable): if isinstance(command, ApplicationCommand): command.guild_only = True else: command.__guild_only__ = True return command return inner
[docs]def is_nsfw() -> Callable: """A decorator that limits the usage of a slash command to 18+ channels and users. In guilds, the command will only be able to be used in channels marked as NSFW. In DMs, users must have opted into age-restricted commands via privacy settings. Note that apps intending to be listed in the App Directory cannot have NSFW commands. Example ------- .. code-block:: python3 from discord import is_nsfw @bot.slash_command() @is_nsfw() async def test(ctx): await ctx.respond("This command is age restricted.") """ def inner(command: Callable): if isinstance(command, ApplicationCommand): command.nsfw = True else: command.__nsfw__ = True return command return inner