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

Discord机器人执行purge命令时出现「应用未响应」问题

解决Discord机器人Purge命令「应用未响应」问题

问题现象

执行purge斜杠命令后,机器人能正常删除指定数量的消息,但Discord客户端会弹出「The application did not respond」提示,服务器控制台抛出NotFound: 404 Not Found (error code: 10062): Unknown interaction错误,其他斜杠命令无此异常。

报错原因

Discord的交互命令有3秒超时限制:必须在用户触发命令后的3秒内调用interaction.response相关方法完成响应。当前代码中,先执行interaction.channel.purge(消息数量较多时此操作耗时可能超过3秒),还额外添加了2秒延迟,导致交互会话超时失效,后续调用interaction.response.send_message时就会触发「Unknown interaction」错误。

解决方案

  1. 先调用interaction.response.defer()告诉Discord需要更多处理时间,延长交互会话有效期;
  2. 完成消息清理后,使用interaction.followup.send()发送最终结果,而非继续使用interaction.response。

修改后的代码

@tree.command(
    name="purge",
    description="Deletes a specified number of messages from the channel."
)
async def purge(interaction, limit: int):
    # 先发送延迟响应,避免超时
    await interaction.response.defer(ephemeral=True)
    try:
        if interaction.user.guild_permissions.manage_messages:
            await interaction.channel.purge(limit=limit + 1)
            await interaction.followup.send(f"{limit} messages deleted!", ephemeral=True)
        else:
            await interaction.followup.send("你没有使用该命令的权限。", ephemeral=True)
    except discord.errors.Forbidden:
        await interaction.followup.send("我没有执行此操作的权限。", ephemeral=True)
    except Exception as e:
        await interaction.followup.send(f"发生意外错误:{str(e)}", ephemeral=True)

代码说明

  • interaction.response.defer(ephemeral=True):立即向Discord发送临时响应,标记命令正在处理,且该响应仅触发命令的用户可见;
  • interaction.followup.send():处理完成后发送最终结果,是延迟响应后的标准反馈方式;
  • 移除了不必要的await sleep(2),避免额外浪费时间;
  • 调整异常处理逻辑,所有反馈都使用followup.send,确保在交互会话有效期内完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:22:38