Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you remove a role from a user?

I'm trying to remove a role from a user with a command but I'm not quite sure how the command works.

Here is the code:

@bot.command(pass_context=True)
@commands.has_role('staff')
async def mute(ctx, user: discord.Member):
    await bot.remove_roles(user, 'member')
    await bot.say("{} has been muted from chat".format(user.name))
like image 253
Umar Sharif Avatar asked Oct 28 '25 14:10

Umar Sharif


2 Answers

It looks like remove_roles needs a Role object, not just the name of the role. We can use discord.utils.get to get the role

from discord.utils import get

@bot.command(pass_context=True)
@commands.has_role('staff')
async def mute(ctx, user: discord.Member):
    role = get(ctx.message.server.roles, name='member')
    await bot.remove_roles(user, role)
    await bot.say("{} has been muted from chat".format(user.name))

I don't know what happens if you try to remove a role that the target member doesn't have, so you might want to throw in some checks. This might also fail if you try to remove roles from an server admin, so you might want to check for that too.

like image 166
Patrick Haugh Avatar answered Oct 31 '25 03:10

Patrick Haugh


To remove a role, you'll need to use the remove_roles() method. It works like this:

member.remove_roles(role)

The "role" is a role object, not the (role's) name, so it should be:

role_get = get(member.guild.roles, id=role_id)  
await member.remove_roles(role_get)

With your code:

@bot.command(pass_context=True)
@commands.has_role('staff')
async def mute(ctx, user: discord.Member):
    role_get = get(member.guild.roles, id=role_id) #Returns a role object.
    await member.remove_roles(role_get) #Remove the role (object) from the user.
    await bot.say("{} has been muted from chat".format(user.name))
like image 36
I'm a Coder Avatar answered Oct 31 '25 03:10

I'm a Coder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!