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

如何使用discord.py机器人命令删除特定成员的消息?

实现Discord机器人删除指定成员所有消息的命令

你提供的示例代码无法运行,核心原因是discord.Member对象没有message.delete_all()这个方法。下面给出可正常运行的实现方案,同时兼顾权限控制和API限制:

必要前提

  • 机器人账号需要拥有管理消息权限
  • 执行命令的用户也需要对应权限(可通过代码限制)
  • Discord API限制:仅能批量删除14天以内的消息,超过14天的消息只能逐条删除

基础实现代码(逐条删除)

import discord
from discord.ext import commands

# 初始化机器人,必须开启消息内容意图
intents = discord.Intents.all()
intents.message_content = True  # Discord开发者后台也需开启该意图
bot = commands.Bot(command_prefix="Mia ", case_insensitive=True, intents=intents)

@bot.command(name="clean")
@commands.has_permissions(manage_messages=True)  # 限制仅有权限的用户可调用
async def clear_member_messages(ctx, member: discord.Member):
    deleted_count = 0
    # 遍历当前频道所有消息
    async for message in ctx.channel.history(limit=None):
        if message.author == member:
            try:
                await message.delete()
                deleted_count += 1
            except discord.errors.Forbidden:
                await ctx.send(f"无法删除{member.mention}的某条消息,权限不足。")
            except discord.errors.HTTPException:
                await ctx.send(f"删除{member.mention}的消息时出现异常。")
    await ctx.send(f"已清理{member.mention}的{deleted_count}条消息。")

@bot.event
async def on_ready():
    print(f"机器人已登录:{bot.user.name}")

bot.run("你的机器人Token")

优化版(批量+逐条结合,提升效率)

针对14天内的消息使用批量删除减少API调用,14天以上的消息逐条处理:

import discord
from discord.ext import commands
from datetime import timedelta

intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix="Mia ", case_insensitive=True, intents=intents)

@bot.command(name="clean")
@commands.has_permissions(manage_messages=True)
async def clear_member_messages(ctx, member: discord.Member):
    deleted_count = 0
    fourteen_days_ago = discord.utils.utcnow() - timedelta(days=14)

    # 批量删除14天内的消息,每次最多处理100条
    to_delete = []
    async for message in ctx.channel.history(limit=None, after=fourteen_days_ago):
        if message.author == member:
            to_delete.append(message)
    
    if to_delete:
        # 拆分消息列表为100条一组的 chunk
        for chunk in [to_delete[i:i+100] for i in range(0, len(to_delete), 100)]:
            await ctx.channel.delete_messages(chunk)
            deleted_count += len(chunk)
    
    # 逐条删除14天以上的消息
    async for message in ctx.channel.history(limit=None, before=fourteen_days_ago):
        if message.author == member:
            try:
                await message.delete()
                deleted_count += 1
            except Exception as e:
                await ctx.send(f"无法删除旧消息:{str(e)}")
    
    await ctx.send(f"已清理{member.mention}的{deleted_count}条消息。")

@bot.event
async def on_ready():
    print(f"机器人已登录:{bot.user.name}")

bot.run("你的机器人Token")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:35:44