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

Discord机器人cleanup命令报错:Unknown interaction(错误码10062)求助

问题分析与解决方案

错误原因

Discord要求斜杠命令的交互必须在3秒内完成响应。当使用amount选项删除多条消息时,channel.purge()操作耗时超过3秒,导致Discord判定该交互已失效,从而抛出404 Not Found (error code: 10062): Unknown interaction错误。all选项看似正常,大概率是当前频道消息量较少,purge操作能在3秒内完成。

修复方案

在执行耗时的purge操作前,先调用await interaction.response.defer()告知Discord将延迟响应,之后通过await interaction.followup.send()发送最终结果,避免交互超时失效。

修改后的代码

@bot.tree.command(name="cleanup", description="Well... it cleans... what else do you think it does (:)")
@commands.has_permissions(manage_messages=True)
@app_commands.describe(all="Delete all messages in this channel",
                       amount="Delete a specific amount of messages (1 to 100)")
async def cleanup(interaction: discord.Interaction, all: bool = False, amount: int = None):
    try:
        if all:
            # 延迟响应,告知Discord后续发送结果
            await interaction.response.defer()
            await interaction.channel.purge(limit=None)
            # 发送最终清理完成消息
            await interaction.followup.send(f"All messages in this channel have been deleted.")
        elif amount:
            if amount < 1 or amount > 100:
                await interaction.response.send_message(f"Please enter a number between 1 and 100 for the 'amount' option.")
            else:
                # 延迟响应并指定后续消息仅执行者可见
                await interaction.response.defer(ephemeral=True)
                await interaction.channel.purge(limit=amount)
                await interaction.followup.send(f"{amount} messages have been deleted in this channel.", ephemeral=True)
        else:
            await interaction.response.send_message(f"Please provide one of the options: 'all' or 'amount'.")
    except Exception as e:
        print(f"An error occurred: {e}")
        # 针对不同交互状态发送错误提示
        if interaction.response.is_done():
            await interaction.followup.send(f"An error occurred while cleaning up messages: {str(e)}", ephemeral=True)
        else:
            await interaction.response.send_message(f"An error occurred while cleaning up messages: {str(e)}", ephemeral=True)

补充说明

  • defer()的ephemeral=True参数可保持原代码中仅执行者可见消息的行为。
  • 新增的异常分支逻辑,确保操作出错时也能给用户反馈,避免出现无响应状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:08:21