在Discord Cog中创建clean斜杠命令时遇应用无响应问题求助
问题原因及修复方案
你的/clean命令出现"应用无响应"的问题,核心是响应时机错误和Interaction对象调用方式不当,同时还混用了前缀命令的权限装饰器,具体修复如下:
错误点分析
- 响应时机太晚:
ctx.channel.purge是耗时操作,你先执行它才延迟响应,Discord会因超过3秒未收到响应判定应用无响应 - 错误调用Interaction方法:你直接用
discord.Interaction.response.defer,应该通过命令参数里的ctx(实际是Interaction实例)来调用响应方法 - 权限装饰器混用:
@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
相关产品推荐
相关产品推荐

