How to purge messages for specific users in Discord.py

3.6k views Asked by At

Hey so I was trying to make a command in discord.py rewrite version was doing something like >purgemessage 5 would purge 5 messages of the user who sent that message but for some reason, it won't work. I am using this in a reply so it won't show the error;-; but here is what I have done so far to try to make it work!

# purges author's messages
@commands.command(name='purgemessage', aliases=['pm'])
@commands.cooldown(1, 300)
@commands.has_any_role(OwnerRole, GuildMasterRole, AdminRole, ExclusiveMemberRole)
async def purgemessage(self, ctx, amount:int, *, arg:str=None):
    msg = []
    channel = ctx.message.channel.history(limit=None)
    async for message in channel:
        if message.author == ctx.message.author:
            msg.append(message)
    await ctx.message.channel.delete_messages(msg)
    await asyncio.sleep(.5)
    botMessage = await ctx.send(f'**{amount}** messages were successfully deleted!')
    await asyncio.sleep(.5)
    await botMessage.delete()
1

There are 1 answers

4
Allister On

I haven't done thorough tests, but the first error I am getting (after rewriting to work outside a cog so I could quickly test), is

discord.errors.HTTPException: 400 Bad Request (error code: 50034): You can only bulk delete messages that are under 14 days old.

This error might be caused by your code not containing anything to stop adding messages after reaching amount, and continuing backward for a user's entire history in a channel.
This could very well not be the error you're getting, depending on the channel you're testing in. I would highly recommend you start working on an environment that will show you errors so we can help you better.
I don't know enough to debug the code you've given, but here's something that does what you want in less code and I know works:

channel = ctx.channel
await channel.purge(limit=amount, check=lambda message: message.author == ctx.author)

ctx.channel is the channel the command was sent in, ctx.author is who sent it.
channel.purge will purge limit amount of messages that meet the check function, which in this case is a lambda (a function defined in one line, looks like this: lambda argument: expression. The lambda will implictly return the expression).

The check keyword will pass message as an argument, so I've named by lambda argument appropriately. The expression checks that the message we're checking (message.author) was written by the invoker of the command (ctx.author).

This code works, even for messages over 14 days old, but it does take some time for larger amounts of messages.