Python 如何从用户中删除角色?

Python 如何从用户中删除角色?,python,discord.py,Python,Discord.py,我试图用命令从用户中删除角色,但我不太确定该命令是如何工作的 代码如下: @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))

我试图用命令从用户中删除角色,但我不太确定该命令是如何工作的

代码如下:

@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))
它似乎需要一个
角色
对象,而不仅仅是角色的名称。我们可以使用
discord.utils.get
来获取角色

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))
我不知道如果您试图删除目标成员没有的角色会发生什么,因此您可能需要进行一些检查。如果您试图从服务器管理员中删除角色,此操作也可能失败,因此您可能还需要检查此操作。

请尝试:

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函数有两个参数,第一个参数是从中删除角色的用户和角色本身。可以不在函数参数中写入“user:discord.Member”,只保留“ctx”。您还需要要删除的角色。role=get(ctx.author.guild.roles,name=“要删除的角色的名称”(还包括“from discord.utils import get”),然后调用函数:“wait 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))