Search code examples
python-3.xpycord

Clear by user command does not clear all messages by user


I was trying to make a command that clears specified number of messages by a particular user, I am new to discord.py, my problem is that the command doesn't clear messages if any other user has sent a message/interrupted messages of the specified user. Eg:

User 1: A
User 2: B
User 1: A
User 1: A

I try to clear 3 messages by user 1, but it clears only the last 2 and not the one that comes before User 2 sent a message. Here's my code:

@bot.slash_command(description='Clears messages by a specified user.')
async def user_clear(ctx,amount:int, member:discord.Member):
  def check(message):
    return message.author==member
  await ctx.channel.purge(check=check,limit=amount)
  await ctx.respond(f"Cleared {amount} messages by {member}!")

I'd appreciate any help!


Solution

  • Here's one which works:

    @bot.command()
    async def user_clear(ctx: commands.Context, amount: int, member: discord.Member = None):
        counter = 0
        async for message in ctx.channel.history(limit=100, before=ctx.message):
            if counter < amount and message.author == member:
                await message.delete()
                counter += 1
    
        await ctx.channel.send(f"Cleared {amount} messages by {member}!")