【问题标题】:Why error - AttributeError: 'NoneType' object has no attribute为什么错误 - AttributeError: 'NoneType' 对象没有属性
【发布时间】:2021-03-08 17:50:38
【问题描述】:

我只是编写 discord bot,需要帮助来为用户添加角色。

我用过脚本:

import discord #first script line

bot = discord.Client()


@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" //help"))
guild_count = 0

for guild in bot.guilds:
    print(f"- {guild.id} (name: {guild.name})")

    guild_count = guild_count + 1
print("Verify bot is in " + str(guild_count) + " guilds.")

@bot.event
async def on_message(message):
if message.content == "//verify": #first command
    member = message.author
    wait_until_ready()
    var = discord.utils.get(message.guild.roles, name="verifyed")
    await member.add_roles(var)
    await message.author.send("You are verifyed on server! Thanks for using!")
    await message.author.send("Vote for our bot : **we are not in bot list already**")
    embed = discord.Embed(title='Verify',description='User verifyed! Use **//verify to verify your self!')
    await message.add_reaction('✅')
    embed.set_footer(text="Coded by Puk3l YT#2657")
    await message.channel.send(message.channel, embed=embed)

然后我刚刚测试了代码,得到了错误消息:

Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
  File "C:\Users\mykem\Desktop\bot\online_bot.py", line 23, in on_message
    await member.add_roles(var)
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site- packages\discord\member.py", line 676, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

我能做什么?有人能帮我吗?谢谢大家的回答

【问题讨论】:

  • 确保在discord.utils.get() 行中输入正确的角色名称。检查标点符号,即大写和小写字母。

标签: python discord discord.py


【解决方案1】:

代码:

var = discord.utils.get(message.guild.roles, name="verifyed")
await member.add_roles(var)

追溯:

    await member.add_roles(var)
  File "C:\Users\mykem\AppData\Local\Programs\Python\Python38-32\lib\site- packages\discord\member.py", line 676, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'

错误是它试图获取角色但找不到任何角色。 varNone 而不是 discord.Role 类型的对象。因此,您随后的电话 await member.add_roles(var) 失败。您需要添加一个确保var 有效的条件。

例如

if var:
  await member.add_roles(var)
else:
  print("role could not be found")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2017-03-10
    • 2019-07-18
    • 2018-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多