如何使Discord机器人命令赋予用户角色?

时间:2019-12-21 19:55:54

标签: python discord.py

我想创建一个无需提及用户即可赋予用户角色的命令,但我不知道该怎么做。

代码:

@bot.command()
async def blog(ctx, member: discord.Member = None):
    role = discord.utils.get(ctx.guild.roles, name='abbonato-blogger')
    await member.add_roles(role)
    await ctx.send('fatto.')

错误:

PS C:\Users\Fred\Desktop\Cyberpapera2.0> & C:/Python/Python37/python.exe c:/Users/Fred/Desktop/Cyberpapera2.0/bot.py
Ignoring exception in command blog:
Traceback (most recent call last):
  File "C:\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 79, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:/Users/Fred/Desktop/Cyberpapera2.0/bot.py", line 632, in blog
    await member.add_roles(role)
AttributeError: 'NoneType' object has no attribute 'add_roles'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python\Python37\lib\site-packages\discord\ext\commands\bot.py", line 863, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 728, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Python\Python37\lib\site-packages\discord\ext\commands\core.py", line 88, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'add_roles'

1 个答案:

答案 0 :(得分:0)

您的错误是由于member的默认值为None
当不带任何参数调用命令时,例如通过!blogmember将是None,因此,当到达行await member.add_roles(role)时,就会出现AttributeError,并告诉您'NoneType' object has no attribute 'add_roles'

您应该处理默认值大小写并检查member is None的时间。
另外,如果您不想在未传递member时处理命令,则可以完全删除默认值并处理MissingRequiredArgument exception