You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何修正Discord机器人删除所有消息的命令?

修正后的批量消息清理与垃圾账号移除命令

原代码的核心问题

  • 频道获取逻辑错误:discord.TextChannel.id(id) 是错误用法,无法通过这种方式获取频道对象
  • 批量删消息API用错:guild.delete_messages() 要求传入消息列表,清空频道消息应该用频道的purge()方法
  • 无效方法调用:ctx.delete_channel()ctx.delete_messages() 都是不存在的方法
  • 参数处理缺失:未将频道ID转为整数类型,也没处理参数为空的情况
  • 提示消息删除逻辑错误:await ctx.delete() 只会删除用户发送的命令消息,无法删除机器人发送的提示消息

修正后的完整代码

import discord
from discord.ext import commands
import asyncio

@bot.command(name="cleanup")
@commands.has_permissions(manage_messages=True, kick_members=True)
async def cleanup(ctx, channel_id: int = None, reason: str = "未提供原因"):
    # 处理频道参数,默认使用当前命令所在频道
    if not channel_id:
        channel = ctx.channel
    else:
        channel = ctx.guild.get_channel(channel_id)
        if not channel:
            await ctx.send("无效的频道ID,未找到对应频道")
            return

    # 批量删除频道所有消息(最多删除14天内的消息)
    try:
        deleted_count = await channel.purge(limit=None, reason=reason)
        # 发送清理完成提示
        msg = await ctx.send(f"{ctx.author.mention} 已清理频道 {channel.mention} 的 {len(deleted_count)} 条消息,原因:{reason}")
        await asyncio.sleep(10)
        await msg.delete()
    except discord.Forbidden:
        await ctx.send("我没有权限清理该频道的消息")
        return
    except discord.HTTPException:
        await ctx.send("清理消息时出现错误")
        return

    # 额外:移除服务器内的垃圾机器人(可根据需求调整判断条件)
    bot_count = 0
    for member in ctx.guild.members:
        if member.bot:
            # 这里可以加判断条件,比如加入时间过短、无角色等
            # 示例:移除所有机器人(谨慎使用!)
            try:
                await member.kick(reason=f"清理垃圾机器人:{reason}")
                bot_count += 1
            except discord.Forbidden:
                continue
    if bot_count > 0:
        bot_msg = await ctx.send(f"已移除 {bot_count} 个机器人账号")
        await asyncio.sleep(5)
        await bot_msg.delete()

    # 删除用户发送的命令消息
    await ctx.message.delete()

代码说明

  • 命令名改为cleanup更直观,支持指定频道ID(默认用当前频道)
  • 加入了权限检查:需要manage_messages(删消息)和kick_members(踢账号)权限
  • 处理了参数缺失和无效频道的情况,添加了错误捕获
  • 使用channel.purge()批量清空消息,自动返回删除的消息数量
  • 新增了垃圾机器人移除逻辑(可根据实际需求调整判断条件,比如只踢新加入的机器人)
  • 正确处理了提示消息的删除,避免残留

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

火山引擎 最新活动