改变颜色角色不和谐



首先,我想指出我是python的初学者。

我正在尝试编写一个命令,允许用户通过机器人更改其角色的颜色。但是,我遇到了许多我找不到答案的问题。

第一个问题是我无法访问调用命令的用户的角色。 然而,我决定跳过它,直接进入一个特定的角色。 所以我做了这个代码:

@client.command(pass_context=1)
async def changecolor(ctx, NewColor):
author = ctx.message.author
server = ctx.message.author.server
dictOfColors = { '1' : discord.Color.default(),
'2' : discord.Color.teal(),
'3' : discord.Color.dark_teal(),
'4' : discord.Color.green(),
'5' : discord.Color.dark_green(),
'6' : discord.Color.blue(),
'7' : discord.Color.purple(),
'8' : discord.Color.dark_purple(),
'9' : discord.Color.magenta(),
'10' : discord.Color.dark_magenta(),
'11' : discord.Color.gold(),
'12' : discord.Color.dark_gold(),
'13' : discord.Color.orange(),
'14' : discord.Color.dark_orange(),
'15' : discord.Color.red(),
'16' : discord.Color.dark_red() }
role = discord.utils.get(server.roles, name='New Member')
if NewColor in dictOfColors:
await client.edit_role(server, role, colour=NewColor)

但是当我尝试时:.changecolor 5收到此错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'

你能给我一个提示,说明我做错了什么吗?

可以使用角色转换器从角色提及中获取角色。 我也会让用户传递颜色的名称而不是数字:

@client.command(pass_context=True)
async def changecolor(ctx, role: discord.Role, *, color):
if role not in ctx.message.author.roles:
await bot.say("You do not have the role " + role.name)
return
color = '_'.join(color.lower().split())
if not hasattr(discord.Color, color):  # We could also use inspect.ismethod to only accept classmethod names
await bot.say("I do not recognize the color " + color)
return
await client.edit_role(ctx.message.server, role, colour=getattr(discord.Color, color)())

然后,您将用类似以下内容来称呼它:

!changecolor @NewMember dark gold

将最后一行更改为

await client.edit_role(server, role, colour=dictOfColors[NewColor])

您将字典中想要的颜色编号分配给colour属性,而不是该键处的值,即实际颜色。

最新更新