pythonerror-handlingdiscord.pypurge

how do i fix my purge function in discord.py?


this is my purge command. I am very new to slash commands.

@bot.command(name="purge", description="Purge a specific amount of messages.", guild=guild_ID)
@commands.guild_only()
@commands.has_permissions(manage_messages=True)
async def purge(ctx: discord.Interaction, num_messages: int):

    if num_messages < 1:
        await ctx.response.send_message("You must provide a valid number of messages to delete.", ephemeral=True)
        return

    deleted = await ctx.channel.purge(limit=num_messages)
    embed = discord.Embed(title="", description=f"✅ Deleted {len(deleted)} messages.")
    await ctx.response.send_message("", ephemeral=True, embed=embed)

this is the error i am geting "404 Not Found (error code: 10062): Unknown interaction"

I have now tried searching everywhere on github/stackoverflow to find a solution on my problem


Solution

  • The decorator @bot.command creates a text command (those that are triggered by messages using the bot prefix). If you want to create an application command, also known as Slash Command, you should use decorator @app_commands.app_command or @bot.hybrid_command to create a command hybrid (will work for both text and interaction using /).

    @bot.hybrid_command(name="purge")
    @commands.guild_only()
    @commands.has_permissions(manage_messages=True)
    async def purge(ctx: commands.Context, num_messages: commands.Range[int, 1]):
        """Purge a specific amount of messages
    
        Args:
           num_messages: the amount of messages to delete
        """
        deleted = await ctx.channel.purge(limit=num_messages)
        embed = discord.Embed(description=f"✅ Deleted {len(deleted)} messages.")
        await ctx.reply(ephemeral=True, embed=embed)
    
    • Note that I used commands.Range to ensure that num_messages will be a larger integer that 1. So you don't need to check this value;
    • I'm using docstrings to describe the function of the command and arguments. These descriptions will automatically be used by the application commands;
    • You will need to sync your commands with discord whenever you create a new one or change their syntax (parameters, name, descriptions).