discord.py中/purge混合命令遇10062错误:仅数量为1时正常
问题分析与解决办法
问题原因
执行/purge 10时触发Unknown interaction错误,是因为ctx.channel.purge(limit=amount)会把触发命令的斜杠消息也纳入清理范围。这条消息被删除后,后续的ctx.reply()找不到对应的交互对象,导致404错误。而/purge 1时,清理的是更早的1条消息,触发消息未被删除,所以回复正常。
解决方案
有两种可行的修改方式:
方式1:先发送回复再清理消息
ephemeral类型的回复仅命令执行者可见,不会被频道的purge操作清理,先发送回复确保交互有效,再执行消息清理:
@commands.hybrid_command(name = "purge", description = "Purges a specified number of messages") @commands.has_permissions(manage_messages = True) async def purge(self, ctx : commands.Context, amount : int): creator = EmbedCreator() embed = creator.create( title = "Success", description = f"```py\nCleared '{amount}' Messages ```", color = discord.Color.green() ) # 优先发送回复,再清理消息 await ctx.reply(embed = embed, delete_after = 10, ephemeral = True) await ctx.channel.purge(limit = amount)
方式2:清理时排除触发命令的消息
通过check参数过滤掉触发命令的消息,保留交互所需的消息对象:
@commands.hybrid_command(name = "purge", description = "Purges a specified number of messages") @commands.has_permissions(manage_messages = True) async def purge(self, ctx : commands.Context, amount : int): creator = EmbedCreator() embed = creator.create( title = "Success", description = f"```py\nCleared '{amount}' Messages ```", color = discord.Color.green() ) # 定义过滤函数:排除触发命令的消息 def exclude_command_msg(message): return message.id != ctx.message.id await ctx.channel.purge(limit = amount, check=exclude_command_msg) await ctx.reply(embed = embed, delete_after = 10, ephemeral = True)
额外注意
原代码中嵌入消息的描述文本换行存在格式问题,需在代码块内添加\n保证格式正确,避免嵌入消息显示异常。
内容的提问来源于stack exchange,提问作者Grimreaper8793
相关产品推荐
相关产品推荐

