- 1 year ago
Adding Roles In Slash Commands (Discord.Py)
To add roles to slash commands in Discord.py, you can use the @slash.subcommand
decorator to define subcommands and their properties. Within this decorator, you can use the @slash.option
decorator to specify the options for the subcommand, including roles. Here's an example:
pythonimport discord
from discord_slash import SlashCommand, SlashContext
from discord_slash.utils.manage_commands import create_option, create_choice
client = discord.Client(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
@slash.subcommand(base="roles", name="add", description="Add a role to a user")
async def roles_add(ctx: SlashContext, user: discord.Member, role: discord.Role):
await user.add_roles(role)
await ctx.send(f"Added {role.name} to {user.display_name}")
roles_add.add_option(create_option(name="user", description="Select a user", option_type=6, required=True))
roles_add.add_option(create_option(name="role", description="Select a role", option_type=8, required=True))
In this example, we're defining a subcommand called roles add
that takes two options: user
(a user to add a role to) and role
(a role to add to the user). The create_option
function is used to define these options and their properties.
To add roles to the subcommand, we use the create_choice
function to create a list of role choices, and then pass this list to the choices
parameter of the create_option
function. The option_type
parameter specifies the type of the option, which is 6 for users and 8 for roles.
Once the subcommand and its options are defined, you can register the command with Discord using the sync_commands=True
parameter in the SlashCommand
constructor, and it will be available for use in your server.