首页 > 解决方案 > AttributeError: 'NoneType' 对象没有属性 'roles' 添加角色时出错

问题描述

当我使用脚本时:

@bot.command()
async def agree(ctx):
  await ctx.author.send('Thank you for reading the Terms of Use, you should have access to the server now! (If you have not been given access please contact one of the staff members)')

  var = discord.utils.get(ctx.guild.roles, name = "Pogchamp")
  ctx.author.add_roles(var)

错误 :

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

有谁能够帮我?

标签: pythondiscord.py

解决方案


该错误AttributeError: 'NoneType' object has no attribute 'roles'是由于未等待该语句而发生的。

这是添加用户角色的部分

  ctx.author.add_roles(var)

这可以简单地纠正为:

  await ctx.author.add_roles(var)

如果您还想从命令中指定角色,这可以与role: discord.Role = None等待成员作者他们设置的角色一起使用,但在这种情况下,您似乎只想为同意 TOS 的用户提供设置的角色。

还要确保您启用了成员意图或至少启用了 Discord 提供的基本意图。另外,请确保您拥有允许使用 Discord 实用程序的主要导入

import discord
import discord.utils
from discord.ext import commands, tasks

推荐阅读