Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discord.py | add role to someone

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)
like image 684
BasicCoderr Avatar asked Mar 02 '18 20:03

BasicCoderr


People also ask

How do you get a bot to mention a 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.


2 Answers

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

like image 94
Patrick Haugh Avatar answered Sep 19 '22 01:09

Patrick Haugh


@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}")
like image 26
Mr Fuzzy Avatar answered Sep 18 '22 01:09

Mr Fuzzy