discord.py中DM命令触发Forbidden错误时无法发送Embed提示求助
问题分析与解决方案
核心问题
你用的是斜杠命令(@client.tree.command),但on_command_error事件只负责处理传统前缀命令(@client.command)的错误,所以当前的错误处理代码根本没触发。另外还有两处API使用错误:
- 错误判断逻辑写错,
isinstance(error, commands.CommandInvokeError(Forbidden))不是正确的写法 - Embed没有
add_image方法,应该用set_image
解决方案1:命令内直接捕获错误(简单直观)
在dm命令里用try-except直接捕获Forbidden错误,实时返回提示:
@client.tree.command(name="dm", description="给用户发私信!", guild=GUILD_ID) async def dm(interaction: discord.Interaction, user: discord.Member, message: str): em = Embed(title=f"来自{interaction.user.display_name}的消息!", description=message, color=0x00FF00) em.set_footer(text='回复请使用 /dm 命令!') try: await user.send(embed=em) await interaction.response.send_message("私信已发送!") except discord.Forbidden: error_emb = Embed(title="错误:权限不足", description="无法发送私信,可能是目标用户关闭了私信功能", color=0xFF0000) error_emb.set_image(url="https://media1.tenor.com/m/5lbcs68aI2MAAAAC/anime-sad.gif") await interaction.response.send_message(embed=error_emb, ephemeral=True) # 仅触发者可见
解决方案2:全局斜杠命令错误处理
如果需要给所有斜杠命令统一处理错误,可以重写CommandTree的错误处理方法:
@client.tree.error async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError): # 捕获命令调用时的嵌套错误,取出原始异常 if isinstance(error, discord.app_commands.CommandInvokeError): original_error = error.original if isinstance(original_error, discord.Forbidden): error_emb = Embed(title="错误:权限不足", description="无法执行命令,可能是目标用户关闭了私信功能", color=0xFF0000) error_emb.set_image(url="https://media1.tenor.com/m/5lbcs68aI2MAAAAC/anime-sad.gif") # 先检查交互是否已响应,避免重复响应报错 if interaction.response.is_done(): await interaction.followup.send(embed=error_emb, ephemeral=True) else: await interaction.response.send_message(embed=error_emb, ephemeral=True) # 其他类型错误可在此添加处理逻辑
注意事项:
- 确保导入
discord.app_commands模块 ephemeral=True可让错误提示仅触发命令的用户看到,避免频道刷屏
内容的提问来源于stack exchange,提问作者Mykado
相关产品推荐
相关产品推荐

