From 9eda65886e534ff8c84baa4743900ac49d87fb31 Mon Sep 17 00:00:00 2001 From: Rafael Vargas Date: Fri, 24 Dec 2021 13:10:18 -0400 Subject: [PATCH] Adding class ErrorHandler to log errors --- extensions/general/Control.py | 34 ++++++++++++++ extensions/general/ErrorHandler.py | 74 ++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100644 extensions/general/Control.py create mode 100644 extensions/general/ErrorHandler.py diff --git a/extensions/general/Control.py b/extensions/general/Control.py new file mode 100644 index 0000000..c612c4b --- /dev/null +++ b/extensions/general/Control.py @@ -0,0 +1,34 @@ +from discord.ext.commands.errors import CommandNotFound, MissingRequiredArgument +from discord.ext import commands + + +class Control(commands.Cog): + """Control the flow of the Bot""" + + def __init__(self, bot): + self.__bot = bot + + @property + def bot(self): + return self.__bot + + @bot.setter + def bot(self, newBot): + self.__bot = newBot + + @commands.Cog.listener() + async def on_ready(self): + print(f'Bot {self.__bot.user.name} inicializado') + + @commands.Cog.listener() + async def on_command_error(self, ctx, error): + if isinstance(error, MissingRequiredArgument): + await ctx.channel.send(f'Falta argumentos. Digite {self.__bot.prefix}help para ver os comandos') + elif isinstance(error, CommandNotFound): + await ctx.channel.send(f'O comando não existe') + else: + raise error + + +def setup(bot): + bot.add_cog(Control(bot)) diff --git a/extensions/general/ErrorHandler.py b/extensions/general/ErrorHandler.py new file mode 100644 index 0000000..d22704c --- /dev/null +++ b/extensions/general/ErrorHandler.py @@ -0,0 +1,74 @@ +import sys +import datetime +import traceback + +MAXIMUM_TRIES = 10 + + +class ErrorHandler(): + """Receive errors to write into a log file + + Arg: + folder_path = Relative path from root to where the logs should be create + """ + + def __init__(self, folder_path='') -> None: + self.__folder_path = folder_path + + def write(self, error) -> bool: + """Write the error to a log file""" + if not isinstance(error, Exception): + return False + + full_path = self.__open_file() + if isinstance(full_path, bool): + print('Parei') + return False + + error_str = self.__prepare_error(error) + + try: + with open(file=full_path, mode='w+') as log_file: + log_file.write(error_str) + return True + except Exception as e: + print(e) + return False + + def __prepare_error(self, error: Exception) -> str: + """Receive the error and return a good str""" + time_now = datetime.datetime.now() + tipo = sys.exc_info()[0] + msg = sys.exc_info()[1] + tb = traceback.format_tb(sys.exc_info()[2]) + error_str = f'Error Time: {time_now}\nTipo: {tipo}\nMsg: {msg}\nTraceback: {tb}' + return error_str + + def __open_file(self) -> str: + """Open a file to write the error""" + successfull = False + tries = 0 + + while True: + now = datetime.datetime.now() + date_now = now.strftime(r'%d.%b.%Y-%Hh%Mm%Ss') + + full_path = f'{self.__folder_path}/{date_now}({tries}).txt' + + try: + log_file = open(file=full_path, mode='w+') + log_file.close() + except Exception as e: + print(e) + tries += 1 + if tries > MAXIMUM_TRIES: + successfull = False + break + else: + successfull = True + break + + if successfull: + return full_path + else: + return False