python Discord.py删除文本通道中的所有消息

Tyr*_*ell 4 python python-3.x discord

所以我试图让我的不和谐机器人删除文本频道中的所有消息,因为我喜欢它,当它很干净,但我不知道如何做到这是我试过的

@CLIENT.command()
async def Clear(message):
    return await CLIENT.delete_message(message)
Run Code Online (Sandbox Code Playgroud)

似乎无法弄明白有人可以帮助谢谢<3我已经尝试了其他的东西并查看了其他帖子但我只发现机器人将每次我键入时删除该消息(不是我正在寻找的)

小智 8

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)
Run Code Online (Sandbox Code Playgroud)

如果没有提到要删除的消息数量,默认会删除4条消息,即(amount-1)

使用命令-clear-clear [number]来删除消息。写完“clear”后,不要在上一行中使用括号


Wri*_*ght 7

如果您想批量删除邮件(即,一次删除一些邮件,请使用await Client.delete_messages(list_of_messages).这是一个示例

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)
Run Code Online (Sandbox Code Playgroud)

注意:执行此操作仅适用于14天及以下的邮件,并且您不能一次删除100条以上的邮件,这意味着输入此邮件!clear 120会引发错误.然而,这并非不可能.while如果你真的想要,你可以在那里添加一个循环,但这可能会产生意想不到的结果.

现在,如果你有消息年长超过14天?你不能使用Client.delete_messages(list_of_messages).相反,您可以使用Client.delete_message(Message)它一次只删除一条消息.是的,我知道很慢但是现在,这就是我们所拥有的一切.因此,您可以修改原始代码,以便在每次循环时删除它logs_from().

像这样的东西:

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)
Run Code Online (Sandbox Code Playgroud)