首页 > 解决方案 > 命令引发异常:AttributeError: 'Context' object has no attribute 'id' discord.py

问题描述

我想使用命令删除 JSON 文件中的公会 ID。

这是我的代码:

 @welcome.command(pass_context=True)
    @commands.has_permissions(administrator=True)
    async def reset(guild):
        with open('welcome.json', 'r') as f:
            welcome = json.load(f)
    
        welcome.pop(str(guild.id))
        with open('welcome.json', 'w',) as f:
            json.dump(welcomereset, f, indent=4)

这是错误消息:discord.ext.commands.errors.CommandInvokeError:命令引发异常:AttributeError:'Context'对象没有属性'id'

我怎样才能解决这个问题?

标签: pythondiscord.py

解决方案


 @welcome.command() #pass_context is deprecated, every command will always get passes Context as first param.
 @commands.has_permissions(administrator=True)
 async def reset(ctx: commands.Context): #Just normal typehint for you to easily understand.
        with open('welcome.json', 'r') as f:
            welcome = json.load(f)
    
        welcome.pop(str(ctx.guild.id)) #ctx.guild -> discord.Guild and than .id for it's id. I would put an if statement to check if the command was even in a guild, so NoneType attribute error won't raise.
        with open('welcome.json', 'w',) as f:
            json.dump(welcomereset, f, indent=4)

每个命令中的第一个参数是 ctx 或 context 代表 discord.ext.commands.Context 对象,如您所见,它没有 id。如果您试图获取调用命令的公会 ID,则执行 ctx.guild 将返回 Optional[discord.Guild](如果命令是在私人频道中调用的)。如果它不是 None,你可以做 ctx.guild.id,这可能是你想要的。而且您不再需要 pass_context(用于传递 discord.ext.commands.Context btw)。这意味着现在,guild 是您的 Context 对象。


推荐阅读