简体   繁体   中英

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))

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.

To remove a role, you'll need to use the remove role method, and I Tested that it works like : member.remove_roles(role) The "role" is an role object, not the 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)  
      await member.remove_roles(role_get)  
      await bot.say("{} has been muted from chat".format(user.name))

Try that:

import discord
from discord.ext import commands

@bot.command()
@commands.has_role('staff')
async def mute(ctx, user: discord.Member):
    role = discord.utils.get(ctx.guild, name='member')
    await user.remove_roles(role)
    await ctx.send(f'{user.name} has been muted from chat')

Remove_roles function takes two parameters, first of which is the user from which the role and the role itself are removed. It is possible not to write 'user: discord .Member' in the function parameters, leave only 'ctx'. You also need the role you want to delete. role = get (ctx.author.guild.roles, name = "the name of the role you want to remove" (also include 'from discord.utils import get') and then call the function: 'await ctx.author.remove_roles (role)

from discord.utils import get



@bot.command(pass_context=True)
@commands.has_role('staff')
async def mute(ctx):
    await ctx.author..remove_roles(role)
    await ctx.send("{} has been muted from chat".format(user.name))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM