Search code examples
pythonerror-handlingdiscord.py

Trying to send a debug message whenever my bot is trying to DM a member with their dm's turned off, discord.py (first post)


I'm trying to send an embed describing the error whenever my bot dm command, but it just goes straight to the error, without sending the embed.

Here's my code for the error event:

@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)

and for my dm command :

@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!")

I'm using discord.py latest update, and python 3.10.8


Solution

  • Need an error handler for your app (slash) commands? These are handled on the CommandTree. You can set one using the decorator or subclass it.

    Documentation

    How

    from discord import app_commands, Interaction, Forbidden
    
    bot = commands.Bot(...)
    # Bot has a built-in tree
    tree = bot.tree
    
    # this will function as a global error handler for app commands
    @tree.error
    async def tree_on_error(
        interaction: Interaction,
        error: app_commands.AppCommandError
    ):
        error = getattr(error, 'original', error)
        if isinstance(error, 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.set_image(url="https://media1.tenor.com/m/5lbcs68aI2MAAAAC/anime-sad.gif")
            await interaction.response.send_message(embed=emb)