首页 > 解决方案 > AttributeError:“NoneType”对象没有属性“角色”

问题描述

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

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

#我已经定义了返回成员ID的成员

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

标签: discordbotspython-3.6typeerrordiscord.py

解决方案


显而易见的原因是 member 的值为 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

推荐阅读