如何让我的 Discord Bot 删除频道中的所有消息?

时间:2021-02-18 23:34:26

标签: python discord discord.py

我试图让我的机器人在用户要求机器人删除所有消息时立即删除所有消息,但我的代码不起作用。

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)

如何修复我的代码,以便我的机器人可以删除所有消息?我相信我最大的问题是 await client.delete_messages(msg),因为 Python 不断说客户端没有 delete_messages 的属性。

2 个答案:

答案 0 :(得分:1)

删除每条消息会限制机器人的速率,产生性能问题,这也会降低机器人的速度。相反,如果机器人只是删除频道并在完全相同的位置克隆它,效率会更高。

这是您的命令中包含的清除

@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")

答案 1 :(得分:0)

因此,您可以通过清除而不是删除消息来执行此操作。这将删除频道中的所有消息并保持频道 ID 不变,这意味着您只需要 manage_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)