How can I make my Discord Bot delete all messages in a channel?

Viewed 892

I am trying to make my bot delete all messages at once when a user asks the bot to do so, but my code isn't working.

import os
import discord

client = discord.Client()
client = commands.Bot(command_prefix='+')
@client.command(name='effacer')

async def purge(ctx):
    async for msg in client.logs_from(ctx.message.channel):
        await client.delete_messages(msg)
    await ctx.send("Who am I? What is this place? And where the hell did the messages go?")

client.run(TOKEN)

How can I fix my code so that my bot can delete all messages? I believe my biggest problem is await client.delete_messages(msg), since Python continuously says that the client has no attribute to delete_messages.

2 Answers

By deleting every message would rate limit the bot, creating performance issues which would also slow down the bot. Instead it would be more efficient if the bot just deleted the channel and made a clone of it in the exact same place.

Here's the purge included in your command

@client.command(name='effacer')
async def purge(ctx):
        await ctx.channel.delete()
        new_channel = await ctx.channel.clone(reason="Channel was purged")
        await new_channel.edit(position=ctx.channel.position)
        await new_channel.send("Channel was purged")

So the way you would do that is with purge, not delete messages. This will delete all the messages in the channel AND keep the channel id the same, meaning you'll only need the manage_messages permission to run this command. The way it works is it counts all the messages in the channel and then purges that number of messages

import os
import discord

client = discord.Client()
client = commands.Bot(command_prefix='+')

@client.command(name='effacer')
async def purge(ctx):
    limit = 0
    async for msg in ctx.channel.history(limit=None):
        limit += 1
    await ctx.channel.purge(limit=limit)

client.run(TOKEN)
Related