使用discord.py slash commands执行purge时仅删1条消息或报错
问题解决:Discord.py Slash命令Purge时的Unknown Interaction错误
问题原因
删除多条消息时,purge操作耗时超过Discord要求的3秒slash命令响应时限,Discord会判定交互失效,抛出NotFound: 404 Not Found (error code: 10062): Unknown interaction错误。此外你的代码存在缩进错误,会导致命令无法正确注册。
修复步骤
1. 修正命令注册的缩进错误
修改src/commands/__init__.py中的缩进,确保装饰器与函数对齐:
import discord from discord import app_commands from src.commands import responses def await_commands(client): # syncing slash commands @client.event async def on_ready(): try: synced = await client.tree.sync() print(f"Synced {len(synced)} commands(s)") except Exception as e: print(e) @client.tree.command(name='clear', description="Delete messages") @app_commands.describe(amount="Number of messages to delete") async def clear(interaction: discord.Interaction, amount: int): await responses.clear(interaction, 'clear', amount)
2. 修改Purge逻辑,添加延迟响应
修改src/commands/responses.py中的clear函数,先调用defer延长响应时间,再执行purge并发送跟进消息:
async def clear(interaction, command, amount: int): # 延迟响应,告知Discord后续会发送结果 await interaction.response.defer(ephemeral=True) # ephemeral=True让回复仅你可见,可根据需求修改 if amount > 100: await interaction.followup.send("The amount of messages to delete is too much") elif amount > 0: deleted_messages = await interaction.channel.purge(limit=amount) await interaction.followup.send(f"{len(deleted_messages)} messages have been deleted") elif amount < 0: await interaction.followup.send("Can't delete a negative amount of messages") else: await interaction.followup.send("0 Messages have been deleted")
3. 权限检查
确保你的Bot账号在目标频道拥有管理消息权限,否则无法执行消息删除操作。
原理说明
interaction.response.defer():向Discord发送"正在处理"的信号,将响应时限延长至15分钟,避免超时错误。interaction.followup.send():在defer之后,必须用这个方法发送最终结果,不能再使用interaction.response.send_message()。
内容的提问来源于stack exchange,提问作者EMSR
相关产品推荐
相关产品推荐

