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

在Discord Cog中创建clean斜杠命令时遇应用无响应问题求助

问题原因及修复方案

你的/clean命令出现"应用无响应"的问题,核心是响应时机错误和Interaction对象调用方式不当,同时还混用了前缀命令的权限装饰器,具体修复如下:

错误点分析

  1. 响应时机太晚:ctx.channel.purge是耗时操作,你先执行它才延迟响应,Discord会因超过3秒未收到响应判定应用无响应
  2. 错误调用Interaction方法:你直接用discord.Interaction.response.defer,应该通过命令参数里的ctx(实际是Interaction实例)来调用响应方法
  3. 权限装饰器混用:@commands.has_permissions是前缀命令的装饰器,slash command需用app_commands.checks.has_permissions

修正后的Message Cog代码

from discord import app_commands
from discord.ext import commands

class Message(commands.Cog):  # 若你自定义了InitCog可保留,否则替换为commands.Cog
    # 清理消息
    @app_commands.command(name='clean', description='清理频道消息')
    @app_commands.describe(num='要清理的消息数量')
    @app_commands.checks.has_permissions(manage_channels=True)
    async def clean(self, ctx: app_commands.Context, num: int):
        # 先发送延迟响应,告知Discord正在处理
        await ctx.response.defer(ephemeral=True)
        # 执行消息清理
        deleted_messages = await ctx.channel.purge(limit=num)
        # 发送清理结果的后续消息
        await ctx.followup.send(f'已删除 {len(deleted_messages)} 条消息')

async def setup(client):
    await client.add_cog(Message(client))

额外优化建议

  • 用len(deleted_messages)替代直接用num更准确,因为实际可删除的消息数量可能受权限、消息时效(超过14天的消息无法批量删除)等限制
  • 可添加异常处理,覆盖权限不足、参数非法等场景:
    try:
        deleted_messages = await ctx.channel.purge(limit=num)
        await ctx.followup.send(f'已删除 {len(deleted_messages)} 条消息')
    except discord.Forbidden:
        await ctx.followup.send('我没有清理消息的权限!')
    except ValueError:
        await ctx.followup.send('请输入有效的消息数量!')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:30:53