danielmike293
danielmike293

Reputation: 33

Delete messages from specifc user using Discord py

I wanted to create a clear command where if example .clear @user#0000 100 it will clear the last 100 messages @user#0000 sent. Here is my code:

    @commands.command()
    @commands.has_permissions(manage_messages=True)
    async def clear(self, ctx, amount=1):
        await ctx.channel.purge(limit=amount + 1)
    @clear.error
    async def clear_error(self, ctx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.send('Sorry, you are missing the ``MANAGE_MESSAGES`` permission to use this command.')

This code i provided only deletes depeneding how many messages will be deleted in a channel. I want to make a code where the bot will delete messages from a specific user. If this is possible, please let me know. I will use the code as future reference. Much appreciated.

Upvotes: 3

Views: 1023

Answers (1)

Ratery
Ratery

Reputation: 2917

You can use check kwarg to purge messages from specific user:

from typing import Optional 

@commands.command()
@commands.has_permissions(manage_messages=True)
async def clear(self, ctx, member: Optional[discord.Member], amount: int = 1):
    def _check(message):
        if member is None:
            return True
        else:
            if message.author != member:
                return False
            _check.count += 1
            return _check.count <= amount
    _check.count = 0
    await ctx.channel.purge(limit=amount + 1 if member is None else 1000, check=_check)

Upvotes: 1

Related Questions