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

如何修复discord.py中的Purge斜杠命令?Unknown interaction错误

解决Discord斜杠命令Unknown Interaction错误

错误原因分析

出现404 Not Found (error code: 10062): Unknown interaction的核心原因有三个:

  • 混用了前缀命令的装饰器(@bot.command)定义斜杠命令,导致Discord无法正确识别交互请求
  • 未处理交互响应超时:如果purge操作耗时超过3秒,Discord会自动关闭交互会话,后续响应触发错误
  • 权限检查装饰器不匹配:前缀命令的权限检查不适用于斜杠命令

修正后的代码

from discord import app_commands
import discord
from discord.ext import commands

# 初始化Bot实例(确保开启必要的Intents,比如message_content)
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())

@app_commands.command(name="purge", description="Purge a specific amount of messages.")
@app_commands.guilds(guild_ID)  # 注意参数是复数guilds,传入服务器ID列表
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(interaction: discord.Interaction, num_messages: int):
    # 验证输入有效性
    if num_messages < 1:
        await interaction.response.send_message("你必须提供一个大于0的有效消息数量。", ephemeral=True)
        return
    
    # *关键步骤*:延迟响应,避免超时导致交互失效
    await interaction.response.defer(ephemeral=True)
    
    # 执行消息清理,先确认当前是文本频道
    if isinstance(interaction.channel, discord.TextChannel):
        deleted = await interaction.channel.purge(limit=num_messages)
        embed = discord.Embed(description=f"✅ 已删除 {len(deleted)} 条消息。")
        # 发送延迟后的最终响应
        await interaction.followup.send(embed=embed, ephemeral=True)
    else:
        await interaction.followup.send("无法在当前频道执行消息清理操作。", ephemeral=True)

# 同步斜杠命令到目标服务器(必须执行)
@bot.event
async def on_ready():
    await bot.tree.sync(guild=discord.Object(id=guild_ID))
    print(f"已登录为 {bot.user}")

关键修改点说明

  • 替换装饰器:用@app_commands.command替代@bot.command,这是discord.py定义斜杠命令的标准方式;权限检查改用@app_commands.checks.has_permissions
  • 处理超时问题:通过interaction.response.defer()告知Discord需要更多处理时间,避免3秒超时导致交互被标记为未知
  • 命令同步:在on_ready事件中执行bot.tree.sync(),确保斜杠命令被注册到目标服务器,否则命令不会显示在Discord中
  • 类型安全校验:增加频道类型检查,避免在非文本频道执行purge引发额外错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:37:37