diff options
author | aninternettroll <lucafulger@gmail.com> | 2020-09-27 10:50:50 +0000 |
---|---|---|
committer | aninternettroll <lucafulger@gmail.com> | 2020-09-27 10:50:50 +0000 |
commit | d439a851657beea76516d76b129ad2002bce9e55 (patch) | |
tree | 925946523588ce9d991ea5ba27f95c37ad3426a0 | |
parent | 74cc1bcbab8bf54d4d6be420c87a82e06a707b3a (diff) | |
download | steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar.gz steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar.bz2 steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar.lz steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar.xz steve-bot-d439a851657beea76516d76b129ad2002bce9e55.tar.zst steve-bot-d439a851657beea76516d76b129ad2002bce9e55.zip |
Better Error Handler
-rwxr-xr-x | bot.py | 2 | ||||
-rw-r--r-- | cogs/errorhandler.py | 75 | ||||
-rwxr-xr-x | cogs/player.py | 58 | ||||
-rwxr-xr-x | cogs/utils.py | 10 |
4 files changed, 103 insertions, 42 deletions
@@ -16,7 +16,7 @@ extensions = [ # "cogs.webserver", # "cogs.twitter", "cogs.logs", - "cogs.errorhandler" + "cogs.errorhandler", ] diff --git a/cogs/errorhandler.py b/cogs/errorhandler.py index 8533a61..7b7c0ec 100644 --- a/cogs/errorhandler.py +++ b/cogs/errorhandler.py @@ -1,20 +1,75 @@ +import traceback +import sys from discord.ext import commands class Errorhandler(commands.Cog): - def __init__(self, bot): - self.bot = bot + def __init__(self, bot): + self.bot = bot - @commands.Cog.listener() - async def on_command_error(self, ctx, error): - if isinstance(error, commands.CommandNotFound): - return + @commands.Cog.listener() + async def on_command_error(self, ctx, error): + """The event triggered when an error is raised while invoking a command. + Parameters + ------------ + ctx: commands.Context + The context used for command invocation. + error: commands.CommandError + The Exception raised. + """ - if isinstance(error, commands.CommandOnCooldown): - return await ctx.send(f'{ctx.author.mention}, you have to wait {round(error.retry_after, 2)} seconds before using this again') + # This prevents any commands with local handlers being handled here in on_command_error. + if hasattr(ctx.command, "on_error"): + return - raise error + # This prevents any cogs with an overwritten cog_command_error being handled here. + cog = ctx.cog + if cog: + if cog._get_overridden_method(cog.cog_command_error) is not None: + return + + ignored = (commands.CommandNotFound,) + + # Allows us to check for original exceptions raised and sent to CommandInvokeError. + # If nothing is found. We keep the exception passed to on_command_error. + error = getattr(error, "original", error) + + # Anything in ignored will return and prevent anything happening. + if isinstance(error, ignored): + return + + if isinstance(error, commands.DisabledCommand): + await ctx.send(f"{ctx.command} has been disabled.") + + elif isinstance(error, commands.NoPrivateMessage): + try: + await ctx.author.send( + f"{ctx.command} can not be used in Private Messages." + ) + except discord.HTTPException: + pass + + elif isinstance(error, commands.CommandOnCooldown): + await ctx.send( + f"{ctx.author.mention}, you have to wait {round(error.retry_after, 2)} seconds before using this again" + ) + + # For this error example we check to see where it came from... + elif isinstance(error, commands.BadArgument): + if ( + ctx.command.qualified_name == "tag list" + ): # Check if the command being invoked is 'tag list' + await ctx.send("I could not find that member. Please try again.") + + else: + # All other Errors not returned come here. And we can just print the default TraceBack. + print( + "Ignoring exception in command {}:".format(ctx.command), file=sys.stderr + ) + traceback.print_exception( + type(error), error, error.__traceback__, file=sys.stderr + ) def setup(bot): - bot.add_cog(Errorhandler(bot)) + bot.add_cog(Errorhandler(bot)) diff --git a/cogs/player.py b/cogs/player.py index f21992d..ae328a5 100755 --- a/cogs/player.py +++ b/cogs/player.py @@ -74,8 +74,8 @@ class YTDLSource(discord.PCMVolumeTransformer): def __getitem__(self, item: str): """Allows us to access attributes similar to a dict. - This is only useful when you are NOT downloading. - """ + This is only useful when you are NOT downloading. + """ return self.__getattribute__(item) @classmethod @@ -112,7 +112,7 @@ class YTDLSource(discord.PCMVolumeTransformer): async def regather_stream(cls, data, *, loop): """Used for preparing a stream, instead of downloading. - Since Youtube Streaming links expire.""" + Since Youtube Streaming links expire.""" loop = loop or asyncio.get_event_loop() requester = data["requester"] @@ -129,11 +129,11 @@ class YTDLSource(discord.PCMVolumeTransformer): class MusicPlayer: """A class which is assigned to each guild using the bot for Music. - This class implements a queue and loop, which allows for different guilds to listen to different playlists - simultaneously. + This class implements a queue and loop, which allows for different guilds to listen to different playlists + simultaneously. - When the bot disconnects from the Voice it's instance will be destroyed. - """ + When the bot disconnects from the Voice it's instance will be destroyed. + """ __slots__ = ( "bot", @@ -289,14 +289,14 @@ class Player(commands.Cog): async def connect_(self, ctx, *, channel: discord.VoiceChannel = None): """Connect to voice. - Parameters - ------------ - channel: discord.VoiceChannel [Optional] - The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in - will be made. + Parameters + ------------ + channel: discord.VoiceChannel [Optional] + The channel to connect to. If a channel is not specified, an attempt to join the voice channel you are in + will be made. - This command also handles moving the bot to different channels. - """ + This command also handles moving the bot to different channels. + """ if not channel: try: channel = ctx.author.voice.channel @@ -328,14 +328,14 @@ class Player(commands.Cog): async def play_(self, ctx, *, search: str): """Request a song and add it to the queue. - This command attempts to join a valid voice channel if the bot is not already in one. - Uses YTDL to automatically search and retrieve a song. + This command attempts to join a valid voice channel if the bot is not already in one. + Uses YTDL to automatically search and retrieve a song. - Parameters - ------------ - search: str [Required] - The song to search and retrieve using YTDL. This could be a simple search, an ID or URL. - """ + Parameters + ------------ + search: str [Required] + The song to search and retrieve using YTDL. This could be a simple search, an ID or URL. + """ await ctx.trigger_typing() vc = ctx.voice_client @@ -452,11 +452,11 @@ class Player(commands.Cog): async def change_volume(self, ctx, *, vol: float): """Change the player volume. - Parameters - ------------ - volume: float or int [Required] - The volume to set the player to in percentage. This must be between 1 and 100. - """ + Parameters + ------------ + volume: float or int [Required] + The volume to set the player to in percentage. This must be between 1 and 100. + """ vc = ctx.voice_client if not vc or not vc.is_connected(): @@ -479,9 +479,9 @@ class Player(commands.Cog): async def stop_(self, ctx): """Stop the currently playing song and destroy the player. - !Warning! - This will destroy the player assigned to your guild, also deleting any queued songs and settings. - """ + !Warning! + This will destroy the player assigned to your guild, also deleting any queued songs and settings. + """ vc = ctx.voice_client if not vc or not vc.is_connected(): diff --git a/cogs/utils.py b/cogs/utils.py index 1d3f3a8..569ef05 100755 --- a/cogs/utils.py +++ b/cogs/utils.py @@ -3,12 +3,14 @@ import datetime import functools import json from datetime import timedelta + # forgot to import this and ended up looking mentally unstable # troll literally pointed out atleast 4 things I did wrong in 3 lines of code from random import choice, randint import discord from discord.ext import commands, tasks + # from PIL.Image import core as Image # import image as Image from PIL import Image, ImageFilter @@ -305,11 +307,15 @@ class Utils(commands.Cog): datetime.date(year, 4, 9), ], [ - "Daniel", # Shadowfi + "Daniel", # Shadowfi self.bot.get_user(586664256217415681), datetime.date(year, 11, 14), ], - ["Sawyer", self.bot.get_user(404873210597867541), datetime.date(year, 9, 12)], + [ + "Sawyer", + self.bot.get_user(404873210597867541), + datetime.date(year, 9, 12), + ], [ "Marco", self.bot.get_user(299668599650648065), |