SilentVOEZ
SilentVOEZ

Reputation: 15

discord.py - How to purge messages from a mentioned user?

I have found this question but for some reason it doesn't when I mention a user. It doesn't show any errors on the terminal when I execute the command. The code looks like this from the question:

@commands.command()
@commands.has_permissions(manage_messages=True)
async def purge(self, ctx, num: int, user: discord.Member = None):
    if user:
        check_func = lambda msg: msg.author == user and not msg.pinned
    else:
        check_func = lambda msg: not msg.pinned
    await ctx.message.delete()
    await ctx.channel.purge(limit=num, check=check_func)
    await ctx.send(f'{num} messages deleted.', delete_after=5)

It works with only a number of messages like q!purge 5 but not with q!purge 5 @SomeUser#1234.

Upvotes: 0

Views: 3826

Answers (1)

Just for fun
Just for fun

Reputation: 4225

This can be done using Channel.history

@bot.command()
async def purge(ctx, limit=50, member: discord.Member=None):
    await ctx.message.delete()
    msg = []
    try:
        limit = int(limit)
    except:
        return await ctx.send("Please pass in an integer as limit")
    if not member:
        await ctx.channel.purge(limit=limit)
        return await ctx.send(f"Purged {limit} messages", delete_after=3)
    async for m in ctx.channel.history():
        if len(msg) == limit:
            break
        if m.author == member:
            msg.append(m)
    await ctx.channel.delete_messages(msg)
    await ctx.send(f"Purged {limit} messages of {member.mention}", delete_after=3)

Upvotes: 1

Related Questions