You need to enable JavaScript to run this app. discord.py rewrite 清除指定用户消息的@purgemessage指令失效问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

discord.py rewrite 清除指定用户消息的@purgemessage指令失效问题咨询

discord.py rewrite版本用户定向消息清理指令问题修复

问题场景

开发discord机器人时,计划实现输入> purgemessage 5指令后,自动清除指令发起用户的最近5条历史消息。目前功能运行异常,因在回复场景下测试,前端未显示任何报错信息,已编写的初始代码如下:

# purges author's messages
@commands.command(name='purgemessage', aliases=['pm'])
@commands.cooldown(1, 300)
@commands.has_any_role(OwnerRole, GuildMasterRole, AdminRole, ExclusiveMemberRole)
async def purgemessage(self, ctx, amount:int, *, arg:str=None):
    msg = []
    channel = ctx.message.channel.history(limit=None)
    async for message in channel:
        if message.author == ctx.message.author:
            msg.append(message)
    await ctx.message.channel.delete_messages(msg)
    await asyncio.sleep(.5)
    botMessage = await ctx.send(f'**{amount}** messages were successfully deleted!')
    await asyncio.sleep(.5)
    await botMessage.delete()

初始代码的问题点

  • 逻辑完全未使用传入的amount参数:代码无上限遍历频道全量历史消息,会把频道内该用户发过的所有消息全部收集,既没有实现“只删指定数量消息”的目标,也会因为遍历量过大触发Discord接口限流。
  • 不符合Discord接口调用规则:delete_messages方法仅支持批量删除14天以内、单批最多100条的消息,无上限收集的消息列表很容易超出接口限制,触发无提示的接口异常。
  • 统计范围有偏差:没有将用户触发指令的那条消息纳入处理流程,最终实际删除的消息数会和用户预期不符。
  • 缺少异常兜底:如果收集到的用户消息数不足传入的amount值,空消息列表调用删除方法会直接触发接口报错。

可正常运行的修正代码

import asyncio
from discord.ext import commands

# purges author's messages
@commands.command(name='purgemessage', aliases=['pm'])
@commands.cooldown(1, 300)
@commands.has_any_role(OwnerRole, GuildMasterRole, AdminRole, ExclusiveMemberRole)
async def purgemessage(self, ctx, amount: int, *, arg: str = None):
    # 优先删除用户触发指令的原消息
    await ctx.message.delete()
    collected_msgs = []
    # 带兜底限制遍历历史消息,避免无意义的接口请求
    async for msg in ctx.channel.history(limit=amount + 10):
        if msg.author == ctx.author:
            collected_msgs.append(msg)
            # 收集够指定数量的消息就停止遍历
            if len(collected_msgs) >= amount:
                break
    # 非空列表才执行批量删除,避免触发空值报错
    if collected_msgs:
        await ctx.channel.delete_messages(collected_msgs)
    # 临时提示消息自动删除
    await asyncio.sleep(0.5)
    send_tip = await ctx.send(f'**{amount}** 条属于你的消息已成功删除!')
    await asyncio.sleep(0.5)
    await send_tip.delete()

落地注意事项

  • 机器人需要提前在对应频道开通「管理消息」权限,否则删除操作会静默失败,普通用户端不会收到任何权限不足的提示。
  • 建议给amount参数增加上限校验,最大值设置为100,适配Discord批量删除的接口限制。
  • 当前代码里的arg参数没有实际业务用途,属于冗余参数,可根据需求选择保留或删除。
  • 如果需要清理超过14天的历史消息,需要改用单条消息逐次删除的逻辑,不能直接调用批量删除接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.23 02:15:03