首页 > 解决方案 > 如何修复discord.py中的“名称'服务器'未定义”错误

问题描述

我正在为我的不和谐服务器设置一个 python 机器人。我正在尝试添加一个功能,当人们加入时,他们会键入 - 机器人会将他们分配给所述角色

我试图通过使用 message.roles 和 server.roles 来分配我想要的角色,但两者仍然以同样的错误为食。

BOT_PREFIX = ('-')

...

#ComputerScience
@client.command(pass_context = True)
async def Cs(member, *roles):
    role = discord.utils.get(server.roles, name="ComputerScience")
    await client.add_role(member, role)

当在聊天中输入“-Cs”时,它显示给他们计算机科学角色,但我得到:“忽略命令 Cs 中的异常...... NameError:名称'服务器'未定义”

标签: pythondiscord.py

解决方案


您正在传递调用 context,但未在命令的函数签名中接受它。该上下文是您可以从中获取信息的server地方:

@client.command(pass_context = True)
async def Cs(ctx):
    role = discord.utils.get(ctx.message.server.roles, name="ComputerScience")
    await client.add_role(ctx.message.author, role)

推荐阅读