You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python实现Discord批量删除聊天记录的机器人

实现批量删除聊天记录的Discord机器人

核心修改思路

你当前的代码仅删除了触发命令的消息,要实现批量删除指定数量的近期/历史消息,需要利用Discord.py的TextChannel.purge()方法,同时解析命令中的数量参数。

修改后的完整代码

import discord

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):  
        channel = message.channel.name
        restricted_channels = ["command-bot"]  
        prefix = "-"

        if message.content.startswith(prefix):
            if channel in restricted_channels:  
                # 拆分命令与参数
                command_parts = message.content[len(prefix):].split()
                if not command_parts:
                    return
                
                command = command_parts[0]
                if command == "clear":
                    # 先删除触发命令的消息
                    await message.delete()

                    # 处理数量参数
                    if len(command_parts) < 2:
                        await message.channel.send("请指定要删除的消息数量,格式:`-clear 10`")
                        return
                    
                    try:
                        delete_count = int(command_parts[1])
                        # Discord API限制单次最多删除100条消息
                        if delete_count <= 0 or delete_count > 100:
                            await message.channel.send("数量必须在1-100之间")
                            return
                    except ValueError:
                        await message.channel.send("请输入有效的数字")
                        return

                    # 批量删除消息(自动跳过超过14天的历史消息)
                    deleted = await message.channel.purge(limit=delete_count)
                    # 3秒后自动删除成功提示
                    await message.channel.send(f"已删除{len(deleted)}条消息", delete_after=3)

# 替换为你的机器人Token
client = MyClient(intents=discord.Intents.default())
client.run("YOUR_BOT_TOKEN")

关键细节说明

  • 参数解析:通过split()拆分命令内容,提取用户指定的删除数量
  • 批量删除逻辑:purge(limit=delete_count)会一次性删除指定数量的最新消息,Discord API限制无法删除超过14天的历史消息
  • 错误处理:覆盖了无参数、非数字参数、数量超出范围的场景,给出明确提示
  • 权限要求:机器人必须拥有服务器的「管理消息」权限,否则无法执行删除操作
  • 冗余清理:删除成功的提示会自动在3秒后消失,避免残留无效消息

内容的提问来源于stack exchange,提问作者le nam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:40:34