I have trouble with making an "add role" command in discord.py. I don't know what is wrong; it just doesn't work.
@client.command()
@commands.has_role("Admin")
async def addrole(ctx):
user = ctx.message.author
role = discord.utils.get(user.server.roles, name="Test")
await client.add_roles(user, role)
From any text channel, simply type @(The name of the role) , select it, and hit enter. You can also mention roles by ID. This is useful for programmers who write bots for Discord, or create Webhooks, because if the name of the role changes, the mention still works.
from discord.ext import commands
from discord.utils import get
bot = commands.Bot(command_prefix='!')
@bot.command(pass_context=True)
@commands.has_role("Admin") # This must be exactly the name of the appropriate role
async def addrole(ctx):
member = ctx.message.author
role = get(member.server.roles, name="Test")
await bot.add_roles(member, role)
I think the only real mistake in your code is the lack of pass_context=True
in the @bot.command
decorator. You may have seen some code without this, but that likely belongs to the experimental "rewrite" branch of discord.py
@bot.command(pass_context=True)
async def giverole(ctx, user: discord.Member, role: discord.Role):
await user.add_roles(role)
await ctx.send(f"hey {ctx.author.name}, {user.name} has been giving a role called: {role.name}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With