diff --git a/config.ini b/config.ini index 33eac8a..d3dc2d0 100644 --- a/config.ini +++ b/config.ini @@ -1,9 +1,12 @@ [telegram] # They can be found here: https://my.telegram.org +# Read the wiki for further informations on how to get those values, if you haven't api_id = api_hash = [var] +# Log types: debug, info, warn, error +log_level = info backup_dir = backup [language] @@ -14,4 +17,4 @@ enabled = False message_limit = 3 [plugins] -OpenWeatherMapKey = XXXXXXXXX \ No newline at end of file +OpenWeatherMapKey = XXXXXXXXX diff --git a/main.py b/main.py index 5f8129d..50ce5af 100644 --- a/main.py +++ b/main.py @@ -8,13 +8,6 @@ from translations import translations from telethon import TelegramClient, events -logging.basicConfig( - level=logging.WARN, - format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", - filename="userbot.log", - filemode="a" -) - def load_commands(client): commands_folder = os.path.join(os.path.dirname(__file__), 'commands') for filename in os.listdir(commands_folder): @@ -24,29 +17,48 @@ def load_commands(client): if hasattr(module, 'register'): module.register(client) +def get_log_level(level_str: str): + levels = { + 'info': logging.INFO, + 'warn': logging.WARN, + 'warning': logging.WARN, + 'debug': logging.DEBUG, + 'error': logging.ERROR, + } + return levels.get(level_str.lower(), logging.INFO) + async def main(): - # Read credentials from config.ini file + # Read data from config.ini file config = configparser.ConfigParser() config.read('config.ini') api_id = config['telegram']['api_id'] api_hash = config['telegram']['api_hash'] backup_folder = config['var']['backup_dir'] + log_channel = config['var']['log_level'] + + # Configure logging here (after reading config) + logging.basicConfig( + level=get_log_level(log_channel), + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + filename="userbot.log", + filemode="a" + ) client = TelegramClient('session_name', api_id, api_hash) try: await client.start() load_commands(client) - print(translations['userbot_started']) + logging.info(translations['userbot_started']) await client.run_until_disconnected() except asyncio.CancelledError: - print(translations['userbot_disconnected_cancelled_error']) + logging.warning(translations['userbot_disconnected_cancelled_error']) except Exception as e: - traceback.print_exc() - print(translations['error_occurred'].format(error=str(e))) + logging.error("Unhandled exception", exc_info=True) + logging.error(translations['error_occurred'].format(error=str(e))) def handle_signal(signum, frame): - print(translations['abort_signal_received']) + logging.info(translations['abort_signal_received']) asyncio.get_event_loop().stop() if __name__ == '__main__':