diff --git a/BotCode/routers/commands/user_cmd/help_cmd.py b/BotCode/routers/commands/user_cmd/help_cmd.py index 95bbe9e..a9306b0 100644 --- a/BotCode/routers/commands/user_cmd/help_cmd.py +++ b/BotCode/routers/commands/user_cmd/help_cmd.py @@ -1,7 +1,7 @@ # BotCode/routers/commands/user_cmd/help_cmd.py # Работа с командой /help, для вывода помощи пользователю -from BotLibrary.samples.user_cmd_class import CommandHandler +from BotLibrary import CommandHandler # Создание команды /help с нужными параметрами help_cmd = CommandHandler( diff --git a/BotCode/routers/commands/user_cmd/start_cmd.py b/BotCode/routers/commands/user_cmd/start_cmd.py index fddcf60..0172a52 100644 --- a/BotCode/routers/commands/user_cmd/start_cmd.py +++ b/BotCode/routers/commands/user_cmd/start_cmd.py @@ -1,7 +1,7 @@ # BotCode/routers/commands/user_cmd/start_cmd.py # # Работа с командой /start, для запуска бота -from BotLibrary.samples.user_cmd_class import CommandHandler +from BotLibrary import CommandHandler from BotCode.keyboards import get_start_kb # Создание команды /start с нужными параметрами @@ -13,5 +13,4 @@ start_cmd = CommandHandler( callbackdata="keywords", text_msg="Старт!", keyboard=get_start_kb, - chat_action=True ) diff --git a/BotLibrary/__init__.py b/BotLibrary/__init__.py index e43fcf3..9964e1a 100644 --- a/BotLibrary/__init__.py +++ b/BotLibrary/__init__.py @@ -7,3 +7,4 @@ from .loggers import * from .system import * from .timer import * from .validators import * +from .samples import * diff --git a/BotLibrary/loggers/start_info_out.py b/BotLibrary/loggers/start_info_out.py index c571dad..fe8a74a 100644 --- a/BotLibrary/loggers/start_info_out.py +++ b/BotLibrary/loggers/start_info_out.py @@ -3,7 +3,7 @@ from time import sleep from colorama import Fore -from ProjectsFiles import Permissions +from ProjectsFiles import Permissions, ProjectPath, BotVar from .custom_loggers import Logs from ..system import BotInfo @@ -20,25 +20,26 @@ def bot_info_out() -> str: bot_post_name: str = f"Доп. имя: {BotInfo.last_name}\n" bot_username: str = f"Юзернейм: @{BotInfo.username}\n" bot_id: str = f"ID: {BotInfo.id}\n" - bot_language: str = f"Языковой код: {BotInfo.language_code}\n" bot_can_join_groups: str = f"Может ли вступать в группы: {BotInfo.can_join_groups}\n" bot_can_read_all_group_messages: str = f"Чтение всех сообщений: {BotInfo.can_read_all_group_messages}\n" - bot_is_premium: str = f"Является премиум-ботом: {BotInfo.is_premium}\n" - bot_added_to_attachment_menu: str = f"Добавлен в меню вложений: {BotInfo.added_to_attachment_menu}\n" bot_supports_inline_queries: str = f"Поддерживает инлайн-запросы: {BotInfo.supports_inline_queries}\n" bot_can_connect_to_business: str = f"Подключение к бизнес-аккаунтам: {BotInfo.can_connect_to_business}\n" bot_has_main_web_app: str = f"Основное веб-приложение: {BotInfo.has_main_web_app}\n" # Формируем полный текст с выводом информации о боте - bot_all_info: str = (f"{bot_name} {bot_post_name} {bot_username} {bot_id} {bot_language} " - f"{bot_can_join_groups} {bot_can_read_all_group_messages} {bot_is_premium} " - f"{bot_added_to_attachment_menu} {bot_supports_inline_queries} {bot_can_connect_to_business} " + bot_all_info: str = (f"{bot_name} {bot_post_name} {bot_username} {bot_id} " + f"{bot_can_join_groups} {bot_can_read_all_group_messages} " + f"{bot_supports_inline_queries} {bot_can_connect_to_business} " f"{bot_has_main_web_app}") # Печатаем все данные в консоль с задержкой в 1 секунду sleep(1) if Permissions.start_info_console: print(Fore.CYAN + bot_all_info) + if Permissions.start_info_to_file: + # Преобразуем словарь bot_all_info в строку и записываем в файл + with open(ProjectPath.bot_info_log_file, 'w', encoding=BotVar.encod) as file: + file.write(str(bot_all_info)) return bot_all_info diff --git a/BotLibrary/system/bots.py b/BotLibrary/system/bots.py index 104a2f4..cb113a1 100644 --- a/BotLibrary/system/bots.py +++ b/BotLibrary/system/bots.py @@ -33,51 +33,49 @@ dp["database"] = None # Настройки для бота bot_properties = DefaultBotProperties( - parse_mode=BotVar.parse_mode, # Устанавливаем формат HTML для всех сообщений - disable_notification=BotVar.disable_notification, # Отключаем уведомления при отправке сообщений - protect_content=BotVar.protect_content, # Защищаем содержимое сообщений от копирования - allow_sending_without_reply=BotVar.allow_sending_without_reply, # Разрешаем отправлять сообщения без ответа на другое сообщение - link_preview_is_disabled=BotVar.link_preview_is_disabled, # Отключаем предварительный просмотр ссылок + parse_mode=BotVar.parse_mode, + disable_notification=BotVar.disable_notification, + protect_content=BotVar.protect_content, + allow_sending_without_reply=BotVar.allow_sending_without_reply, + link_preview_is_disabled=BotVar.link_preview_is_disabled, link_preview_prefer_small_media=BotVar.link_preview_prefer_small_media, link_preview_prefer_large_media=BotVar.link_preview_prefer_large_media, link_preview_show_above_text=BotVar.link_preview_show_above_text, - show_caption_above_media=BotVar.show_caption_above_media, # Показываем подпись выше медиа + show_caption_above_media=BotVar.show_caption_above_media, ) # Создание экземпляра бота -bot = Bot(token=bot_token, default=bot_properties) # Объявление бота +bot = Bot(token=bot_token, default=bot_properties) # Фильтры для различных типов сообщений -F_Media = F.photo | F.files | F.video | F.animation | F.voice | F.video_note # Фильтр для медиа -F_All = F.text | F.photo | F.files | F.video | F.animation | F.voice | F.video_note # Фильтр на все +F_Media = F.photo | F.files | F.video | F.animation | F.voice | F.video_note +F_All = F.text | F.photo | F.files | F.video | F.animation | F.voice | F.video_note # Класс для хранения данных о боте class BotInfo: """ Класс для хранения данных о боте и их обновления. """ - # Статические переменные для хранения данных id: int = None first_name: str = None last_name: str = None username: str = None description: str = None short_description: str = None - can_join_groups: bool = None - can_read_all_group_messages: bool = None + can_join_groups: bool = False + can_read_all_group_messages: bool = False language_code: str = BotVar.language prefix: str = BotVar.prefix - is_premium: bool = None - added_to_attachment_menu: bool = None - supports_inline_queries: bool = None - can_connect_to_business: bool = None - has_main_web_app: bool = None + is_premium: bool = False + added_to_attachment_menu: bool = False + supports_inline_queries: bool = False + can_connect_to_business: bool = False + has_main_web_app: bool = False @classmethod def update(cls, bot_info) -> None: """ Обновляет данные о боте. - :param bot_info: Объект с данными о боте, полученные через API Telegram. """ cls.id = bot_info.id @@ -92,23 +90,16 @@ class BotInfo: cls.supports_inline_queries = bot_info.supports_inline_queries cls.can_connect_to_business = bot_info.can_connect_to_business cls.has_main_web_app = bot_info.has_main_web_app - cls.can_join_groups = getattr(bot_info, 'can_join_groups', None) - cls.can_read_all_group_messages = getattr(bot_info, 'can_read_all_group_messages', None) - + cls.can_join_groups = getattr(bot_info, 'can_join_groups', False) + cls.can_read_all_group_messages = getattr(bot_info, 'can_read_all_group_messages', False) async def bot_get_info() -> dict: """ Получает информацию о боте и обновляет данные в классе BotInfo. - :return: Словарь с данными о боте. """ - # Получение информации о боте через API bot_info_data = await bot.get_me() - - # Обновляем данные о боте в BotInfo BotInfo.update(bot_info_data) - - # Возвращаем обновленные данные о боте return { 'bot_info': bot_info_data, 'id': bot_info_data.id, @@ -124,5 +115,6 @@ async def bot_get_info() -> dict: 'supports_inline_queries': bot_info_data.supports_inline_queries, 'can_connect_to_business': bot_info_data.can_connect_to_business, 'has_main_web_app': bot_info_data.has_main_web_app, - 'can_join_groups': getattr(bot_info_data, 'can_join_groups', None), + 'can_join_groups': getattr(bot_info_data, 'can_join_groups', False), + 'can_read_all_group_messages': getattr(bot_info_data, 'can_read_all_group_messages', False), } diff --git a/BotLibrary/system/directory.py b/BotLibrary/system/directory.py index 6518b06..be0910d 100644 --- a/BotLibrary/system/directory.py +++ b/BotLibrary/system/directory.py @@ -29,7 +29,6 @@ async def create_directories(base_directory: str, subdirectories: List[str]) -> # Проверка, существует ли директория, если нет - создаём if not os.path.exists(directory_path): os.makedirs(directory_path) - print(f"Создана директория: {directory_path}") # Функция установки начальных директорий @@ -39,8 +38,6 @@ async def setup_directories() -> None: """ # Создание директорий для медиа файлов await create_directories(ProjectPath.personal_media, TypeDirectory.media_directories) - - # Раскомментируйте следующие строки, если необходимо создать другие директории - # await create_directories(ProjectPath.received_media, TypeDirectory.media_directories) - # await create_directories(ProjectPath.bot_files, TypeDirectory.avatar_directories) + await create_directories(ProjectPath.received_media, TypeDirectory.media_directories) + await create_directories(ProjectPath.received_avatars, TypeDirectory.avatar_directories) # await create_directories(ProjectPath.msg, TypeDirectory.msg_directories) diff --git a/ProjectsFiles/configs/config.py b/ProjectsFiles/configs/config.py index 19c5604..ff20dd1 100644 --- a/ProjectsFiles/configs/config.py +++ b/ProjectsFiles/configs/config.py @@ -16,6 +16,7 @@ class Permissions: msg_logging : bool = False # Логирование сообщений в консоль (В разработке) start_info_console : bool = True # Вывод информации о боте в начале (True/False) + start_info_to_file : bool = True # Вывод информации о боте в файл (True/False) sql_user : bool = True # Разрешение на регистрацию в базе данных (True/False) diff --git a/ProjectsFiles/configs/project_path.py b/ProjectsFiles/configs/project_path.py index a6f6e6f..4cce6b8 100644 --- a/ProjectsFiles/configs/project_path.py +++ b/ProjectsFiles/configs/project_path.py @@ -22,6 +22,12 @@ class TypeDirectory: voice : str = "Voice" media_directories : List[str] = [avatar, photo, video, videonote, gif, files, voice] + # Названия директорий для аватарок + user_avatar : str = "Users" + chat_avatar : str = "Chats" + channel_avatar : str = "Channel" + avatar_directories : List[str] = [user_avatar, chat_avatar, channel_avatar] + # Класс создания директорий проекта class ProjectPath: @@ -29,12 +35,15 @@ class ProjectPath: Класс для хранения путей к проектам и логам. """ BotLogs : str = "BotLogs" + bot_info_log_file: str = f"{BotLogs}/bot_info.log" start_log_file: str = f"{BotLogs}/start.log" debug_log_file: str = f"{BotLogs}/debug.log" info_log_file : str = f"{BotLogs}/info.log" warning_log_file: str = f"{BotLogs}/warning.log" error_log_file: str = f"{BotLogs}/error.log" - logs_path : List[str] = [debug_log_file, info_log_file, warning_log_file, error_log_file] + BotFiles : str = "BotFiles" + received_media : str = f"{BotFiles}/media" + received_avatars : str = f"{BotFiles}/avatars" personal_media : str = "ProjectsFiles/media" diff --git a/main.py b/main.py index 0e485ab..bdad5ac 100644 --- a/main.py +++ b/main.py @@ -12,6 +12,7 @@ async def main(): await setup_logger() await bot_get_info() Logs.start(text=f"Начало запуска бота @{BotInfo.username}...") + bot_info_out() # Создание пустых директорий await setup_directories()