AttributeError: 'NoneType' object has no attribute 'roles'

AttributeError: 'NoneType' object has no attribute 'roles'

我一直在尝试使用 python 制作一个不和谐的机器人。该机器人根据 s/he 所在的房间将成员添加到另一个房间。当我尝试 运行 代码时,我不断收到此错误

AttributeError: 'NoneType' object has no attribute 'roles'

这是我得到错误的定义

def get_sibling_role(member):
roles = member.roles; ret = None #<==there is an issue on this
for role in roles:
    if role.name == "Brothers Waiting Room":
        ret = ("Brother", role); break
    elif role.name == "Sisters Waiting Room":
        ret = ("Sister", role); break
return ret

#我已经有会员定义了returns会员ID

谁能帮我找出定义中的问题?

显而易见的原因是成员的值为None。为避免这种情况,您可以添加“not None”的检查。我还假设错位是因为发布了有问题的代码而不是在代码中。

def get_sibling_role(member):
  if member is None:
    return None

  roles = member.roles; ret = None #<==there is an issue on this
  for role in roles:
     if role.name == "Brothers Waiting Room":
        ret = ("Brother", role); break
     elif role.name == "Sisters Waiting Room":
        ret = ("Sister", role); break
  return ret

NoneType 问题是许多程序员面临的一个错误discord.py,主要有几个原因

1- 我自己在上一题中的错误超出了给定的代码范围。我写的代码是正确的,但是,我在同一代码中定义了两个客户端实例,这让整个程序变得混乱,它为成员和角色返回 none,所以修改你的 discord.Client或 commands.Bot 构造函数。

client = discord.Client(intents=intents)

如果你想测试和调试,我建议在 on_ready(): 函数下使用以下代码打印服务器中的第一个成员。

print (guild.members[1])

2- 第二个常见错误是人们往往不使用意图,他们必须使用意图来获取成员 https://discordpy.readthedocs.io/en/latest/intents.html 此外,您应该按照不和谐门户 https://discord.com/developers/applications

中上一个文档中的说明启用它们(特权网关)

3- 将您的 discord.py 更新到版本 1.5.0。或更高。确保将其安装到正确的环境