diff --git a/db_access.py b/db_access.py index 696b2bd..4423564 100644 --- a/db_access.py +++ b/db_access.py @@ -1,3 +1,4 @@ +import asyncio import json import logging import os @@ -229,19 +230,28 @@ class DBAccess: else: self.log.addHandler(logging.StreamHandler()) - try: - self.connection = mysql.connect( - host='localhost', - user=DB_USERNAME, - password=DB_PASSWORD, - database='hfc_db' - ) - except mysql.Error as e: - self.connection.reconnect(attempts=12, delay=5) + self.connection = None + for i in range(12): + try: + self.connection = mysql.connect( + host='localhost', + user=DB_USERNAME, + password=DB_PASSWORD, + database='hfc_db' + ) + except mysql.Error as e: + self.log.error(f'Failed to connect to database. This is attempt {i+1}') + self.connection = mysql.connect( + host='localhost', + user=DB_USERNAME, + password=DB_PASSWORD, + database='hfc_db' + ) def __del__(self): - self.connection.close() + if self.connection is not None: + self.connection.close() def add_area(self, area_id: int, area_name: str): with self.get_cursor() as crsr: diff --git a/main.py b/main.py index 48099bf..adf6ce5 100644 --- a/main.py +++ b/main.py @@ -1,3 +1,9 @@ +import datetime +import sys +import traceback +import types +from types import TracebackType + import discord from discord.ext import commands, tasks from dotenv import load_dotenv @@ -32,8 +38,38 @@ async def on_message(msg: discord.Message): @bot.event async def on_ready(): - await Notificator.setup(bot, handler) await bot.change_presence(activity=discord.Activity(name='for HFC alerts.', type=discord.ActivityType.watching)) + botdata_path = os.path.join(os.path.realpath(__file__), '..', 'botdata') + if not os.path.isdir(botdata_path): + os.mkdir(botdata_path) + + botdata_backup_path = os.path.join(botdata_path, 'backups') + if not os.path.isdir(botdata_backup_path): + os.mkdir(botdata_backup_path) + + await Notificator.setup(bot, handler) + + +@bot.event +async def on_error(event, *args, **kwargs): + e: tuple[type, Exception, types.TracebackType] = sys.exc_info() + time = datetime.datetime.now() + path = os.path.join(os.path.realpath(__file__), '..', 'botdata', 'backups', f'ERRLOG_{time.strftime("%Y-%m-%d_%H-%M-%S")}.txt') + tb_str = '\n'.join(traceback.format_tb(e[2])) + + data = f""" +An error has occurred! Don't worry, I saved an automatic log for ya :) +---------------------------------------------------------------------- +Rough DateTime: {time.strftime("%Y-%m-%d %H:%M:%S")} +Error: {e[0].__name__}: {e[1]} + +Traceback: +---------- +{tb_str} +""" + + with open(path, 'w') as f: + f.write(data) bot.run(token=TOKEN, log_handler=handler)