Skip to content
Advertisement

Command raised an exception: AttributeError: ‘Context’ object has no attribute ‘id’ discord.py

I want to delete the Guild ID in a JSON file with an Command.

This is my code:

 @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)

This is the Error Message: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: ‘Context’ object has no attribute ‘id’

How can i fix this?

Advertisement

Answer

 @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)

The first parameter in each command is ctx or context the represents discord.ext.commands.Context object, which as you can see, doesn’t have id. If you are trying to get the guild id of where the command was invoked, doing ctx.guild will return Optional[discord.Guild](if command was invoked in a private channel). And than if it is not None, you can do ctx.guild.id, which is probably what you want. And you no longer need pass_context(which was used to pass discord.ext.commands.Context btw). Which means the right now, guild is your Context object.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement