Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(Discord PY) How do I handle slash command errors from different cog files?

You would typically handle the error of each slash command in the same file that its in, is there a way to essentially have all slash commands in one file and all of the error handling for each slash command in a different file?

This is what it typically looks like ->

class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def echo(self, ctx, arg):
        await ctx.send(arg)

    @echo.error
    async def echo_error(self, ctx, error):
        await ctx.send("There was an error")
        if isinstance(error, command.MissingRequiredArgument):
            await ctx.send("MIssing Required Argument")
        else:
            raise error

I haven’t tried anything yet because I’m fairly new to python, so I was just curious if this was even possible. Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Before your bot.run(), add these lines of code:

import asyncio  #usually the imports are at the top of the file
from cog_file import ErrorCog
from slash_commands_file import SlashCog
asyncio.run(bot.add_cog(ErrorCog(bot)))
asyncio.run(bot.add_cog(SlashCog(bot)))

where cog_file.py and slash_commands_file.py are in the same folder as the one running the bot.

The cog_file.py is the same you have. For the slash_commands_file, you would have something like this:

from discord.ext import commands
from discord import app_commands

class SlashCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    @app_commands.command(name='command-name') #here just as with normal @tree.command
    async def my_slash_command(self, interaction: discord.Interaction):
        pass   #in here same as always except bot is replaced with self.bot

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading