Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Discord.py delete all messages in a text channel

I am trying to make my Discord bot delete all messages in a text channel, but I can't figure out how to do it. This is what I have tried:

@CLIENT.command()
async def Clear(message):
    return await CLIENT.delete_message(message)

I have tried other things and looked at other posts, but I have only found out that the bot will delete the message I type every time (not what I'm looking for).

like image 795
Tyrell Avatar asked Apr 18 '17 06:04

Tyrell


2 Answers

If you wanted to bulk delete messages (that is, delete a number of messages at once, use await Client.delete_messages(list_of_messages). Here's an example

import asyncio
import discord
from discord.ext.commands import Bot

Client = Bot('!')


@Client.command(pass_context = True)
async def clear(ctx, number):
    mgs = [] #Empty list to put all the messages in the log
    number = int(number) #Converting the amount of messages to delete to an integer
    async for x in Client.logs_from(ctx.message.channel, limit = number):
        mgs.append(x)
    await Client.delete_messages(mgs)

Client.run(Token)

NOTE: Doing this will only work for messages 14 days old and under and you can't delete above 100 messages at a time, meaning typing this !clear 120 would raise an error. However, its not impossible. You can add a while loop in there if you really wanted to but that may produce unexpected results.

Now, what if you have messages older than 14 days? You can't use Client.delete_messages(list_of_messages). Instead, you can use Client.delete_message(Message) this would delete only one message at a time. Yes, I know slow but for now, that's all we've got. So, you can modify the original code to have it delete each time it loops in the logs_from().

Something like this:

import asyncio
import discord
from discord.ext.commands import Bot

Client = Bot('!')

@Client.command(pass_context = True)
async def clear(ctx, number):
    number = int(number) #Converting the amount of messages to delete to an integer
    counter = 0
    async for x in Client.logs_from(ctx.message.channel, limit = number):
        if counter < number:
            await Client.delete_message(x)
            counter += 1
            await asyncio.sleep(1.2) #1.2 second timer so the deleting process can be even

Client.run(Token)
like image 94
Wright Avatar answered Nov 09 '22 20:11

Wright


client = commands.Bot(command_prefix='-')

@client.command(name='clear', help='this command will clear msgs')
async def clear(ctx, amount = 5):
    await ctx.channel.purge(limit=amount)

if the number of messages to be deleted is not mentioned, by default it will delete 4 messages i.e (amount-1)

use command -clear or -clear [number] to delete the messages. Don't use brackets in the previous line after writing 'clear'

like image 34
Souvik Guria Avatar answered Nov 09 '22 21:11

Souvik Guria