每当我的机器人试图在 DM 关闭的情况下向成员发送 DM 时,都会尝试发送调试消息,discord.py(第一篇文章)

问题描述 投票:0回答:1

每当我的 bot dm 命令时,我都会尝试发送一个描述错误的嵌入,但它只是直接出现错误,而不发送嵌入。

这是我的错误事件代码:

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandInvokeError(Forbidden)):
        emb = Embed(title="Error : Forbidden",
                    description="Couldn't use the command, probably because you tried to DM someone with their DM's off",
                    color=0xFF0000)
        emb.add_image("https://media1.tenor.com/m/5lbcs68aI2MAAAAC/anime-sad.gif")
        await ctx.send(embed=emb)

对于我的 dm 命令:

@client.tree.command(name="dm", description="DM's someone!", guild=GUILD_ID)
async def dm(interaction: discord.Interaction, user: discord.Member, message: str):
    em = Embed(title=f"Here's a message from {interaction.user.display_name}!",
               description=message,
               color=0x00FF00)
    em.set_footer(text='Answer them by using /dm !')
    await user.send(embed=em)
    await interaction.response.send_message("DM sent!")

我正在使用discord.py最新更新和python 3.10.8

python error-handling discord.py
1个回答
0
投票

您的应用程序(斜杠)命令需要错误处理程序吗? 这些在 CommandTree 上处理。您可以使用装饰器设置一个或将其子类化(推荐)。

文档

如何

from discord import app_commands, Interaction

bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a CommandTree you define.
tree = bot.tree
# can't find your tree? -> ?tag definetree

# this will function as a global error handler for app commands
@tree.error
# this is NOT an event, it only works because of that ^ decorator 
async def tree_on_error(
    interaction: Interaction,
    error: app_commands.AppCommandError
):
    error = getattr(error, 'original', error)
    if isinstance(error, discord.Forbidden):
        emb = Embed(
            title="Error : Forbidden",
            description="Couldn't use the command, probably because you tried to DM someone with their DM's off",
            color=0xFF0000
        )
        emb.add_image("https://media1.tenor.com/m/5lbcs68aI2MAAAAC/anime-sad.gif")
        await ctx.send(embed=emb)
© www.soinside.com 2019 - 2024. All rights reserved.