【问题标题】:AttributeError: 'NoneType' object has no attribute 'roles'AttributeError:“NoneType”对象没有属性“角色”
【发布时间】:2021-02-08 03:18:36
【问题描述】:

我一直在尝试使用 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的成员

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

【问题讨论】:

  • 显然memberNone。调用此函数时仔细检查您的数据。
  • 你是对的,memberNone。当我尝试单独打印时,它打印了None。我现在正试图看看如何避免让它变空,看看那部分有什么问题。感谢您的帮助。

标签: discord bots python-3.6 typeerror discord.py


【解决方案1】:

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

【讨论】:

  • 没错,它是空的。现在我将看看如何避免让成员为空。谢谢
【解决方案2】:

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

1- 我自己在上一个问题中的错误超出了给定的代码。我写的代码是正确的,但是,我在同一代码中定义了两个客户端实例,这使整个程序变得混乱,成员和角色都没有返回任何内容,因此请修改您的 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 版。或更高。确保将其安装到正确的环境中


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-01
    • 2021-12-26
    • 2019-07-23
    • 2018-05-13
    • 2020-09-07
    • 2017-05-03
    • 2023-03-16
    • 2018-07-14
    相关资源
    最近更新 更多