12944qwerty

Errorhandling cog

Feb 18th, 2022 (edited)
931
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.96 KB | None | 0 0
  1. from discord.ext import commands
  2. import discord
  3. import asyncio
  4.  
  5. class CommandErrorHandler(commands.Cog):
  6.     def __init__(self, bot):
  7.         self.bot = bot
  8.  
  9.     @commands.Cog.listener()
  10.     async def on_command_error(self, ctx, error):
  11.         """The event triggered when an error is raised while invoking a command.
  12.        ctx   : Context
  13.        error : Exception"""
  14.  
  15.         error = getattr(error, 'original', error)
  16.  
  17.         # if isinstance(error, ignored):
  18.             # return
  19.        
  20.         msg = None
  21.         if isinstance(error, commands.CommandNotFound):
  22.             msg = await self.em(ctx, title="Command Not Found", description=str(error), bot=self.bot)
  23.  
  24.         elif isinstance(error, commands.DisabledCommand):
  25.             msg = await self.em(ctx, title="Disabled Command", description=str(error), bot=self.bot)
  26.  
  27.         elif isinstance(error, commands.NoPrivateMessage):
  28.             try:
  29.                 em = discord.Embed(title="No Private Message", description=str(error))
  30.                 em.set_author(name=self.bot.user.display_name, icon_url=self.bot.user.avatar_url)
  31.  
  32.                 msg = await ctx.author.send(embed=em)
  33.             except Exception:
  34.                 pass
  35.  
  36.         elif isinstance(error, commands.BadArgument):
  37.             msg = await self.em(ctx, title='Bad Argument', description=str(error), bot=self.bot)
  38.  
  39.         elif isinstance(error, commands.BotMissingPermissions):
  40.             return await ctx.send('I am missing these permissions to do this command:'
  41.                                   f'\n{self.lts(error.missing_perms)}')
  42.  
  43.         elif isinstance(error, commands.MissingPermissions):
  44.             return await ctx.send('You are missing these permissions to do this command:'
  45.                                   f'\n{self.lts(error.missing_perms)}')
  46.  
  47.         elif isinstance(error, (commands.BotMissingAnyRole, commands.BotMissingRole)):
  48.             return await ctx.send(f'I am missing these roles to do this command:'
  49.                                   f'\n{self.lts(error.missing_roles or [error.missing_role])}')
  50.  
  51.         elif isinstance(error, (commands.MissingRole, commands.MissingAnyRole)):
  52.             return await ctx.send(f'You are missing these roles to do this command:'
  53.                                   f'\n{self.lts(error.missing_roles or [error.missing_role])}')
  54.  
  55.         elif isinstance(error, commands.CommandInvokeError):
  56.             return await self.em(ctx, title="Command Invoke Error", description=str(error), bot=self.bot)
  57.  
  58.         elif isinstance(error, commands.CommandOnCooldown):
  59.             after = error.retry_after
  60.             sec = divmod(after, 60)[1]
  61.             min_ = divmod(divmod(after, 60)[0], 60)[1]
  62.             hours = divmod(divmod(after, 60)[0], 60)[0]
  63.             msg = await self.em(ctx, title="Error", description=f'Please wait another `{hours}` hours and `{min_}` minutes and `{sec}` secs', bot=self.bot)
  64.        
  65.         else:
  66.             await self.em(ctx, title=str(error.__class__.__name__), description=str(error), bot=self.bot)
  67.  
  68.         if type(msg) == discord.Message:
  69.             await asyncio.sleep(5.0)
  70.             await msg.delete()
  71.  
  72.     @staticmethod
  73.     def lts(list_: list):
  74.         """List to string.
  75.           For use in `self.on_command_error`"""
  76.         return ', '.join([obj.name if isinstance(obj, discord.Role) else str(obj).replace('_', ' ') for obj in list_])
  77.    
  78.     @staticmethod
  79.     async def em(self, ctx, *, title, description=None, bot=None, **kwargs):
  80.         """Quick embed sending."""
  81.         kwargs.pop('title', None)
  82.         kwargs.pop('description', None)
  83.         color = kwargs.pop('color', None)
  84.         em = discord.Embed(title=title, description=description, color=color if color else discord.Color.blue())
  85.         if bot is not None:
  86.             em.set_author(name=bot.user.display_name, icon_url=bot.user.avatar_url)
  87.         return await ctx.send(embed=em, **kwargs)
  88.  
  89. def setup(bot):
  90.     bot.add_cog(CommandErrorHandler(bot))
  91.  
Add Comment
Please, Sign In to add comment