如果有人发送诸如 !color
之类的消息,我想删除一个角色
我在网上搜索并找到了这样的解决方案:
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == '!color':
role = get(message.guild.roles, name = 'common')
if role:
await message.author.delete_role(role)
但是,这段代码有两个问题。第一个问题是 if role
语句。即使用户没有角色,它仍然会进入 await message.author.delete_role(role)
。其次,当我运行 await message.author.delete_role(role)
时,它返回错误 AttributeError: 'Member' object has no attribute 'delete_role'
。我怎样才能解决这个问题?谢谢。
这里是整个错误信息:
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 358, in on_message
await message.author.delete_role(role)
AttributeError: 'Member' object has no attribute 'delete_role'
答案 0 :(得分:0)
delete_role
不对。相反,您应该使用 remove_roles
。下面是一个使用 commands extension 的例子。我还在下面的示例中包含了 add_roles
。
@client.command()
async def colour(ctx, colour="red"):
colour = colour.lower()
if colour == "red":
role = get(ctx.guild.roles, name="common") # the role name you provided, common
colour = get(ctx.guild.roles, name="red") # for adding colour
await ctx.author.remove_roles(role) # await remove_roles(*roles, reason=None, atomic=True)
await ctx.author.add_roles(colour) # await add_roles(*roles, reason=None, atomic=True)