Ask coding questions

← Back to all posts
How do you make a working purge command
CUSULe (0)

I have been trying for a long time now

Comments
hotnewtop
LD1 (52)

You would use channel.purge() to do this. Here is an example command:

@bot.command(name="purge")
@commands.has_guild_permissions(manage_messages=True)
async def purge(ctx, limit: int):
    if limit > 1000:
        await ctx.send("You can only purge up to 1000 messages")
        return
    elif limit < 1:
        await ctx.send("You must purge at least 1 message")
        return

    await ctx.channel.purge(limit=limit)

Two things to note. First off, you are using discord.Client instead of discord.ext.commands.Bot. You should always use Bot, never use Client (unless you're making a self bot ig).

All you have to do is replace

client = discord.Client()

with

bot = discord.ext.commands.Bot(command_prefix="!")

Also, you should add this to your imports:

from discord.ext import commands
epicseg (3)

Here you go! This command will only work for admins.

@bot.command(pass_context=True)
@commands.has_permissions(administrator=True)
async def purge(ctx, number: int):
    if not ctx.message.channel.permissions_for(ctx.message.author.guild.me).manage_messages:
        await ctx.send("I do not have permission to delete messages.")
        return
    if number > 200:
        await ctx.send("Please specify a lower number. Discord rate limits us, so we cant really go any higher :(")
        return
    to_delete = []
    async for message in ctx.message.channel.history(limit=number+1):
        to_delete.append(message)
    while to_delete:
        if len(to_delete) > 1:
            await ctx.message.channel.delete_messages(to_delete[:100])
            to_delete = to_delete[100:]
        else:
            await to_delete.delete()
            to_delete = []
        await asyncio.sleep(1.5)
epicseg (3)

Change bot to client. @CUSULe

LD1 (52)

@epicseg This isn't really a good way. It's slow and likely to hit the API ratelimit.

epicseg (3)

@LD1 Better then nothing, but it’s somthing

LD1 (52)

Why not just use channel.purge()? It's litteraly an API endpoint that discord has ended for this purpose. @epicseg

epicseg (3)

@LD1 idk I’m not really good at coding. Srry

LD1 (52)

@epicseg No need to apologize, I was just wondering.