From 114e8ceb0d353edaee1d50bbae9a77ba51d43d8a Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:59:00 +0700 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=B8=D1=81=D1=82=D0=B5=D0=BC=D0=B0=20?= =?UTF-8?q?=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D0=BE=D0=B2=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=B1=D0=B8=D1=82=D0=B0=20=D0=BD=D0=B0=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D1=83=D0=BB=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/config.py | 145 --------------------------- BotLibrary/configs/config.py | 5 + BotLibrary/configs/important_path.py | 87 ++++++++++++++++ BotLibrary/configs/list_ids.py | 71 +++++++++++++ BotLibrary/configs/settings.py | 32 ++++++ 5 files changed, 195 insertions(+), 145 deletions(-) delete mode 100644 BotLibrary/config.py create mode 100644 BotLibrary/configs/config.py create mode 100644 BotLibrary/configs/important_path.py create mode 100644 BotLibrary/configs/list_ids.py create mode 100644 BotLibrary/configs/settings.py diff --git a/BotLibrary/config.py b/BotLibrary/config.py deleted file mode 100644 index 5fc510b..0000000 --- a/BotLibrary/config.py +++ /dev/null @@ -1,145 +0,0 @@ -# BotLibrary/configs/config.py -# Список практически всех переменных проекта - -from os import getenv -from dotenv import load_dotenv -from MySQL.list_ids import * - - -# Настройка экспорта модулей и логирования -__all__ = ("LogsSet", "BotEdit", "ListId", "ImportantPath", "BotVariables", - "bot_token", "api_key", "web_api_key", ) -log_type = "Config" - - -# Загружаем переменные из файла .env -load_dotenv() -bot_token = getenv("main_bot_token") -api_key = getenv("APIKey") -web_api_key = getenv("WebAPIKey") -important_id = getenv("important_id") -secret = getenv("secret") - - -# Класс для параметров логгера -class LogsSet: - # Максимальный размер лог-файла - max_size = "500 MB" - - # Шаблон логов для обычного логгера - info_text = ("{timer:YYYY-MM-DD HH:mm:ss} | " - "PRIMO-{extra[log_type]} | " - "{extra[user]} | {message}") - - # Шаблон логов для логгера-ошибок - error_text = ("{timer:YYYY-MM-DD HH:mm:ss} | ERROR-{extra[log_type]} | " - "{extra[user]} | {message}") - - -# Прочие переменные для проекта -class BotVariables: - # Основные настройки бота - encoding = "utf-8" - time_format = "%Y-%m-%d %H:%M:%S" - language = "Python-Aiogram" - time_zone = "Asia/Novosibirsk" - - # Типы сообщений и список директорий для создания - private_msg = "Личные" - group_msg = "Группы" - bot_msg_directories = [private_msg, group_msg,] - - # Названия директорий для хранения аватаров - user_avatar = "UserAvatar" - chat_avatar = "ChatAvatar" - channel_avatar = "ChannelAvatar" - bot_avatar_directories = [user_avatar, chat_avatar, channel_avatar,] - - # Названия директорий-хранилищ - avatar = "Avatar" - photo = "Photo" - video = "Video" - videonote = "VideoNote" - gif = "GIF" - files = "Document" - voice = "Voice" - youtube = "YouTube" - - # Список директорий для создания - bot_media_directories = [ - avatar, photo, video, videonote, gif, files, voice, youtube, - ] - - -# Класс с параметрами бота -class BotEdit: - name = "Первородная Жемчужина" # Описание имени бота - description = ("Привет, мое имя - Эми! Я буду рада, вам помочь " - "посетить другие миры! Вместе!") # Описание бота - short_description = "Привет, это описание! Как дела?" # Описание виджета бота - prefixs = ('$', '!', '.', '%', '&', ':', '|', '+', '-', '/', '~', '?') # Доступные префиксы бота - - -# Создание списков с ids пользователей -class ListId: - # Получение списков из базы данных - ban_list_id = ban_list_ids - - adm_list_id = important_adm_ids - important_users_list_id = important_users_list_ids - groups_list_id = important_groups_ids - channel_list_id = important_channel_ids - - # Создание единого словаря важных ID с использованием оператора | - important_ids = (important_adm_ids | important_users_list_ids | - important_groups_ids | important_channel_ids) - - -# Класс с важными переменными-пути -class ImportantPath: - # Путь к аватарам проекта - bot_avatar = f"BotLibrary/MediaPersonal/bot_avatar.png" - console_app_avatar = f"BotLibrary/MediaPersonal/console_avatar.png" - - # Пути к файлам логирования - log_start = f"BotLogs/bot_start.log" - log_file = f"BotLogs/bot.log" - log_info = f"BotLogs/bot_info.log" - log_error_file = f"BotLogs/bot_error.log" - - # Пути к хранению сообщений - msg = f"BotLogs/BotMessages" - private_message = f"{msg}/{BotVariables.private_msg}" - group_message = f"{msg}/{BotVariables.group_msg}" - - # Путь к хранилищу базы данных - user_info_file = f"MySQL/user_data.json" - - # Пути к хранению медиа - bot_files = f"BotFiles" - bot_personal_media = f"BotLibrary/media" - bot_received_media = f"BotFiles/MediaReceived" - user_avatar = f"{bot_files}/{BotVariables.user_avatar}" - chat_avatar = f"{bot_files}/{BotVariables.chat_avatar}" - channel_avatar = f"{bot_files}/{BotVariables.channel_avatar}" - - - # Названия директорий-хранилищ для медиа - bot_avatar_directory = f"{bot_personal_media}/{BotVariables.avatar}/" - bot_photo_directory = f"{bot_personal_media}/{BotVariables.photo}/" - bot_video_directory = f"{bot_personal_media}/{BotVariables.video}/" - bot_videonote_directory = f"{bot_personal_media}/{BotVariables.videonote}/" - bot_gif_directory = f"{bot_personal_media}/{BotVariables.gif}/" - bot_document_directory = f"{bot_personal_media}/{BotVariables.files}/" - bot_voice_directory = f"{bot_personal_media}/{BotVariables.voice}/" - bot_youtube_directory = f"{bot_personal_media}/{BotVariables.youtube}/" - - # Названия директорий-хранилищ для закачки - avatar_directory = f"{bot_received_media}/{BotVariables.avatar}/" - photo_directory = f"{bot_received_media}/{BotVariables.photo}/" - video_directory = f"{bot_received_media}/{BotVariables.video}/" - videonote_directory = f"{bot_received_media}/{BotVariables.videonote}/" - gif_directory = f"{bot_received_media}/{BotVariables.gif}/" - document_directory = f"{bot_received_media}/{BotVariables.files}/" - voice_directory = f"{bot_received_media}/{BotVariables.voice}/" - youtube_directory = f"{bot_received_media}/{BotVariables.youtube}/" diff --git a/BotLibrary/configs/config.py b/BotLibrary/configs/config.py new file mode 100644 index 0000000..40ab2fa --- /dev/null +++ b/BotLibrary/configs/config.py @@ -0,0 +1,5 @@ +# BotLibrary/configs/config.py +# Базовые переменные для проекта + +# Базовая кодировка файлов +default_encod = "utf-8" diff --git a/BotLibrary/configs/important_path.py b/BotLibrary/configs/important_path.py new file mode 100644 index 0000000..cc1f23d --- /dev/null +++ b/BotLibrary/configs/important_path.py @@ -0,0 +1,87 @@ +# BotLibrary/configs/important_path.py +# Хранилище всех важных путей + + +# Класс для хранения типов директорий +class TypeDirectory: + # Типы сообщений и список директорий для создания + private_msg = "Личные" + group_msg = "Группы" + msg_directories = [private_msg, group_msg] + + # Названия директорий для хранения аватаров + user_avatar = "UserAvatar" + chat_avatar = "ChatAvatar" + channel_avatar = "ChannelAvatar" + avatar_directories = [user_avatar, chat_avatar, channel_avatar] + + # Названия директорий-хранилищ + avatar = "Avatar" + photo = "Photo" + video = "Video" + videonote = "VideoNote" + gif = "GIF" + files = "Document" + voice = "Voice" + youtube = "YouTube" + + # Список директорий для создания + media_directories = [avatar, photo, video, videonote, + gif, files, voice, youtube] + + +# Класс с важными путями и настройками +class ProjectPath: + # Пути к файлам логирования + logs = "BotLogs" + log_start = f"{logs}/start.log" + log_file = f"{logs}/bot.log" + log_info = f"{logs}/info.log" + log_error_file = f"{logs}/error.log" + + + # Пути к хранилищу сообщений + msg = f"{logs}/BotMessages" + private_message = f"{msg}/{TypeDirectory.private_msg}" + group_message = f"{msg}/{TypeDirectory.group_msg}" + + + # Путь к хранилищу базы данных + SQL = "MySQL" + user_info_file = f"{SQL}/user_data.json" + list_id = f"{SQL}/list_ids.json" + + + # Пути к хранилищу медиа + bot_files = "BotFiles" + personal_media = f"BotLibrary/media" + received_media = f"{bot_files}/MediaReceived" + + + # Пути к папкам аватаров + user_avatar = f"{bot_files}/{TypeDirectory.user_avatar}" + chat_avatar = f"{bot_files}/{TypeDirectory.chat_avatar}" + channel_avatar = f"{bot_files}/{TypeDirectory.channel_avatar}" + + + # Путь к папкам хранения медиа + console_app_avatar = f"{personal_media}/console_avatar.png" + personal_avatar = f"{personal_media}/{TypeDirectory.avatar}" + personal_photo = f"{personal_media}/{TypeDirectory.photo}" + personal_video = f"{personal_media}/{TypeDirectory.video}" + personal_videonote = f"{personal_media}/{TypeDirectory.videonote}" + personal_gif = f"{personal_media}/{TypeDirectory.gif}" + personal_document = f"{personal_media}/{TypeDirectory.files}" + personal_voice = f"{personal_media}/{TypeDirectory.voice}" + personal_youtube = f"{personal_media}/{TypeDirectory.youtube}" + + + # Путь к папкам получения медиа + received_avatar = f"{received_media}/{TypeDirectory.avatar}" + received_photo = f"{received_media}/{TypeDirectory.photo}" + received_video = f"{received_media}/{TypeDirectory.video}" + received_videonote = f"{received_media}/{TypeDirectory.videonote}" + received_gif = f"{received_media}/{TypeDirectory.gif}" + received_document = f"{received_media}/{TypeDirectory.files}" + received_voice = f"{received_media}/{TypeDirectory.voice}" + received_youtube = f"{received_media}/{TypeDirectory.youtube}" diff --git a/BotLibrary/configs/list_ids.py b/BotLibrary/configs/list_ids.py new file mode 100644 index 0000000..a7029a0 --- /dev/null +++ b/BotLibrary/configs/list_ids.py @@ -0,0 +1,71 @@ +# BotLibrary/configs/list_ids.py +# Получение id пользователей из базы данных + +import os +import json +from loguru import logger + +from .config import * +from .important_path import ProjectPath + +# Настройка экспорта модулей и логирования +__all__ = ("load_ids_from_json", "save_ids_to_json", "DataID") +default_file = ProjectPath.list_id +log_type = "ListID" + + +# Чтение данных из файла JSON с обработкой ошибок +def load_ids_from_json(file=default_file, encoding=default_encod): + try: + # Проверка существования файла + if not os.path.exists(file): + # Если файл не существует, создаем его с пустым содержимым + with open(file, "w", encoding=encoding) as f: + json.dump({}, f, ensure_ascii=False, indent=4) + + # Чтение данных из файла + with open(file, "r", encoding=encoding) as f: + return json.load(f) + + except FileNotFoundError: + (logger.bind(log_type=log_type, user="Файл id") + .error(f"Файл {file} не найден!")) + return {} + + except json.JSONDecodeError: + (logger.bind(log_type=log_type, user="Декодирование id") + .error(f"Ошибка декодирования JSON в файле {file}")) + return {} + + except Exception as e: + (logger.bind(log_type=log_type, user="Чтение id") + .error(f"Произошла ошибка при чтении файла {file}: {e}")) + return {} + + +# Запись данных в файл JSON с обработкой ошибок +def save_ids_to_json(file=default_file, encoding=default_encod, data=None): + try: + with open(file, "w", encoding=encoding) as f: + json.dump(data, f, ensure_ascii=False, indent=4) + + except Exception as e: + (logger.bind(log_type=log_type, user="Запись id") + .error(f"Произошла ошибка при записи в файл {file}: {e}")) + + +# Класс для хранения данных из JSON +class DataID: + # Получение информации из списка важных айди, забанненых айди и общих + data_list_id = load_ids_from_json(ProjectPath.list_id) + data_user_data = load_ids_from_json(ProjectPath.user_info_file) + + # Список забанненых пользователей + ban_list = data_list_id.get("ban_list_ids", {}) + + # Список важных айди + admins = data_list_id.get("important_adm_ids", {}) + groups = data_list_id.get("important_groups_ids", {}) + users = data_list_id.get("important_users_list_ids", {}) + channels = data_list_id.get("important_channel_ids", {}) + important = {**admins, **groups, **users, **channels} diff --git a/BotLibrary/configs/settings.py b/BotLibrary/configs/settings.py new file mode 100644 index 0000000..6184785 --- /dev/null +++ b/BotLibrary/configs/settings.py @@ -0,0 +1,32 @@ +# BotLibrary/configs/settings.py +# Список практически всех переменных проекта + +from os import getenv +from dotenv import load_dotenv + +# Настройка экспорта модулей +__all__ = ("BotEdit", "BotVariables", "bot_token", "api_key", + "web_api_key", "important_id", "secret") + + +# Класс с параметрами бота +class BotEdit: + name = "Первородная Жемчужина" # Описание имени бота + description = ("Привет, мое имя - Эми! Я буду рада помочь вам " + "посетить другие миры! Вместе!") # Описание бота + short_description = "Привет, это описание! Как дела?" # Описание виджета бота + + +# Важные параметры бота +class BotVariables: + language = "Python3-Aiogram" + prefixs = ('$', '!', '.', '%', '&', ':', '|', '+', '-', '/', '~', '?') + + +# Загружаем переменные из файла .env +load_dotenv(".env") +bot_token = getenv("main_bot_token") +api_key = getenv("APIKey") +web_api_key = getenv("WebAPIKey") +important_id = getenv("important_id") +secret = getenv("secret")