From 08cb5eaa352b73e0062ce1180be6a2b1ccb188f9 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:57:34 +0700 Subject: [PATCH 01/35] =?UTF-8?q?=D0=A3=D0=BB=D1=83=D1=87=D1=88=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=B8=D0=BD=D0=B8=D1=86=D0=B8=D0=B0=D0=BB?= =?UTF-8?q?=D0=B8=D0=B7=D0=B0=D1=82=D0=BE=D1=80=D0=BE=D0=B2=20=D0=BF=D0=B0?= =?UTF-8?q?=D0=BA=D0=B5=D1=82=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/inline/__init__.py | 2 ++ BotCode/keyboards/inline_kb/__init__.py | 8 ++------ BotCode/keyboards/reply_kb/__init__.py | 4 ++-- BotCode/routers/__init__.py | 1 - BotCode/routers/callback_handlers/__init__.py | 6 +++++- BotCode/routers/downloads/__init__.py | 8 +++++--- BotLibrary/__init__.py | 2 +- BotLibrary/analitics/__init__.py | 2 +- BotLibrary/configs/__init__.py | 8 ++++++++ BotLibrary/library/__init__.py | 6 +++++- MySQL/__init__.py | 1 - 11 files changed, 31 insertions(+), 17 deletions(-) create mode 100644 BotLibrary/configs/__init__.py diff --git a/BotCode/inline/__init__.py b/BotCode/inline/__init__.py index 4f95659..802f5d9 100644 --- a/BotCode/inline/__init__.py +++ b/BotCode/inline/__init__.py @@ -1,2 +1,4 @@ +# BotCode/inline/__init__.py +# Инициализация пакета inline, для инлайн сообщений через @user from .posts_inline import * diff --git a/BotCode/keyboards/inline_kb/__init__.py b/BotCode/keyboards/inline_kb/__init__.py index 1ce98a7..7ae9628 100644 --- a/BotCode/keyboards/inline_kb/__init__.py +++ b/BotCode/keyboards/inline_kb/__init__.py @@ -1,5 +1,5 @@ -# BotCode/keyboards/__init__.py -# Инициализация пакета keyboards, для работы с клавиатурами +# BotCode/keyboards/inline_kb/__init__.py +# Инициализация пакета inline_keyboards, для работы с инлайн клавиатурами from aiogram import Router from .actor_kb import * @@ -8,7 +8,3 @@ from .randnum_kb import * # Объявление роутера и настройка экспорта модулей __all__ = ("router", "actor_kb", "ButtonInl") router = Router(name="inline_kb_router") - - -# Список подключаемых роутеров сверху-вниз -# router.include_routers() diff --git a/BotCode/keyboards/reply_kb/__init__.py b/BotCode/keyboards/reply_kb/__init__.py index 2a26cee..5166890 100644 --- a/BotCode/keyboards/reply_kb/__init__.py +++ b/BotCode/keyboards/reply_kb/__init__.py @@ -1,5 +1,5 @@ -# BotCode/keyboards/__init__.py -# Инициализация пакета keyboards, для работы с клавиатурами +# BotCode/keyboards/reply_kb/__init__.py +# Инициализация пакета reply_kb, для работы с клавиатурами from aiogram import Router from .start_kb import router as start_kb_router diff --git a/BotCode/routers/__init__.py b/BotCode/routers/__init__.py index 6b00bff..45f08da 100644 --- a/BotCode/routers/__init__.py +++ b/BotCode/routers/__init__.py @@ -1,6 +1,5 @@ # BotCode/routers/__init__.py # Инициализация пакета routers, для работы с асинхронными обработчиками -# Пакет старых файлов отключен!! from aiogram import Router from .callback_handlers import router as callback_handlers_router diff --git a/BotCode/routers/callback_handlers/__init__.py b/BotCode/routers/callback_handlers/__init__.py index 9e8ad49..9c5d41d 100644 --- a/BotCode/routers/callback_handlers/__init__.py +++ b/BotCode/routers/callback_handlers/__init__.py @@ -1,11 +1,15 @@ -from aiogram import Router +# BotCode/routers/callback_handlers/__init__.py +# Инициализация пакета callback_handlers, для работы с запросами бота +from aiogram import Router from .actor_kb_cb import router as actor_kb_cb_router from .randnum_kb_cb import router as randnum_kb_cb_router +# Объявление роутера и настройка экспорта модулей __all__ = ("router", ) router = Router(name="callback_handlers") + # Список подключаемых роутеров сверху-вниз router.include_routers( actor_kb_cb_router, diff --git a/BotCode/routers/downloads/__init__.py b/BotCode/routers/downloads/__init__.py index cb9962b..df35270 100644 --- a/BotCode/routers/downloads/__init__.py +++ b/BotCode/routers/downloads/__init__.py @@ -3,15 +3,17 @@ from aiogram import Router from .download_handlers import router as download_media_router -from .download_user_avatar import router as user_avatar_router + +from .download_avatar_all import * +from .download_chat_avatar import * +from .download_user_avatar import * # Объявление роутера и настройка экспорта модулей -__all__ = ("router",) +__all__ = ("router", "download_avatar_all", "download_chat_avatar", "download_user_photos", "download_avatar") router = Router(name="downloads_head_router") # Список подключаемых роутеров сверху-вниз router.include_routers( download_media_router, - user_avatar_router, ) diff --git a/BotLibrary/__init__.py b/BotLibrary/__init__.py index ec6d72c..ad58f35 100644 --- a/BotLibrary/__init__.py +++ b/BotLibrary/__init__.py @@ -5,4 +5,4 @@ from .analitics import * from .library import * from .media import * -from .config import * +from .configs import * diff --git a/BotLibrary/analitics/__init__.py b/BotLibrary/analitics/__init__.py index 89c4d3f..0b9e980 100644 --- a/BotLibrary/analitics/__init__.py +++ b/BotLibrary/analitics/__init__.py @@ -4,6 +4,6 @@ # Импортируем библиотеки для экспорта from .start_info_out import * from .message_to_file import * -from .type_messages import * +from .types_msg import * from .user_data_to_file import * from .find_ids import * diff --git a/BotLibrary/configs/__init__.py b/BotLibrary/configs/__init__.py new file mode 100644 index 0000000..a73e279 --- /dev/null +++ b/BotLibrary/configs/__init__.py @@ -0,0 +1,8 @@ +# BotLibrary/library/__init__.py +# Инициализация пакета library, для работы с собственными библиотеками + +# Импортируем библиотеки для экспорта +from .config import * +from .settings import * +from .list_ids import * +from .important_path import * diff --git a/BotLibrary/library/__init__.py b/BotLibrary/library/__init__.py index 731768c..b81d42d 100644 --- a/BotLibrary/library/__init__.py +++ b/BotLibrary/library/__init__.py @@ -3,7 +3,11 @@ # Импортируем библиотеки для экспорта from .bots import * -from .decorator import * from .logger import * from .edit_bot import * from .directory import * +from .time import * + +from art import * +from colorama import * +from termcolor import * diff --git a/MySQL/__init__.py b/MySQL/__init__.py index b3cbfd7..d6591fa 100644 --- a/MySQL/__init__.py +++ b/MySQL/__init__.py @@ -6,7 +6,6 @@ __all__ = ("router", "db") # Импортируем библиотеки для экспорта from aiogram import Router -from .db import * # Создание роутера "sql_router" -- 2.49.1 From 03cf587919b52ca3c3acfb30ac94474ba54f83af Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:58:21 +0700 Subject: [PATCH 02/35] =?UTF-8?q?=D0=A3=D0=BB=D1=83=D1=87=D1=88=D0=B5?= =?UTF-8?q?=D0=BD=D0=BD=D0=B0=D1=8F=20=D0=BD=D0=B0=D1=81=D1=82=D1=80=D0=BE?= =?UTF-8?q?=D0=B9=D0=BA=D0=B0=20=D0=B1=D0=BE=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/library/bots.py | 75 +++++++++++++++++--------------------- 1 file changed, 34 insertions(+), 41 deletions(-) diff --git a/BotLibrary/library/bots.py b/BotLibrary/library/bots.py index 35a112d..ec3702c 100644 --- a/BotLibrary/library/bots.py +++ b/BotLibrary/library/bots.py @@ -1,53 +1,29 @@ # BotLibrary/library/bots.py # Создание и настройка бота в одном файле -import pytz -from tzlocal import get_localzone -from datetime import datetime from aiogram import Dispatcher, Bot, F from aiogram.client.default import DefaultBotProperties from aiogram.enums import ParseMode + from apscheduler.schedulers.asyncio import AsyncIOScheduler -from config import bot_token, BotVariables +from .time import * +from configs import bot_token, BotVariables # Настройка экспорта модулей и логирования -__all__ = ("bot_token", "dp", "bot", "scheduler", "F_Media", "BotInfo", "bot_get_info") +__all__ = ("dp", "bot", "scheduler", "F_Media", "BotInfo", "bot_get_info") log_type = "Bot" -# Получение времени по UTC -utc_now = datetime.now(pytz.utc) - -# Получение локального времени хоста (с использованием локального часового пояса) -local_tz = get_localzone() # Автоматически определяет локальный часовой пояс -local_now = utc_now.astimezone(local_tz) - -# Получение московского времени -moscow_tz = pytz.timezone("Europe/Moscow") -moscow_now = utc_now.astimezone(moscow_tz) - -# Форматирование времени UTC -utc_time = utc_now.strftime("%Y-%m-%d %H:%M:%S") + " (UTC)" - -# Форматирование времени хоста со сдвигом -utc_offset_host = local_now.utcoffset().total_seconds() / 3600 # Смещение в часах -host_time = local_now.strftime("%Y-%m-%d %H:%M:%S") + f" (UTC{int(utc_offset_host):+})" - -# Форматирование московского времени со сдвигом -utc_offset_moscow = moscow_now.utcoffset().total_seconds() / 3600 # Смещение в часах -moscow_time = moscow_now.strftime("%Y-%m-%d %H:%M:%S") + f" (UTC{int(utc_offset_moscow):+})" - - # Создание экземпляра диспатчера и его параметров dp = Dispatcher() dp["started_at"] = host_time -dp["started_at_msk"] = moscow_time +dp["started_at_msk"] = get_choice_time(TimeVariable.choice_utc_msk) dp["is_active"] = True # Флаг активности бота dp["logs"] = [] dp["users"] = {} dp["sessions"] = {} dp["task_queue"] = [] -dp["config"] = {"max_connections": 100, "retry_interval": 5, "time_format": BotVariables.time_format} +dp["configs"] = {"max_connections": 100, "retry_interval": 5, "time_format": TimeVariable.format} dp["metrics"] = {"messages_received": 0, "messages_sent": 0, "errors": 0} dp["modules"] = {} dp["state"] = {} @@ -58,21 +34,33 @@ dp["database"] = None # Объявление экземпляров и переменных -bot = Bot(token=bot_token, default=DefaultBotProperties(parse_mode=ParseMode.HTML)) # Объявление бота -scheduler = AsyncIOScheduler(timezone=BotVariables.time_zone) # Создание планировщика +bot_properties = DefaultBotProperties( + parse_mode=ParseMode.HTML, # Устанавливаем формат HTML для всех сообщений + disable_notification=True, # Отключаем уведомления при отправке сообщений + protect_content=True, # Защищаем содержимое сообщений от копирования + allow_sending_without_reply=True, # Разрешаем отправлять сообщения без ответа на другое сообщение + # link_preview=LinkPreviewOptions(), # Настройка для предварительного просмотра ссылок + link_preview_is_disabled=True, # Отключаем предварительный просмотр ссылок + show_caption_above_media=False, # Показываем подпись выше медиа +) +bot = Bot(token=bot_token, default=bot_properties) # Объявление бота +scheduler = AsyncIOScheduler(timezone=get_time_zone()) # Создание планировщика F_Media = F.photo | F.files | F.video | F.animation | F.voice | F.video_note # Фильтр-медиа # Класс для хранения данных о боте (некоторые переменные даны как шаблон) class BotInfo: # Статические переменные для хранения данных - id = 10000000 - first_name = "TESTBOT" - last_name = "" - username = "testbot" + id = None + first_name = None + last_name = None + username = None + description = None + short_description = None can_join_groups = None can_read_all_group_messages = None language_code = BotVariables.language + prefixs = BotVariables.prefixs is_premium = None added_to_attachment_menu = None supports_inline_queries = None @@ -86,13 +74,16 @@ class BotInfo: cls.first_name = bot_info.first_name cls.last_name = bot_info.last_name cls.username = bot_info.username - cls.can_join_groups = bot_info.can_join_groups - cls.can_read_all_group_messages = bot_info.can_read_all_group_messages + cls.description = getattr(bot_info, 'description', '') # Default to empty string if no description + cls.short_description = getattr(bot_info, 'description', '') + cls.language_code = bot_info.language_code cls.is_premium = bot_info.is_premium cls.added_to_attachment_menu = bot_info.added_to_attachment_menu 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) # Default to None if no attribute + cls.can_read_all_group_messages = getattr(bot_info, 'can_read_all_group_messages', None) # Default to None # Функция получения данных о боте @@ -110,12 +101,14 @@ async def bot_get_info(): 'first_name': bot_info_data.first_name, 'last_name': bot_info_data.last_name, 'username': bot_info_data.username, - 'can_join_groups': bot_info_data.can_join_groups, - 'can_read_all_group_messages': bot_info_data.can_read_all_group_messages, - 'language_code': BotVariables.language, + 'description': getattr(bot_info_data, 'description', ''), + 'short_description': getattr(bot_info_data, 'description', ''), + 'language_code': bot_info_data.language_code, + 'prefixs': BotVariables.prefixs, 'is_premium': bot_info_data.is_premium, 'added_to_attachment_menu': bot_info_data.added_to_attachment_menu, '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), } -- 2.49.1 From 114e8ceb0d353edaee1d50bbae9a77ba51d43d8a Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:59:00 +0700 Subject: [PATCH 03/35] =?UTF-8?q?=D0=A1=D0=B8=D1=81=D1=82=D0=B5=D0=BC?= =?UTF-8?q?=D0=B0=20=D0=BA=D0=BE=D0=BD=D1=84=D0=B8=D0=B3=D0=BE=D0=B2=20?= =?UTF-8?q?=D1=80=D0=B0=D0=B7=D0=B1=D0=B8=D1=82=D0=B0=20=D0=BD=D0=B0=20?= =?UTF-8?q?=D0=BC=D0=BE=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") -- 2.49.1 From f6d9559a4c17e0267b8750712ce8094e1fb72d54 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:59:12 +0700 Subject: [PATCH 04/35] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B1=D0=B0=D0=B3=D0=B8=20=D1=81=20?= =?UTF-8?q?=D0=B8=D0=B3=D0=BD=D0=BE=D1=80=D0=B8=D1=80=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=D0=BC=20=D0=BF=D0=B0=D0=BA=D0=B5=D1=82=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 78476d1..3086f02 100644 --- a/.gitignore +++ b/.gitignore @@ -3,12 +3,12 @@ # Игнорирование локального окружения и его файлов +.venv .env -.venv/ # Игнорирование пользовательских конфигураций IDE -/.idea +.idea *.iml @@ -18,8 +18,8 @@ Thumbs.db # Игнорирование директории сборки -/build/ -/dist/ +build/ +dist/ # Игнорирование всех скачанных данных логирования @@ -32,9 +32,9 @@ BotLogs/ # Игнорирование установщика проекта -/Test/project_clone.bat +Test/project_clone.bat # Игнорирование базы данных пользователя -/MySQL/user_data.db -/MySQL/user_data.json +MySQL/user_data.db +MySQL/user_data.json -- 2.49.1 From 8493cbb76f38c05b879432205418416ea0473675 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:59:25 +0700 Subject: [PATCH 05/35] =?UTF-8?q?=D0=A4=D1=83=D0=BD=D0=BA=D1=86=D0=B8?= =?UTF-8?q?=D0=B8=20=D0=B4=D0=B5=D0=BA=D0=BE=D1=80=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=8F=20=D1=83=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/library/decorator.py | 74 --------------------------------- 1 file changed, 74 deletions(-) delete mode 100644 BotLibrary/library/decorator.py diff --git a/BotLibrary/library/decorator.py b/BotLibrary/library/decorator.py deleted file mode 100644 index de1817f..0000000 --- a/BotLibrary/library/decorator.py +++ /dev/null @@ -1,74 +0,0 @@ -# BotLibrary/library/decorator.py -# Небольшая библиотека для декорирования текста - -from art import * -from colorama import * -from termcolor import * - -# Подключение ANSI в стандартное Windows_cmd -just_fix_windows_console() - - -# Некоторые возможности библиотеки art и termcolor (не полный, проще использовать сам art) -class ArtObject: - text_hw = colored("Привет, Мир!", "red", attrs=["reverse", "blink"]) - - coffe_art = art("coffee", number=1, space=1) # c[_] - women_art = art("woman", number=1, space=1) # ▓⚗_⚗▓ ▓⚗_⚗▓ - butterfly_art = art("butterfly", number=1, space=1) # Ƹ̵̡Ӝ̵̨̄Ʒ - happy_art = art("happy", number=1, space=1) # ۜ\(סּںסּَ` )/ۜ - random_art = art("random", number=1, space=1) # Вывод случайного арта из библиотеки - - block_font = 'block' # Делает большие квадраты вокруг рисунка - white_buble = 'white_bubble' # Делает вокруг букв белый кружок - cybermedium = 'cybermedium' # Делает текст более "киберпанковым" - random_font = 'random' # Делает случайный фон вокруг рисунка - - -# Коды для редактирования текста -class TextDecorator: - RESET_DECORATOR = "\033[0m" # Код для сброса форматирования - BOLD = "\033[1m" # Код для включения жирного текста - FAINT = "\033[2m" # Код для включения тонкого текста (редко поддерживается) - KURTIV = "\033[3m" # Код для включения курсива - UNDERLINE = "\033[4m" # Код для включения подчеркнутого текста - BLINK = "\033[5m" # Код для включения мигающего текста (редко поддерживается) - INVERT = "\033[7m" # Код для инверсированного цвета - HIDDEN = "\033[8m" # Код для скрытого текста - STRIKETHROUGH = "\033[9m" # Код для зачеркнутого текста - - # Коды для цвета текста - BLACK = "\033[30m" # Черный текст - RED = "\033[31m" # Красный текст - GREEN = "\033[32m" # Зеленый текст - YELLOW = "\033[33m" # Желтый текст - BLUE = "\033[34m" # Синий текст - MAGENTA = "\033[35m" # Пурпурный текст - CYAN = "\033[36m" # Бирюзовый текст - WHITE = "\033[37m" # Белый текст - LIGHT_BLACK = "\033[90m" # Светлый черный (серый) текст - LIGHT_RED = "\033[91m" # Светлый красный текст - LIGHT_GREEN = "\033[92m" # Светлый зеленый текст - LIGHT_YELLOW = "\033[93m" # Светлый желтый текст - LIGHT_BLUE = "\033[94m" # Светлый синий текст - LIGHT_MAGENTA = "\033[95m" # Светлый пурпурный текст - LIGHT_CYAN = "\033[96m" # Светлый бирюзовый текст - LIGHT_WHITE = "\033[97m" # Светлый белый текст - - # Коды для цвета фона - BLACK_BACKGROUND = "\033[40m" # Черный фон - RED_BACKGROUND = "\033[41m" # Красный фон - GREEN_BACKGROUND = "\033[42m" # Зеленый фон - YELLOW_BACKGROUND = "\033[43m" # Желтый фон - BLUE_BACKGROUND = "\033[44m" # Синий фон - MAGENTA_BACKGROUND = "\033[45m" # Пурпурный фон - CYAN_BACKGROUND = "\033[46m" # Бирюзовый фон - WHITE_BACKGROUND = "\033[47m" # Белый фон - LIGHT_BLACK_BACKGROUND = "\033[100m" # Светлый черный фон - LIGHT_RED_BACKGROUND = "\033[101m" # Светлый красный фон - LIGHT_GREEN_BACKGROUND = "\033[102m" # Светлый зеленый фон - LIGHT_YELLOW_BACKGROUND = "\033[103m" # Светлый желтый фон - LIGHT_BLUE_BACKGROUND = "\033[104m" # Светлый синий фон - LIGHT_MAGENTA_BACKGROUND = "\033[105m" # Светлый пурпурный фон - LIGHT_CYAN_BACKGROUND = "\033[106m" # Светлый бирюзовый фон - LIGHT_WHITE_BACKGROUND = "\033[107m" # Светлый белый фон -- 2.49.1 From 8488c3def47af6bb98eecd043a915696b9902b33 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 21:59:53 +0700 Subject: [PATCH 06/35] =?UTF-8?q?=D0=A3=D1=81=D1=82=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D1=89=D0=B8=D0=BA=20=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D0=B0=20=D0=BD=D0=B0=20PyPy=20(=D1=81=D0=B4=D0=B5=D0=BB=D0=B0?= =?UTF-8?q?=D1=82=D1=8C=20=D0=B2=D1=8B=D0=B1=D0=BE=D1=80+=D0=B2=20=D1=80?= =?UTF-8?q?=D0=B0=D0=B7=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- start.bat | 171 +++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 118 insertions(+), 53 deletions(-) diff --git a/start.bat b/start.bat index f59dd59..f0995a5 100644 --- a/start.bat +++ b/start.bat @@ -1,93 +1,158 @@ @echo off REM start.bat -REM Этот файл нужно запускать перед стартом проекта -REM Он создает локальное окружение, скачивает все зависимости -REM Чтобы запустить файл используйте: start start или ./start +REM Этот файл нужно запускать перед стартом проекта. +REM Он создает локальное окружение, скачивает все зависимости. +REM Чтобы запустить файл, используйте: start start или ./start. -REM Включение кодировки для Windows +REM Установить кодировку UTF-8 и заголовок для консоли. chcp 65001 > nul +title Запуск Бота-aiogram cls -REM Изменяем заголовок окна консоли -title Запуск Бота-aiogram - -REM Убедитесь, что PyPy установлен и доступен +REM Проверка установки PyPy. echo Проверка наличия PyPy... -pypy --version || ( +pypy --version > nul 2>&1 || ( color C - echo PyPy не установлен. Установите PyPy и повторите попытку. - echo Установите его по ссылке: https://www.pypy.org/download.html + echo [ОШИБКА]: PyPy не установлен. Установите PyPy и повторите попытку. + echo Ссылка для установки: https://www.pypy.org/download.html title Проект - PyPy не установлен! pause exit /b ) +echo [OK]: PyPy установлен. echo. -REM Проверка наличия Git +REM Проверка установки Git. echo Проверка наличия Git... git --version > nul 2>&1 || ( color C - echo Git не установлен. Установите Git и повторите попытку. - echo Установите его по ссылке: https://git-scm.com/downloads + echo [ОШИБКА]: Git не установлен. Установите Git и повторите попытку. + echo Ссылка для установки: https://git-scm.com/downloads title Проект - Git не установлен! pause exit /b ) +echo [OK]: Git установлен. echo. -REM Проверка наличия Git репозитория +REM Проверка и инициализация Git репозитория. if not exist .git ( echo Создание Git репозитория... - git init - echo Добавление удалённого репозитория... - git remote add origin https://github.com/Whyverum/PrimoPearlBot + git init > nul + git remote add origin https://github.com/Whyverum/PrimoPearlBot > nul + echo [OK]: Git репозиторий создан и настроен. ) else ( - echo Удалённый репозиторий уже настроен. + echo [OK]: Git репозиторий уже настроен. ) echo. -REM Создание .env для хранения токенов -echo Создаётся файл .env... -( - echo main_bot_token=Вставьте Токен бота с @BotFather - echo APIKey=Иной ключ-api - echo WebAPIKey=Иной ключ web-api - echo important_id=Иной важный айди - echo secret=Некий секрет -) > .env -echo. -echo Файл .env - успешно создан! -echo Пожалуйста, перейдите в файл и вставьте свои ключи. -pause > Вы готовы продолжить? Нажмите ENTER, чтобы продолжить! -echo. -pause > Вы уверены???Нажмите ENTER, чтобы продолжить! - -REM Создание виртуального окружения, если его еще нет +REM Создание виртуального окружения, если его еще нет. if not exist .venv ( echo Создание виртуального окружения... - pypy -m venv .venv - echo. + pypy -m venv .venv > nul + if %errorlevel% neq 0 ( + color C + echo [ОШИБКА]: Не удалось создать виртуальное окружение. + pause + exit /b + ) + echo [OK]: Виртуальное окружение создано. +) else ( + echo [OK]: Виртуальное окружение уже существует. ) +echo. -REM Активируем виртуальное окружение +REM Создание файла .env с вводом данных из консоли в папке .venv. +if not exist .venv\.env ( + echo Создаётся файл .env в папке .venv... + set /p main_bot_token=Введите токен бота (main_bot_token): + set /p APIKey=Введите ключ API (APIKey): + set /p WebAPIKey=Введите ключ Web API (WebAPIKey): + set /p important_id=Введите важный ID (important_id): + set /p secret=Введите секретный ключ (secret): + + REM Проверяем пустые значения. + if "%main_bot_token%"=="" ( + echo [ОШИБКА]: Токен бота не может быть пустым. + pause + exit /b + ) + if "%APIKey%"=="" ( + echo [ОШИБКА]: Ключ API не может быть пустым. + pause + exit /b + ) + if "%WebAPIKey%"=="" ( + echo [ОШИБКА]: Ключ Web API не может быть пустым. + pause + exit /b + ) + if "%important_id%"=="" ( + echo [ОШИБКА]: Важный ID не может быть пустым. + pause + exit /b + ) + if "%secret%"=="" ( + echo [ОШИБКА]: Секретный ключ не может быть пустым. + pause + exit /b + ) + + REM Создание файла .env. + ( + echo main_bot_token=%main_bot_token% + echo APIKey=%APIKey% + echo WebAPIKey=%WebAPIKey% + echo important_id=%important_id% + echo secret=%secret% + ) > .venv\.env + echo [OK]: Файл .env успешно создан в папке .venv! +) else ( + echo [OK]: Файл .env уже существует в папке .venv. +) +echo. + +REM Активация виртуального окружения. echo Активация виртуального окружения... -call .venv\Scripts\activate -echo. - -REM Установка Poetry, если не установлен -echo Проверка наличия Poetry... -poetry --version || ( - echo Установка Poetry... - pip install poetry +call .venv\Scripts\activate > nul +if %errorlevel% neq 0 ( + color C + echo [ОШИБКА]: Не удалось активировать виртуальное окружение. + pause + exit /b ) +echo [OK]: Виртуальное окружение активировано. echo. -REM Установка зависимостей из poetry.lock и pyproject.toml -echo Установка зависимостей... -poetry install -poetry update +REM Проверка и установка Poetry. +echo Проверка наличия Poetry... +poetry --version > nul 2>&1 || ( + echo Установка Poetry... + pip install poetry > nul + if %errorlevel% neq 0 ( + color C + echo [ОШИБКА]: Не удалось установить Poetry. + pause + exit /b + ) + echo [OK]: Poetry успешно установлен. +) +echo [OK]: Poetry установлен. echo. -REM Очистка консоли перед запуском main.py +REM Установка зависимостей. +echo Установка зависимостей проекта... +poetry install > nul +if %errorlevel% neq 0 ( + color C + echo [ОШИБКА]: Не удалось установить зависимости. + pause + exit /b +) +echo [OK]: Зависимости установлены. +echo. + +REM Очистка консоли перед запуском. cls -pause > Настройте конфигуратор или запустите main.py! +echo Все готово! Настройте конфигурацию или запустите main.py. +pause -- 2.49.1 From 9bb313759a0b24562283ac9667545f2353dd9f4f Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:00:20 +0700 Subject: [PATCH 07/35] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=B2=D1=81=D0=B5=D1=85=20=D1=82=D0=B8=D0=BF?= =?UTF-8?q?=D0=BE=D0=B2=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/analitics/type_messages.py | 73 ------------------------ BotLibrary/analitics/types_msg.py | 80 +++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 73 deletions(-) delete mode 100644 BotLibrary/analitics/type_messages.py create mode 100644 BotLibrary/analitics/types_msg.py diff --git a/BotLibrary/analitics/type_messages.py b/BotLibrary/analitics/type_messages.py deleted file mode 100644 index ae2451c..0000000 --- a/BotLibrary/analitics/type_messages.py +++ /dev/null @@ -1,73 +0,0 @@ -# BotLibrary/analitics/log_type.py -# Определение типа сообщения - -from .find_ids import find_chat_id -from config import BotEdit, ImportantPath - -# Настройка экспорта модулей и логирования -__all__ = ("types_message", "types_chat",) -log_type = "Type_message" - - -# Проверка на тип чата -def types_chat(message): - chat_id = find_chat_id(message) - if message.chat.type == "private": - file_path = f"{ImportantPath.private_message}/{chat_id}.txt" - else: - file_path = f"{ImportantPath.group_message}/{chat_id}.txt" - return file_path - - -# Проверка на тип сообщения -def types_message(message): - if message.pinned_message: # Закрепленное сообщение - file_type = "Закрепленное сообщение" - elif message.text: - first_char = message.text.strip()[0] if message.text.strip() else "" # Извлекаем первый символ текста - if first_char in BotEdit.prefixs: - file_type = "Команда" - else: - file_type = "Текст" - elif message.photo: - file_type = "Фото" - elif message.sticker: - file_type = "Стикер" - elif message.animation: - file_type = "Гиф" - elif message.voice: - file_type = "Голосовое сообщение" - elif message.video_note: - file_type = "Видеосообщение" - elif message.video: - file_type = "Видео" - elif message.audio: - file_type = "Аудио" - elif message.files: - file_type = "Документ" - elif message.contact: - file_type = "Контакт" - elif message.location: - file_type = "Локация" - elif message.venue: - file_type = "Место" - elif message.dice: - file_type = "Бросок кубика" - elif message.story: - file_type = "История" - elif message.game: - file_type = "Игра" - elif message.new_chat_members: - file_type = (f"Участник(и) присоединился(ись): " - f"{', '.join([member.username for member in message.new_chat_members if member.username])}") - elif message.left_chat_member: - file_type = f"Участник покинул чат: {message.left_chat_member.username or 'Неизвестный'}" - elif getattr(message, 'boost_added', False): # Проверяем наличие атрибута boost_added - file_type = "Буст чата!" - elif message.poll: - file_type = "Опрос" - elif message.forward_from or message.forward_from_chat: - file_type = "Пересланное сообщение" - else: - file_type = "Неизвестный тип сообщения" - return file_type diff --git a/BotLibrary/analitics/types_msg.py b/BotLibrary/analitics/types_msg.py new file mode 100644 index 0000000..0e904b8 --- /dev/null +++ b/BotLibrary/analitics/types_msg.py @@ -0,0 +1,80 @@ +# BotLibrary/analitics/log_type.py +# Определение типа сообщения + +from aiogram.types import ContentType +from configs import * +from .find_ids import find_imp_id + +# Настройка экспорта модулей и логирования +__all__ = ("types_message", "types_chat",) +log_type = "Type_message" + + +# Проверка на тип чата +def types_chat(message): + chat_id = find_imp_id(message.from_user.id) + if message.chat.type == "private": + file_path = f"{ProjectPath.private_message}/{chat_id}.txt" + else: + file_path = f"{ProjectPath.group_message}/{chat_id}.txt" + return file_path + + +def types_message(message): + # Словарь для соответствия типов сообщений + content_types = { + ContentType.TEXT: "Текст", + ContentType.PHOTO: "Фото", + ContentType.STICKER: "Стикер", + ContentType.ANIMATION: "Гиф", + ContentType.VOICE: "Голосовое сообщение", + ContentType.VIDEO_NOTE: "Видеосообщение", + ContentType.VIDEO: "Видео", + ContentType.AUDIO: "Аудио", + ContentType.DOCUMENT: "Документ", + ContentType.CONTACT: "Контакт", + ContentType.LOCATION: "Локация", + ContentType.VENUE: "Место", + ContentType.DICE: "Бросок кубика", + ContentType.STORY: "История", + ContentType.GAME: "Игра", + ContentType.POLL: "Опрос", + ContentType.FORUM_TOPIC_CREATED: "Создание темы на форуме", + ContentType.FORUM_TOPIC_EDITED: "Редактирование темы форума", + ContentType.FORUM_TOPIC_CLOSED: "Закрытие темы форума", + ContentType.FORUM_TOPIC_REOPENED: "Открытие темы форума", + ContentType.GENERAL_FORUM_TOPIC_HIDDEN: "Скрытие общей темы форума", + ContentType.GENERAL_FORUM_TOPIC_UNHIDDEN: "Раскрытие общей темы форума", + ContentType.GIVEAWAY_CREATED: "Создание розыгрыша", + ContentType.GIVEAWAY: "Розыгрыш", + ContentType.GIVEAWAY_WINNERS: "Победители розыгрыша", + ContentType.GIVEAWAY_COMPLETED: "Розыгрыш завершен", + ContentType.VIDEO_CHAT_SCHEDULED: "Запланированный видеочат", + ContentType.VIDEO_CHAT_STARTED: "Видеочат начат", + ContentType.VIDEO_CHAT_ENDED: "Видеочат завершен", + ContentType.VIDEO_CHAT_PARTICIPANTS_INVITED: "Участники приглашены в видеочат", + ContentType.PINNED_MESSAGE: "Закрепленное сообщение", + ContentType.INVOICE: "Счет", + ContentType.SUCCESSFUL_PAYMENT: "Успешный платеж", + ContentType.REFUNDED_PAYMENT: "Возврат платежа", + ContentType.USERS_SHARED: "Пользователи поделились", + ContentType.CHAT_SHARED: "Чат был передан", + ContentType.CONNECTED_WEBSITE: "Подключенный веб-сайт", + ContentType.WRITE_ACCESS_ALLOWED: "Разрешение на запись", + ContentType.PASSPORT_DATA: "Данные паспорта", + ContentType.PROXIMITY_ALERT_TRIGGERED: "Срабатывание предупреждения о близости", + ContentType.BOOST_ADDED: "Буст чата", + ContentType.CHAT_BACKGROUND_SET: "Установлен фон чата" + } + + # Проверяем тип сообщения и возвращаем описание + if message.pinned_message: # Закрепленное сообщение + return content_types.get(ContentType.PINNED_MESSAGE, "Закрепленное сообщение") + + # Проверка для обычных сообщений + for content_type, description in content_types.items(): + if getattr(message, content_type.value, None): + return description + + # Если сообщение не соответствует ни одному из типов + return "Неизвестный тип сообщения" -- 2.49.1 From e3543c24337cd9a61bb327747466325d04d99a39 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:01:10 +0700 Subject: [PATCH 08/35] =?UTF-8?q?=D0=9A=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D0=B0=20/randnum?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/keyboards/inline_kb/randnum_kb.py | 6 +++--- BotCode/routers/callback_handlers/randnum_kb_cb.py | 8 +++++++- BotCode/routers/commands/user_cmd/randnum_cmd.py | 8 +++++--- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/BotCode/keyboards/inline_kb/randnum_kb.py b/BotCode/keyboards/inline_kb/randnum_kb.py index fc21754..0fff06e 100644 --- a/BotCode/keyboards/inline_kb/randnum_kb.py +++ b/BotCode/keyboards/inline_kb/randnum_kb.py @@ -1,8 +1,8 @@ -# BotCode/keyboards/start_kb.py -# Создания клавиатуры на команду: /start +# BotCode/keyboards/inline_kb/randnum_kb.py +# Создания инлайн-клавиатуры на команду: /randnum from aiogram import Router -from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton +from aiogram.types import InlineKeyboardMarkup from aiogram.utils.keyboard import InlineKeyboardBuilder # Создание роутера и настройка экспорта diff --git a/BotCode/routers/callback_handlers/randnum_kb_cb.py b/BotCode/routers/callback_handlers/randnum_kb_cb.py index cad88b2..f6e5ec3 100644 --- a/BotCode/routers/callback_handlers/randnum_kb_cb.py +++ b/BotCode/routers/callback_handlers/randnum_kb_cb.py @@ -1,11 +1,17 @@ -from random import randint +# BotCode/routers/callback_handlers/randnum_kb_cb.py +# Обработчик запросов в команде /randnum +from random import randint from aiogram import Router, F from aiogram.types import CallbackQuery from keyboards.inline_kb.randnum_kb import ButtonInl, get_randnum_kb +# Создание роутера и настройка экспорта модулей +__all__ = ("router",) router = Router(name="randnum_kb_cb_router") + +# Тестирование редактирования сообщения @router.callback_query(F.data == ButtonInl.mark_cbd) async def random_site_cb(callback_query: CallbackQuery): await callback_query.answer() diff --git a/BotCode/routers/commands/user_cmd/randnum_cmd.py b/BotCode/routers/commands/user_cmd/randnum_cmd.py index ec10b68..634c099 100644 --- a/BotCode/routers/commands/user_cmd/randnum_cmd.py +++ b/BotCode/routers/commands/user_cmd/randnum_cmd.py @@ -5,18 +5,20 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * from keyboards.inline_kb.randnum_kb import get_randnum_kb +from routers.msg_default import msg_default -# Создание роутера и экспорта модулей +# Создание роутера, переменных и экспорта модулей __all__ = ("router", "cmd_randnum", "log_type",) router = Router(name="randnum_router") log_type = "Randnum" +description = "Описание" # Список ключевых слов для команды keywords = ["кфтвтгь", "randnum",] # Хэндлер на команду /randnum -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) async def cmd_randnum(message: types.Message): text = "Работа с рандомом оценок!" @@ -27,4 +29,4 @@ async def cmd_randnum(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) -- 2.49.1 From 22b8181e8ce2aee14f6e8dfa2555750563901542 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:01:33 +0700 Subject: [PATCH 09/35] =?UTF-8?q?=D0=A0=D0=B5=D0=B3=D1=83=D0=BB=D1=8F?= =?UTF-8?q?=D1=80=D0=BD=D1=8B=D0=B5=20=D0=B2=D1=8B=D1=80=D0=B0=D0=B6=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20(=D0=BD=D0=B5=20=D0=B8=D1=81=D0=BF=D0=BE?= =?UTF-8?q?=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D1=82=D1=81=D1=8F)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Test/old_files/regular_handlers.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Test/old_files/regular_handlers.py b/Test/old_files/regular_handlers.py index c3c3ac9..f51394e 100644 --- a/Test/old_files/regular_handlers.py +++ b/Test/old_files/regular_handlers.py @@ -6,7 +6,7 @@ from magic_filter import RegexpMode from re import Match from BotLibrary import logginger -import config +import configs # Настройка экспорта модулей и роутера __all__ = ("router",) @@ -15,7 +15,7 @@ router = Router(name="regular_handlers") # Хэндлер на циферный код (регулярная функция) @router.message( - F.from_user.id.in_(config.ListId.adm_list_id), + F.from_user.id.in_(configs.ListId.adm_list_id), F.text.regexp(r"(\d+)", mode=RegexpMode.MATCH).as_("code"), ) async def handle_code(message: types.Message, code: Match[str]): -- 2.49.1 From 05a79c414460f63525093dbffc0c0ba02cf64875 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:01:53 +0700 Subject: [PATCH 10/35] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=BD=D1=8B=D0=B5=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8?= =?UTF-8?q?=D0=B8=20=D0=B7=D0=B0=D0=B2=D0=B8=D1=81=D0=B8=D0=BC=D0=BE=D1=81?= =?UTF-8?q?=D1=82=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- poetry.lock | 2 +- pyproject.toml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/poetry.lock b/poetry.lock index 1868cf7..89fcc11 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1331,4 +1331,4 @@ propcache = ">=0.2.0" [metadata] lock-version = "2.0" python-versions = "^3.10" -content-hash = "5c732bafa39062b05f576fe9af74f08f65896e2af2788bbc502ccc8194f3cb68" +content-hash = "097c1d241fa62752422275b6a77b4a01de1d4774329740c01f9abffed43ee7c1" diff --git a/pyproject.toml b/pyproject.toml index 0ef6b08..1eef2a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,8 @@ charset-normalizer = "^3.4.0" frozenlist = "^1.5.0" customtkinter = "^5.2.2" pillow = "^11.0.0" +certifi = "^2024.12.14" +idna = "^3.10" [build-system] -- 2.49.1 From 6853470162791d37d5033f08bfd44c1763dca811 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:02:12 +0700 Subject: [PATCH 11/35] =?UTF-8?q?=D0=9D=D0=BE=D0=B2=D1=8B=D0=B5=20=D0=B1?= =?UTF-8?q?=D0=B0=D0=B7=D0=BE=D0=B2=D1=8B=D0=B5=20=D1=84=D1=83=D0=BD=D0=BA?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/routers/msg_default.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 BotCode/routers/msg_default.py diff --git a/BotCode/routers/msg_default.py b/BotCode/routers/msg_default.py new file mode 100644 index 0000000..cabf67b --- /dev/null +++ b/BotCode/routers/msg_default.py @@ -0,0 +1,12 @@ +# BotCode/routers/common/msg_default.py +# Небольшое облегчение для команд + +from loguru import logger +from routers.downloads.download_avatar_all import download_avatar +from BotLibrary.analitics.message_to_file import write_message_to_file +from BotLibrary.analitics.user_data_to_file import write_user_info_to_file + +async def msg_default(message): + await download_avatar(message) + await write_message_to_file(message) + write_user_info_to_file(message.from_user) -- 2.49.1 From 9b39866065bccb785dcb69d57090a3fe515c8a32 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:02:36 +0700 Subject: [PATCH 12/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/actor?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/keyboards/inline_kb/actor_kb.py | 6 +++--- BotCode/routers/callback_handlers/actor_kb_cb.py | 10 +++++++++- BotCode/routers/commands/user_cmd/actor_cmd.py | 8 +++++--- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/BotCode/keyboards/inline_kb/actor_kb.py b/BotCode/keyboards/inline_kb/actor_kb.py index 6d0dce2..ad5271d 100644 --- a/BotCode/keyboards/inline_kb/actor_kb.py +++ b/BotCode/keyboards/inline_kb/actor_kb.py @@ -1,8 +1,8 @@ -# BotCode/keyboards/start_kb.py -# Создания клавиатуры на команду: /start +# BotCode/keyboards/inline_kb/actor_kb.py +# Создания инлайн-клавиатуры на команду: /actor from aiogram import Router -from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton +from aiogram.types import InlineKeyboardMarkup from aiogram.utils.keyboard import InlineKeyboardBuilder # Создание роутера и настройка экспорта diff --git a/BotCode/routers/callback_handlers/actor_kb_cb.py b/BotCode/routers/callback_handlers/actor_kb_cb.py index 6011d7a..d43d1ed 100644 --- a/BotCode/routers/callback_handlers/actor_kb_cb.py +++ b/BotCode/routers/callback_handlers/actor_kb_cb.py @@ -1,11 +1,17 @@ -from random import randint +# BotCode/routers/callback_handlers/actor_kb_cb.py +# Обработчик запросов в команде /actor +from random import randint from aiogram import Router, F from aiogram.types import CallbackQuery from keyboards.inline_kb.actor_kb import ButtonInl +# Создание роутера и настройка экспорта модулей +__all__ = ("router",) router = Router(name="actor_kb_cb_router") + +# Тестирование реферальных ссылок @router.callback_query(F.data == ButtonInl.random_site_cbd) async def random_site_cb(callback_query: CallbackQuery): bot_me = await callback_query.bot.me() @@ -14,6 +20,7 @@ async def random_site_cb(callback_query: CallbackQuery): ) +# Тестирование уведомления для пользователя @router.callback_query(F.data == ButtonInl.random_num_dice_cbd) async def random_num_dice_cb(callback_query: CallbackQuery): await callback_query.answer( @@ -22,6 +29,7 @@ async def random_num_dice_cb(callback_query: CallbackQuery): ) +# Тестирование модального окна для пользователя @router.callback_query(F.data == ButtonInl.random_num_modal_cdb) async def random_num_dice_modal_cb(callback_query: CallbackQuery): await callback_query.answer( diff --git a/BotCode/routers/commands/user_cmd/actor_cmd.py b/BotCode/routers/commands/user_cmd/actor_cmd.py index 140a83b..90c416c 100644 --- a/BotCode/routers/commands/user_cmd/actor_cmd.py +++ b/BotCode/routers/commands/user_cmd/actor_cmd.py @@ -5,11 +5,13 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * from keyboards.inline_kb.actor_kb import get_actor_kb +from routers.msg_default import * -# Создание роутера и настройка экспорта модулей +# Создание роутера, переменных и настройка экспорта модулей __all__ = ("router", "cmd_actor", "log_type",) router = Router(name="actor_router") log_type = "Actor" +description = "Описание" # Список ключевых слов для команды @@ -17,7 +19,7 @@ keywords = ["actor", "фсещк",] # Обработчик команды /actor -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) async def cmd_actor(message: types.Message): try: @@ -33,7 +35,7 @@ async def cmd_actor(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: -- 2.49.1 From e35e377d5c25498df1164a5c867c459ee6755580 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:02:46 +0700 Subject: [PATCH 13/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/ban?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Test/commands/ban_cmd.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Test/commands/ban_cmd.py b/Test/commands/ban_cmd.py index 2a1598d..c022f72 100644 --- a/Test/commands/ban_cmd.py +++ b/Test/commands/ban_cmd.py @@ -15,7 +15,7 @@ command_text = "BAN" # Функция проверки блокировки пользователя в боте @router.message(lambda message: message.from_user.id in ListId.ban_list_id) -async def banned_user(message: types.Message): +async def banned_user(message: types_msg.Message): try: # Вывод сообщения пользователю chat_id = await find_chat_id(message) @@ -36,7 +36,7 @@ async def banned_user(message: types.Message): # Обработчик команды /ban @router.message(Command("ban", "ифт", "бан", ",fy", prefix=BotEdit.prefixs, ignore_case=True)) -async def ban_user_by_username(message: types.Message): +async def ban_user_by_username(message: types_msg.Message): try: text = f"использовал(а) команду /{command_text.lower()}" -- 2.49.1 From 154ae6af27e805159e5a0192c0a53bbd5ff3b95d Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:02:54 +0700 Subject: [PATCH 14/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/exit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/routers/commands/user_cmd/exit_cmd.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/BotCode/routers/commands/user_cmd/exit_cmd.py b/BotCode/routers/commands/user_cmd/exit_cmd.py index 819f0f1..138d2c8 100644 --- a/BotCode/routers/commands/user_cmd/exit_cmd.py +++ b/BotCode/routers/commands/user_cmd/exit_cmd.py @@ -4,18 +4,20 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * +from routers.msg_default import msg_default -# Создание роутера и экспорта модулей -__all__ = ("router", "exit_cmd", "log_type",) +# Создание роутера, переменных и экспорта модулей +__all__ = ("router", "exit_cmd", "log_type", "description") router = Router(name="exit_router") log_type = "Exit" +description = "Выйти из чата (в разработке)" # Список ключевых слов для команды keywords = ["выход", "ds[j;", "exit", "учше",] # Обработчик команды /exit -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) async def exit_cmd(message: types.Message): try: @@ -26,7 +28,7 @@ async def exit_cmd(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: -- 2.49.1 From 97ffc61aa2090aead840533f647aeacf7769034e Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:03:04 +0700 Subject: [PATCH 15/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/help?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/keyboards/reply_kb/help_kb.py | 11 +---------- BotCode/routers/commands/user_cmd/help_cmd.py | 10 ++++++---- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/BotCode/keyboards/reply_kb/help_kb.py b/BotCode/keyboards/reply_kb/help_kb.py index ac91539..a52aace 100644 --- a/BotCode/keyboards/reply_kb/help_kb.py +++ b/BotCode/keyboards/reply_kb/help_kb.py @@ -1,4 +1,4 @@ -# BotCode/keyboards/help_kb.py +# BotCode/keyboards/reply_kb/help_kb.py # Создание клавиатуры для сообщения: "Помогите!" from aiogram import Router, F @@ -22,15 +22,6 @@ def get_help_kb() -> ReplyKeyboardMarkup: ] buttons_row = [KeyboardButton(text=num) for num in numbers] - # Один из способов создания клавиатур - - # - # markup = ReplyKeyboardMarkup( - # keyboard=[buttons_row], - # resize_keyboard=True, - # ) - # return markup - builder = ReplyKeyboardBuilder() for num in numbers: builder.button(text=num) diff --git a/BotCode/routers/commands/user_cmd/help_cmd.py b/BotCode/routers/commands/user_cmd/help_cmd.py index 27e0742..c2857cd 100644 --- a/BotCode/routers/commands/user_cmd/help_cmd.py +++ b/BotCode/routers/commands/user_cmd/help_cmd.py @@ -5,11 +5,13 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * from keyboards.reply_kb.help_kb import get_help_kb +from routers.msg_default import msg_default -# Создание роутера и экспорта модулей -__all__ = ("router", "cmd_help", "log_type",) +# Создание роутера, переменных и экспорта модулей +__all__ = ("router", "cmd_help", "log_type", "description") router = Router(name="help_router") log_type = "Help" +description = "Получить помощь" # Список ключевых слов для команды keywords = ["help", "info", "помощь", "инфо", "?", "информация", "рудз", "штащ", "byaj", @@ -17,7 +19,7 @@ keywords = ["help", "info", "помощь", "инфо", "?", "информаци # Хэндлер на команду /info или /help -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) async def cmd_help(message: types.Message): try: @@ -28,7 +30,7 @@ async def cmd_help(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: -- 2.49.1 From 9e229bc6917acb482b3e081fc8574392dc7b0589 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:03:12 +0700 Subject: [PATCH 16/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/more?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/keyboards/reply_kb/more_kb.py | 2 +- BotCode/routers/commands/user_cmd/more_cmd.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/BotCode/keyboards/reply_kb/more_kb.py b/BotCode/keyboards/reply_kb/more_kb.py index a96ff7d..d743880 100644 --- a/BotCode/keyboards/reply_kb/more_kb.py +++ b/BotCode/keyboards/reply_kb/more_kb.py @@ -1,4 +1,4 @@ -# BotCode/keyboards/more_kb.py +# BotCode/keyboards/reply_kb/more_kb.py # Создания клавиатуры на команду: /more from aiogram import Router diff --git a/BotCode/routers/commands/user_cmd/more_cmd.py b/BotCode/routers/commands/user_cmd/more_cmd.py index ed917e3..c7e6422 100644 --- a/BotCode/routers/commands/user_cmd/more_cmd.py +++ b/BotCode/routers/commands/user_cmd/more_cmd.py @@ -5,18 +5,20 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * from keyboards.reply_kb.more_kb import get_more_kb +from routers.msg_default import msg_default -# Создание роутера и экспорта модулей +# Создание роутера, переменных и экспорта модулей __all__ = ("router", "cmd_start", "log_type",) router = Router(name="more_router") log_type = "More" +description = "Описание" # Список ключевых слов для команды keywords = ["more", "ьщку",] # Обработчик команды /more -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) async def cmd_start(message: types.Message): try: @@ -26,7 +28,7 @@ async def cmd_start(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: -- 2.49.1 From 133c8fa8438c6eadb7ba3a2f9c06a770e45090ea Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:03:38 +0700 Subject: [PATCH 17/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/start?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/keyboards/reply_kb/start_kb.py | 2 +- .../routers/commands/user_cmd/start_cmd.py | 10 ++++++---- BotLibrary/analitics/start_info_out.py | 19 ++++++++++--------- 3 files changed, 17 insertions(+), 14 deletions(-) diff --git a/BotCode/keyboards/reply_kb/start_kb.py b/BotCode/keyboards/reply_kb/start_kb.py index 5299e82..f3f7db5 100644 --- a/BotCode/keyboards/reply_kb/start_kb.py +++ b/BotCode/keyboards/reply_kb/start_kb.py @@ -1,4 +1,4 @@ -# BotCode/keyboards/start_kb.py +# BotCode/keyboards/reply_kb/start_kb.py # Создания клавиатуры на команду: /start from aiogram import Router diff --git a/BotCode/routers/commands/user_cmd/start_cmd.py b/BotCode/routers/commands/user_cmd/start_cmd.py index a4d73f5..973e91b 100644 --- a/BotCode/routers/commands/user_cmd/start_cmd.py +++ b/BotCode/routers/commands/user_cmd/start_cmd.py @@ -5,11 +5,13 @@ from aiogram import Router, types, F from aiogram.filters import Command, CommandStart from BotLibrary import * from keyboards.reply_kb.start_kb import get_start_kb +from routers.msg_default import msg_default -# Создание роутера и настройка экспорта модулей -__all__ = ("router", "cmd_start", "log_type",) +# Создание роутера, переменных и настройка экспорта модулей +__all__ = ("router", "cmd_start", "log_type", "description") router = Router(name="start_router") log_type = "Start" +description = "Запустить бота" # Список ключевых слов для команды keywords = ["start", "старт", "запуск", "пуск", "on", "вкл", "с", "s", "ы", @@ -17,7 +19,7 @@ keywords = ["start", "старт", "запуск", "пуск", "on", "вкл", " # Обработчик команды /start -@router.message(Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(keywords)) @router.message(CommandStart()) async def cmd_start(message: types.Message): @@ -30,7 +32,7 @@ async def cmd_start(message: types.Message): # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: diff --git a/BotLibrary/analitics/start_info_out.py b/BotLibrary/analitics/start_info_out.py index 1b8facf..6363b42 100644 --- a/BotLibrary/analitics/start_info_out.py +++ b/BotLibrary/analitics/start_info_out.py @@ -3,12 +3,13 @@ # Логирование стартов бота в bot_start.log from datetime import datetime -from timer import sleep +from colorama import Fore from loguru import logger +from time import sleep -from config import ImportantPath, BotVariables +from ..configs import ProjectPath, default_encod +from ..library.time import TimeVariable from ..library.bots import BotInfo -from ..library.decorator import TextDecorator # Настройка экспорта модулей и логирования __all__ = ("bot_info_out",) @@ -17,14 +18,14 @@ log_type = "Start_INFO" # Функция для получения информации о боте и выводе ее в консоль и файл def bot_info_out(): - bot_time = f"Бот @{BotInfo.username} запущен в {datetime.now().strftime(BotVariables.time_format)}\n" + bot_time = f"Бот @{BotInfo.username} запущен в {datetime.now().strftime(TimeVariable.format)}\n" bot_name = f"Основное имя: {BotInfo.first_name}\n" bot_postname = f" Доп. имя: {BotInfo.last_name}\n" bot_username = f" Юзернейм: @{BotInfo.username}\n" bot_id = f" ID: {BotInfo.id}\n" bot_language = f" Языковой код: {BotInfo.language_code}\n" bot_can_join_groups = f" Может ли вступать в группы: {BotInfo.can_join_groups}\n" - bot_can_read_all_group_messages = f" Чтение всех сообщений: {BotInfo.can_read_all_group_messages}\n" + bot_can_read_all_group_messages = f" Чтение всех сообщений: {BotInfo.can_read_all_group_messages}\n" # Теперь атрибут существует bot_is_premium = f" Является премиум-ботом: {BotInfo.is_premium}\n" bot_added_to_attachment_menu = f" Добавлен в меню вложений: {BotInfo.added_to_attachment_menu}\n" bot_supports_inline_queries = f" Поддерживает инлайн-запросы: {BotInfo.supports_inline_queries}\n" @@ -39,20 +40,20 @@ def bot_info_out(): # Печатаем все данные в консоль с задержкой в 1 секунду sleep(1) - print(TextDecorator.BLUE, bot_all_info, TextDecorator.RESET_DECORATOR) + print(Fore.CYAN + bot_all_info) # Записываем информацию в файл try: - with open(ImportantPath.log_info, 'w', encoding=BotVariables.encoding) as log_file: + with open(ProjectPath.log_info, 'w', encoding=default_encod) as log_file: log_file.write(f"{bot_time}{bot_all_info}") # Создание файла bot_start.log - with open(ImportantPath.log_start, 'a', encoding=BotVariables.encoding) as log_start_file: + with open(ProjectPath.log_start, 'a', encoding=default_encod) as log_start_file: log_start_file.write(f"{bot_time}\n") + return bot_all_info # Проверка на ошибку и ее логирование except Exception as e: text_error = f"Ошибка при получении ID пользователя: {e}" logger.bind(log_type="INFO", user=log_type).error(text_error) - return text_error -- 2.49.1 From c39453bd7c83d09b6d124f1ae2c95fb0aa9ee627 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:04:12 +0700 Subject: [PATCH 18/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/start=5Ftime=20=D0=B8=20=D0=B2=D1=80=D0=B5=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../commands/user_cmd/start_time_cmd.py | 10 ++-- BotLibrary/library/time.py | 49 +++++++++++++++++++ 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/BotCode/routers/commands/user_cmd/start_time_cmd.py b/BotCode/routers/commands/user_cmd/start_time_cmd.py index c491b37..f348701 100644 --- a/BotCode/routers/commands/user_cmd/start_time_cmd.py +++ b/BotCode/routers/commands/user_cmd/start_time_cmd.py @@ -4,11 +4,13 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * +from routers.msg_default import msg_default -# Создание роутера и настройка экспорта модулей -__all__ = ("router", "start_time", "log_type",) +# Создание роутера, переменных и настройка экспорта модулей +__all__ = ("router", "start_time", "log_type", "description") router = Router(name="start_time_router") log_type = "Start_Time" +description = "Время запуска" # Список ключевых слов для команды start_time_keywords = ["start_time", "stime", "старт_время", "время_старта", "с_время", @@ -17,7 +19,7 @@ start_time_keywords = ["start_time", "stime", "старт_время", "врем # Хэндлер на команду /start_time -@router.message(Command(*start_time_keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(Command(*start_time_keywords, prefix=BotVariables.prefixs, ignore_case=True)) @router.message(F.text.lower().in_(start_time_keywords)) async def start_time(message: types.Message, started_at: str, started_at_msk: str): try: @@ -29,7 +31,7 @@ async def start_time(message: types.Message, started_at: str, started_at_msk: st # Активация логгера await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: diff --git a/BotLibrary/library/time.py b/BotLibrary/library/time.py index e69de29..65e291e 100644 --- a/BotLibrary/library/time.py +++ b/BotLibrary/library/time.py @@ -0,0 +1,49 @@ +# BotLibrary/library/time.py +# Библиотека поиски времени + +import pytz +from tzlocal import get_localzone +from datetime import datetime + +# Настройка экспорта модулей и логирования +__all__ = ("TimeVariable", "host_time", "get_choice_time", "get_time_zone") +log_type = "Time" + + +"""Создание класса с временными параметрами""" +class TimeVariable: + format = "%Y-%m-%d %H:%M:%S" + another_format = "%S:%M:%H %d-%m-%Y" + choice_main_utc = "Asia/Novosibirsk" + choice_utc_msk = "Europe/Moscow" + + +"""Получение времени хоста и иного места""" +timezone = pytz.timezone(TimeVariable.choice_utc_msk) +host_time = datetime.now(timezone) + + +"""Функция получения локальной временной зоны""" +def get_time_zone(): + local_timezone = get_localzone() + return local_timezone.key + + +"""Возвращает текущее время по выбранному часовому поясу в формате строки""" +def get_choice_time(choice_utc): + # Текущее время в UTC + utc_now = datetime.now(pytz.utc) + + # Московский часовой пояс + choice_tz = pytz.timezone(choice_utc) + + # Перевод времени в московский часовой пояс + choice_now = utc_now.astimezone(choice_tz) + + # Смещение UTC для Москвы + utc_offset_choice = choice_now.utcoffset().total_seconds() / 3600 # Смещение в часах + + # Форматирование времени + choice_time = choice_now.strftime(TimeVariable.format) + f" (UTC{int(utc_offset_choice):+})" + + return choice_time -- 2.49.1 From 38040368ed73387eac8f935354fd4120e66288aa Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:04:34 +0700 Subject: [PATCH 19/35] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=B0=20=D0=B4=D0=B5=D0=BD=D1=8C=20=D1=80?= =?UTF-8?q?=D0=BE=D0=B6=D0=B4=D0=B5=D0=BD=D0=B8=D0=B5=20(=D0=BF=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B5=D1=80=D0=B8=D1=82=D1=8C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/analitics/user_data_to_file.py | 32 ++++++++++++++--------- 1 file changed, 20 insertions(+), 12 deletions(-) diff --git a/BotLibrary/analitics/user_data_to_file.py b/BotLibrary/analitics/user_data_to_file.py index 7447315..8ff4f2d 100644 --- a/BotLibrary/analitics/user_data_to_file.py +++ b/BotLibrary/analitics/user_data_to_file.py @@ -1,10 +1,13 @@ # BotLibrary/analitics/user_data_to_file.py -# Запись информации о пользователях в файл "user_data.db" (Сделать счетчик пользователей) +# Запись информации о пользователи в базу данных import os import json import datetime -from config import ImportantPath, BotVariables + +from aiogram.types import User, Birthdate +from configs import * +from ..library.time import TimeVariable # Настройка экспорта модулей и логирования __all__ = ("write_user_info_to_file", "format_user_record",) @@ -12,13 +15,13 @@ log_type = "User_data_file" # Функция записи информации в JSON-файл -def write_user_info_to_file(user): - directory = os.path.dirname(ImportantPath.user_info_file) +def write_user_info_to_file(user: User): + directory = os.path.dirname(ProjectPath.user_info_file) if not os.path.exists(directory): os.makedirs(directory) - if os.path.exists(ImportantPath.user_info_file): - with open(ImportantPath.user_info_file, "r", encoding=BotVariables.encoding) as file: + if os.path.exists(ProjectPath.user_info_file): + with open(ProjectPath.user_info_file, "r", encoding=default_encod) as file: try: user_data = json.load(file) except json.JSONDecodeError: @@ -29,19 +32,24 @@ def write_user_info_to_file(user): user_record = format_user_record(user) user_data[str(user.id)] = user_record - with open(ImportantPath.user_info_file, "w", encoding=BotVariables.encoding) as file: + with open(ProjectPath.user_info_file, "w", encoding=default_encod) as file: json.dump(user_data, file, ensure_ascii=False, indent=4) - return f"Информация о пользователе успешно записана или обновлена." - # Функция форматирования вывода в JSON-файл -def format_user_record(user): +def format_user_record(user: User): first_name = getattr(user, 'first_name', '') # Получаем имя last_name = getattr(user, 'last_name', '') # Получаем фамилию или пустую строку + # Получение даты рождения + birthdate = getattr(user, 'birthdate', None) + if isinstance(birthdate, Birthdate): + birthdate_str = f"{birthdate.day:02d}.{birthdate.month:02d}.{birthdate.year or 'Не указано'}" + else: + birthdate_str = "Не указано" + return { - "Время знакомства": datetime.datetime.now().strftime(BotVariables.time_format), + "Время знакомства": datetime.datetime.now().strftime(TimeVariable.format), "Имя": first_name, "Фамилия": last_name, "Юзернейм": f"@{getattr(user, 'username', 'Не указано')}", @@ -50,5 +58,5 @@ def format_user_record(user): "Бот": getattr(user, 'is_bot', False), "Премиум": getattr(user, 'is_premium', False), "Язык": getattr(user, 'language_code', 'Не указано'), + "Дата рождения": birthdate_str, # Добавляем дату рождения } - -- 2.49.1 From c8af3efb0b3bb153e842dedb11c371fab645eb65 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:04:57 +0700 Subject: [PATCH 20/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BE=D0=B1=D1=8B=D1=87=D0=BD=D1=8B?= =?UTF-8?q?=D1=85=20=D1=81=D0=BE=D0=BE=D0=B1=D1=89=D0=B5=D0=BD=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/routers/common/messages.py | 15 ++++++--------- BotCode/routers/common/phrase.py | 26 +++++++++++++++----------- 2 files changed, 21 insertions(+), 20 deletions(-) diff --git a/BotCode/routers/common/messages.py b/BotCode/routers/common/messages.py index 521c70b..3d9907f 100644 --- a/BotCode/routers/common/messages.py +++ b/BotCode/routers/common/messages.py @@ -4,22 +4,19 @@ from BotLibrary import * from aiogram import Router, types - -from ..downloads.download_avatar_all import download_avatar +from routers.msg_default import * # Настройка экспорта модулей и роутера __all__ = ("router",) router = Router(name="common_message_router") +log_type = "Messages" + # Хэндлер на все сообщения и записывает данные @router.message() async def handle_all_messages(message: types.Message): - log_type = "Messages" - name = find_chat_id(message) + user_name = find_imp_id(message.from_user.id) message_type = types_message(message) - await logginger(message) - await download_avatar(message) - - await common_msg_logginger(message, name, message_type, log_type) - return f"Получено новое сообщение!" + await common_msg_logginger(message, user_name, message_type, log_type) + await msg_default(message) diff --git a/BotCode/routers/common/phrase.py b/BotCode/routers/common/phrase.py index 91027ab..7083a1a 100644 --- a/BotCode/routers/common/phrase.py +++ b/BotCode/routers/common/phrase.py @@ -1,11 +1,16 @@ +# BotCode/routers/common/phrase.py +# Обработчик особых команд + from aiogram import Router, types, F from aiogram.types import ReplyKeyboardRemove -from BotLibrary import find_chat_id, types_message, common_msg_logginger +from routers.msg_default import * +from BotLibrary import find_imp_id, types_message, common_msg_logginger from keyboards.reply_kb.start_kb import ButtonText # Настройка экспорта модулей и роутера __all__ = ("router",) + router = Router(name="phrase_message_router") @@ -14,7 +19,7 @@ router = Router(name="phrase_message_router") async def hello_message(message: types.Message): log_type = "Start_Button" text_message = f"Привет, я бот. А ты кто?" - name = find_chat_id(message) + name = find_imp_id(message.from_user.id) message_type = types_message(message) await message.reply( @@ -22,8 +27,7 @@ async def hello_message(message: types.Message): ) await common_msg_logginger(message, name, message_type, log_type) - return text_message - + await msg_default(message) # Ответ бота на кнопку или сообщение: "Помощь!" @@ -31,7 +35,7 @@ async def hello_message(message: types.Message): async def help_message(message: types.Message): log_type = "Help_Button" text_message = f"Привет, я надеюсь помогу тебе... Лучше напиши /help.." - name = find_chat_id(message) + name = find_imp_id(message.from_user.id) message_type = types_message(message) await message.reply( @@ -39,7 +43,7 @@ async def help_message(message: types.Message): ) await common_msg_logginger(message, name, message_type, log_type) - return text_message + await msg_default(message) # Ответ бота на кнопку или сообщение: "Пока-пока!" @@ -47,7 +51,7 @@ async def help_message(message: types.Message): async def bye_message(message: types.Message): log_type = "Messages" text_message = f"Надеюсь скоро увидимся! Захочешь поговорить нажми на /start!" - name = find_chat_id(message) + name = find_imp_id(message.from_user.id) message_type = types_message(message) await message.reply( @@ -56,15 +60,15 @@ async def bye_message(message: types.Message): ) await common_msg_logginger(message, name, message_type, log_type) - return text_message + await msg_default(message) # Ответ бота на сообщение: "Кошмар" @router.message(F.text.lower() == "кошмар") async def scary_message(message: types.Message): - log_type = "Messages" + log_type = "Scary" text_message = f"Кошмар, тот еще!" - name = find_chat_id(message) + name = find_imp_id(message.from_user.id) message_type = types_message(message) await message.reply( @@ -72,4 +76,4 @@ async def scary_message(message: types.Message): ) await common_msg_logginger(message, name, message_type, log_type) - return text_message + await msg_default(message) -- 2.49.1 From 7e9dfd4d1b61e8709482aa9e562012f4a8de0dfa Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:05:13 +0700 Subject: [PATCH 21/35] =?UTF-8?q?=D0=9F=D0=BE=D0=B4=D1=81=D1=87=D0=B5?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=B4=D0=B0=20=D0=B2=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B5=D0=BA=D1=82=D0=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- project_count_line.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/project_count_line.py b/project_count_line.py index f027ed1..0f1ac26 100644 --- a/project_count_line.py +++ b/project_count_line.py @@ -1,9 +1,14 @@ +# project_count_line.py +# Файл для подсчета количества строк и файлов + import os # Настройка экспорта модулей __all__ = ("count_lines_in_python_files",) type_messages = "count_lines_project" + +# Функция подсчета строк и кода python3 def count_lines_in_python_files(directory): total_lines = 0 total_files = 0 @@ -32,8 +37,8 @@ def count_lines_in_python_files(directory): return total_lines, total_files # Задайте путь к вашей директории -directory_path = r'/' +directory_path = r'./' lines_count, files_count = count_lines_in_python_files(directory_path) -print(f'Общее количество строк в файлах .py: {lines_count}') -print(f'Общее количество файлов .py: {files_count}') +print(f"Общее количество строк в файлах .py: {lines_count}") +print(f"Общее количество файлов .py: {files_count}") -- 2.49.1 From b793233c0b324007a950403866c4cf444690c184 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:05:28 +0700 Subject: [PATCH 22/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/secret?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../routers/administration/admin_cmd/secret_cmd.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/BotCode/routers/administration/admin_cmd/secret_cmd.py b/BotCode/routers/administration/admin_cmd/secret_cmd.py index 17e7847..223a83b 100644 --- a/BotCode/routers/administration/admin_cmd/secret_cmd.py +++ b/BotCode/routers/administration/admin_cmd/secret_cmd.py @@ -7,6 +7,9 @@ from BotLibrary import * # Создание роутера и настройка экспорта модулей __all__ = ("router",) + +from routers.msg_default import msg_default + router = Router(name="secret_message_router") log_type = "Admin" @@ -16,12 +19,13 @@ keywords = ["secret", "секрет", "ыускуе", "ctrhtn", # Обработчик команды /secret или сообщений с текстом из списка keywords -@router.message(F.from_user.id.in_(ListId.important_ids), - Command(*keywords, prefix=BotEdit.prefixs, ignore_case=True)) -@router.message(F.from_user.id.in_(ListId.important_ids), F.text.lower().in_(keywords)) +@router.message(F.from_user.id.func(lambda user_id: str(user_id) in DataID.important.keys()), + Command(*keywords, prefix=BotVariables.prefixs, ignore_case=True)) +@router.message(F.from_user.id.func(lambda user_id: str(user_id) in DataID.important.keys()), + F.text.lower().in_(keywords)) async def secret_admin_message(message: types.Message): text = f"Привет, важная персона!" await message.reply(text) await cmd_logginger(message, log_type, text) - return text + await msg_default(message) -- 2.49.1 From 1bb1cc60fbd7259b541e910ac0d30380cc2596aa Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:05:40 +0700 Subject: [PATCH 23/35] =?UTF-8?q?=D0=9E=D0=B1=D1=80=D0=B0=D0=B1=D0=BE?= =?UTF-8?q?=D1=82=D1=87=D0=B8=D0=BA=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= =?UTF-8?q?=D1=8B=20/send=20(=D0=B2=20=D1=80=D0=B0=D0=B7=D1=80=D0=B0=D0=B1?= =?UTF-8?q?=D0=BE=D1=82=D0=BA=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Test/commands/send_to_user.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Test/commands/send_to_user.py b/Test/commands/send_to_user.py index cade07b..9eb0b2f 100644 --- a/Test/commands/send_to_user.py +++ b/Test/commands/send_to_user.py @@ -12,10 +12,10 @@ command_text = "Send" # Обработчик команды /send для отправки сообщения определенному пользователю (в разработке) -@router.message(F.from_user.id.in_(ListId.important_ids), +@router.message(F.from_user.id.in_(ListId.important), Command("send", "отправить", "отправ", "s", "ыутв", "jnghfdbnm", "jnghfd", prefix=BotEdit.prefixs, ignore_case=True)) -async def send_message(message: types.Message): +async def send_message(message: types_msg.Message): try: if message.chat.id in ListId.adm_list_id: text = f"использовал(а) команду /{command_text.lower()}" @@ -37,7 +37,7 @@ async def send_message(message: types.Message): await bot.send_message(chat_id=user_id, text=text_send) # Логирование - user_id = find_people_id(user_id) + user_id = find_imp_id(user_id) await cmd_logginger(message, command_text, text) # Логирование и отчет об отправке -- 2.49.1 From 41f7b918ec3e93f5c3b857ba105bb079a4731948 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:06:11 +0700 Subject: [PATCH 24/35] =?UTF-8?q?=D0=98=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=B1=D0=B0=D0=B7=D1=8B=20=D0=B4=D0=B0?= =?UTF-8?q?=D0=BD=D0=BD=D1=8B=D1=85=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE?= =?UTF-8?q?=D0=B2=D0=B0=D1=82=D0=B5=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MySQL/list_ids.json | 33 +++++++++++++++++++++++++++++++ MySQL/list_ids.py | 47 --------------------------------------------- 2 files changed, 33 insertions(+), 47 deletions(-) create mode 100644 MySQL/list_ids.json delete mode 100644 MySQL/list_ids.py diff --git a/MySQL/list_ids.json b/MySQL/list_ids.json new file mode 100644 index 0000000..54f4b77 --- /dev/null +++ b/MySQL/list_ids.json @@ -0,0 +1,33 @@ +{ + "ban_list_ids": { + "6666666666666": "Забанненый" + }, + "important_adm_ids": { + "6751720805": "Лейн", + "7051557370": "Рикси", + "1570652377": "Риша", + "1398573474": "Финаки", + "1851081467": "Финик", + "929782381": "Хиде", + "6714237814": "Слешик" + }, + "important_groups_ids": { + "1087968824": "GroupAnonymousBot", + "-1002247934490": "Сплетни_лавочек", + "-1002124483077": "Труба_Сквад", + "-1002123850090": "Тест_Чат", + "-1001552311087": "Все_Будет_Хорошо" + }, + "important_users_list_ids": { + "7145369362": "Артур", + "1219440132": "Данил", + "1443833264": "Виктор", + "5424384921": "Олег", + "556943853": "Ваня", + "1295708467": "Степан" + }, + "important_channel_ids": { + "10000000000000": "Канал1", + "20000000000000": "Канал2" + } +} diff --git a/MySQL/list_ids.py b/MySQL/list_ids.py deleted file mode 100644 index dc52b96..0000000 --- a/MySQL/list_ids.py +++ /dev/null @@ -1,47 +0,0 @@ -# MySQL/list_ids.py -# Хранилище забанненых и важных пользователей и чатов - -# Айди забанненых пользователей -ban_list_ids = { - 6666666666666: "Лох", # @username_ban1 - # 6751720805: "Лейн", # @verdise -} - - -# Айди администраторов бота -important_adm_ids = { - 6751720805: "Лейн", # @verdise - 7051557370: "Рикси", # @exetreon - 1570652377: "Риша", # @ariinwx - 1398573474: "Финаки", # @fin_aki - 1851081467: "Финик", # @Huuuvs - 929782381: "Хиде", # @tghjudy - 6714237814: "Слешик", # @Slashichan -} - - -# Айди групп-администраторов -important_groups_ids = { - 1087968824: "GroupAnonymousBot", - -1002247934490: "Сплетни_лавочек", - -1002124483077: "Труба_Сквад", - -1002123850090: "Тест_Чат", - -1001552311087: "Все_Будет_Хорошо", -} - - -# Айди важных пользователей бота -important_users_list_ids = { - 7145369362: "Артур", # @i_toksichen - 1219440132: "Данил", # @ohwtfuck - 1443833264: "Виктор", # @B500OP98 - 5424384921: "Олег", # @s1s2s3sf - 556943853: "Ваня", # @skodaracing24 - 1295708467: "Степан", # @No_step_toback -} - - -# Айди важных каналов -important_channel_ids = { - # 7145369362: "Артур", # @i_toksichen -} -- 2.49.1 From 0cabaf56e655d49dc87d3b1fb5005e3ecbf61979 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:06:29 +0700 Subject: [PATCH 25/35] =?UTF-8?q?=D0=91=D0=BE=D0=BB=D0=B5=D0=B5=20=D0=B0?= =?UTF-8?q?=D0=B2=D1=82=D0=BE=D0=BD=D0=BE=D0=BC=D0=BD=D0=B0=D1=8F=20=D1=83?= =?UTF-8?q?=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BA=D0=B0=20=D1=81=D0=BF?= =?UTF-8?q?=D0=B8=D1=81=D0=BA=D0=B0=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/routers/commands/bot_command.py | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/BotCode/routers/commands/bot_command.py b/BotCode/routers/commands/bot_command.py index f7ed53f..d01909b 100644 --- a/BotCode/routers/commands/bot_command.py +++ b/BotCode/routers/commands/bot_command.py @@ -6,10 +6,10 @@ from aiogram import Router, types, F from aiogram.filters import Command from BotLibrary import * -from .user_cmd.start_cmd import log_type as start_cmd_text -from .user_cmd.help_cmd import log_type as help_cmd_text -from .user_cmd.exit_cmd import log_type as exit_cmd_text -from .user_cmd.start_time_cmd import log_type as start_time_cmd_text +from .user_cmd.start_cmd import description as start_description, log_type as start_cmd +from .user_cmd.help_cmd import description as help_description, log_type as help_cmd +from .user_cmd.exit_cmd import description as exit_description, log_type as exit_cmd +from .user_cmd.start_time_cmd import description as start_time_description,log_type as start_time_cmd # Создание роутера и настройка экспорта модулей @@ -23,16 +23,15 @@ secret_keywords = ["setcommands", "setcommand", "ыуесщььфтвы", "ыу # Хэндлер на команду /setcommands для использования в чате -@router.message(F.from_user.id.in_(ListId.important_ids), - Command(*secret_keywords, prefix=BotEdit.prefixs, ignore_case=True)) +@router.message(F.from_user.id.func(lambda user_id: str(user_id) in DataID.important.keys()), + Command(*secret_keywords, prefix=BotVariables.prefixs, ignore_case=True)) +@router.message(F.from_user.id.func(lambda user_id: str(user_id) in DataID.important.keys()), + F.text.lower().in_(secret_keywords)) async def set_commands(): bot_commands = [ - types.BotCommand(command=start_cmd_text.lower(), description="Запустить бота"), - types.BotCommand(command=help_cmd_text.lower(), description="Получить помощь"), - types.BotCommand(command=help_cmd_text.lower(), description="Получить помощь"), - types.BotCommand(command=start_time_cmd_text.lower(), description="Время запуска"), - types.BotCommand(command=exit_cmd_text.lower(), description="Выйти из чата (в разработке)"), - types.BotCommand(command="command", description="Пустая команда"), + types.BotCommand(command=start_cmd.lower(), description=start_description), + types.BotCommand(command=help_cmd.lower(), description=help_description), + types.BotCommand(command=start_time_cmd.lower(), description=start_time_description), + types.BotCommand(command=exit_cmd.lower(), description=exit_description), ] await bot.set_my_commands(bot_commands) - return bot_commands -- 2.49.1 From 2e75264af95a8f38d8a42a7da730076071cb1853 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:06:49 +0700 Subject: [PATCH 26/35] =?UTF-8?q?=D0=90=D0=B2=D1=82=D0=BE=D0=BD=D0=BE?= =?UTF-8?q?=D0=BC=D0=BD=D0=B0=D1=8F=20=D1=81=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B4=D0=B8=D1=80=D0=B5=D0=BA=D1=82=D0=BE=D1=80?= =?UTF-8?q?=D0=B8=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/library/directory.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/BotLibrary/library/directory.py b/BotLibrary/library/directory.py index 6ba006c..4a592e7 100644 --- a/BotLibrary/library/directory.py +++ b/BotLibrary/library/directory.py @@ -2,7 +2,7 @@ # Небольшая библиотека для создания директорий import os -from config import ImportantPath, BotVariables +from BotLibrary.configs import ProjectPath, TypeDirectory # Настройка экспорта модулей и логирования __all__ = ("create_directories", "setup_directories", ) @@ -22,8 +22,7 @@ def create_directories(base_directory, subdirectories): # Начальная установка пустых директорий def setup_directories(): - create_directories(ImportantPath.bot_personal_media, BotVariables.bot_media_directories) - create_directories(ImportantPath.bot_received_media, BotVariables.bot_media_directories) - create_directories(ImportantPath.msg, BotVariables.bot_msg_directories) - create_directories(ImportantPath.bot_files, BotVariables.bot_avatar_directories) - return f"Пустые директории - успешно созданы!" + create_directories(ProjectPath.personal_media, TypeDirectory.media_directories) + create_directories(ProjectPath.received_media, TypeDirectory.media_directories) + create_directories(ProjectPath.bot_files, TypeDirectory.avatar_directories) + create_directories(ProjectPath.msg, TypeDirectory.msg_directories) -- 2.49.1 From dc6c70cf77940bf6e6a807c09be7c08c394e7776 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:07:12 +0700 Subject: [PATCH 27/35] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D0=B5=20=D0=B7=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D1=87=D0=B8=D0=BA=D0=B0=20=D0=B0=D0=B2=D0=B0=D1=82=D0=B0=D1=80?= =?UTF-8?q?=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../routers/downloads/download_avatar_all.py | 8 +-- .../routers/downloads/download_chat_avatar.py | 67 +++++++++---------- .../routers/downloads/download_handlers.py | 14 ++-- .../routers/downloads/download_user_avatar.py | 16 ++--- 4 files changed, 50 insertions(+), 55 deletions(-) diff --git a/BotCode/routers/downloads/download_avatar_all.py b/BotCode/routers/downloads/download_avatar_all.py index 08389ce..65a23d9 100644 --- a/BotCode/routers/downloads/download_avatar_all.py +++ b/BotCode/routers/downloads/download_avatar_all.py @@ -1,15 +1,15 @@ # BotCode/routers/downloads/download_avatar_all.py # Объединение закачки аватаров всех типов - +from BotLibrary import write_user_info_to_file from .download_chat_avatar import download_chat_avatar from .download_user_avatar import download_user_photos # Настройка экспорта модулей -__all__ = ("download_avatar",) +__all__ = ("download_avatar", "download_chat_avatar", "download_user_photos") # Функция объединения закачки аватарок async def download_avatar(message): - await download_chat_avatar(message, message.chat) + await download_chat_avatar(message) await download_user_photos(message) - return f"Успешная закачка аватаров!" + write_user_info_to_file(message.from_user) diff --git a/BotCode/routers/downloads/download_chat_avatar.py b/BotCode/routers/downloads/download_chat_avatar.py index 9dd8fee..7f57f06 100644 --- a/BotCode/routers/downloads/download_chat_avatar.py +++ b/BotCode/routers/downloads/download_chat_avatar.py @@ -1,32 +1,29 @@ +# BotCode/routers/downloads/download_chat_avatar.py +# Функция скачивания аватара чата + import os -import requests -from aiogram import Router -from aiogram.types import Chat +import aiohttp from BotLibrary import * # Создание роутера и настройка экспорта модулей -__all__ = ("router", "download_chat_avatar",) -router = Router(name="avatar_chat_router") +__all__ = ("download_chat_avatar",) log_type = "AvatarChat" # Функция закачки аватарок чатов -async def download_chat_avatar(message, chat: Chat): +async def download_chat_avatar(message): try: + chat = message.chat # Проверка типа чата (группа или супергруппа) if chat.type in ["group", "supergroup"]: - # Получаем информацию о чате (включая фото) chat_info = await bot.get_chat(chat.id) - chat_id = chat.id - - # Проверка наличия аватара + # Проверка на наличие фотографий чата if not chat_info.photo: - text_error = f"Чат с ID {chat_id} не имеет аватара." - logger.bind(log_type=log_type, user=chat_id).error(text_error) + text_error = f"Чат с ID {chat.id} не имеет аватара." + logger.bind(log_type=log_type, user=chat.id).error(text_error) return text_error - # Получаем file_id для фото (высокое качество приоритетно) file_id = ( getattr(chat_info.photo, 'big_file_id', None) or getattr(chat_info.photo, 'medium_file_id', None) or @@ -34,39 +31,41 @@ async def download_chat_avatar(message, chat: Chat): ) if not file_id: - text_error = f"Не удалось получить file_id аватара чата с ID {chat_id}." - logger.bind(log_type=log_type, user=chat_id).error(text_error) + text_error = f"Не удалось получить file_id аватара чата с ID {chat.id}." + logger.bind(log_type=log_type, user=chat.id).error(text_error) return text_error - # Получаем file_info для фото file_info = await bot.get_file(file_id) - - # Строим URL для скачивания файла file_url = f"https://api.telegram.org/file/bot{bot.token}/{file_info.file_path}" - # Формируем путь для сохранения фото - chat_id = find_chat_id(message) - save_dir = f"{ImportantPath.chat_avatar}/{chat_id}" + chat_id = find_imp_id(chat.id) + save_dir = f"{ProjectPath.chat_avatar}/{chat_id}" os.makedirs(save_dir, exist_ok=True) file_extension = os.path.splitext(file_info.file_path)[-1] file_name = f"avatar{file_extension}" save_path = os.path.join(save_dir, file_name) - # Скачиваем аватар - response = requests.get(file_url, stream=True) - if response.status_code == 200: - with open(save_path, "wb") as file: - for chunk in response.iter_content(chunk_size=8192): - file.write(chunk) - return f"Фото аватара чата с ID {chat_id} успешно скачано." - - else: - text_error = f"Не удалось скачать фото аватара чата с ID {chat_id}. Статус: {response.status_code}" - logger.bind(log_type=log_type, user=chat_id).error(text_error) - return text_error + # Асинхронное скачивание + async with aiohttp.ClientSession() as session: + async with session.get(file_url) as response: + if response.status == 200: + with open(save_path, "wb") as file: + while True: + chunk = await response.content.read(8192) + if not chunk: + break + file.write(chunk) + return f"Фото аватара чата с ID {chat_id} успешно скачано." + else: + text_error = f"Не удалось скачать фото аватара чата с ID {chat_id}. Статус: {response.status}" + logger.bind(log_type=log_type, user=chat.id).error(text_error) + return text_error + else: + return except Exception as e: + chat = message.chat text_error = f"Ошибка при скачивании фото аватара чата с ID {chat.id}: {e}" - logger.bind(log_type=log_type, user=chat.id).exception(text_error) + logger.bind(log_type=log_type, user=chat.id).error(text_error) return text_error diff --git a/BotCode/routers/downloads/download_handlers.py b/BotCode/routers/downloads/download_handlers.py index a322fc5..9da6052 100644 --- a/BotCode/routers/downloads/download_handlers.py +++ b/BotCode/routers/downloads/download_handlers.py @@ -19,7 +19,7 @@ log_type = "Media" async def handle_media(message: types.Message): try: await download_avatar(message) - name = find_chat_id(message) + name = find_imp_id(message.from_user.id) await logginger(message) file_id = None @@ -28,8 +28,8 @@ async def handle_media(message: types.Message): media = message.video if message.content_type == types.ContentType.VIDEO else message.animation file_extension = media.mime_type.split('/')[-1] # Получаем расширение файла (например, "mp4" или "gif") file_name = f"{media.file_id}.{file_extension}" # Используем file_id и расширение для имени - save_dir = ImportantPath.video_directory if message.content_type == types.ContentType.VIDEO \ - else ImportantPath.gif_directory + save_dir = ProjectPath.received_video if message.content_type == types.ContentType.VIDEO \ + else ProjectPath.received_gif elif message.content_type == types.ContentType.PHOTO: media = message.photo @@ -38,22 +38,22 @@ async def handle_media(message: types.Message): file_info = await bot.get_file(file_id) # Имя файла будет взято из file_path, который содержит оригинальное имя файла file_name = file_info.file_path.split('/')[-1] # Используем имя файла из пути - save_dir = ImportantPath.photo_directory + save_dir = ProjectPath.received_photo elif message.content_type == types.ContentType.VOICE: media = message.voice file_name = f"{media.file_id}.ogg" # Для голосовых сообщений используем file_id и расширение .ogg - save_dir = ImportantPath.voice_directory + save_dir = ProjectPath.received_voice elif message.content_type == types.ContentType.VIDEO_NOTE: media = message.video_note file_name = f"{media.file_id}.mp4" # Для видеосообщений используем file_id и расширение .mp4 - save_dir = ImportantPath.videonote_directory + save_dir = ProjectPath.received_videonote elif message.content_type == types.ContentType.DOCUMENT: media = message.document file_name = media.file_name # Для видеосообщений используем file_id и расширение .mp4 - save_dir = ImportantPath.document_directory + save_dir = ProjectPath.received_document else: (logger.bind(log_type=log_type, user=message.from_user.username) diff --git a/BotCode/routers/downloads/download_user_avatar.py b/BotCode/routers/downloads/download_user_avatar.py index 29022c3..3e3dd77 100644 --- a/BotCode/routers/downloads/download_user_avatar.py +++ b/BotCode/routers/downloads/download_user_avatar.py @@ -2,35 +2,31 @@ # Закачка всех аватаров пользователей import os -from aiogram import Router, types +from aiogram import types from aiogram.types import UserProfilePhotos from BotLibrary import * # Создание роутера и настройка экспорта модулей -__all__ = ("router", "download_user_photos",) -router = Router(name="avatar_router") +__all__ = ("download_user_photos",) log_type = "AvatarUser" # Функция закачки аватарок пользователя async def download_user_photos(message: types.Message): try: - # Получение ID пользователя - user_id = message.from_user.id + # Проверка на наличие в списке "важных" пользователей + user_id = find_imp_id(message.from_user.id) # Получение аватарок пользователя - user_profile_photos: UserProfilePhotos = await bot.get_user_profile_photos(user_id) - - # Проверка на наличие в списке "важных" пользователей - user_id = find_people_id(user_id) + user_profile_photos: UserProfilePhotos = await bot.get_user_profile_photos(message.from_user.id) # Проверка наличия фотографий if user_profile_photos.total_count == 0: return f"У пользователя {user_id} нет аватарок." # Объявление пути и создание директории - user_directory = f'{ImportantPath.user_avatar}/{user_id}' + user_directory = f'{ProjectPath.user_avatar}/{user_id}' os.makedirs(user_directory, exist_ok=True) # Закачка аватарок пользователя -- 2.49.1 From d62203c693d8dda345585837d7696dadc087707a Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:07:53 +0700 Subject: [PATCH 28/35] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=B2=D0=B5=D0=B1=D1=83=D0=BA=D0=B0=20=D0=B8=20?= =?UTF-8?q?=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D0=BB=D0=BE=D0=B3=D0=B3=D0=B5=D1=80=D0=BE=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/main.py b/main.py index 3521a85..b516897 100644 --- a/main.py +++ b/main.py @@ -9,6 +9,9 @@ from BotCode.routers import set_commands # Запуск основного кода async def main(): + # Создание логгера + await setup_logger() + # Подключение ANSI в стандартное Windows_cmd just_fix_windows_console() @@ -22,12 +25,12 @@ async def main(): await set_commands() # Установка команд бота await bot_get_info() # Получение информации о боте - # Создание логгера и оповещение о запуске - await setup_logger() + # Оповещение о запуске с информацией бота logger.bind(log_type="AEP", user="Console").info(f"Начало запуска бота @{BotInfo.username}...") bot_info_out() # Включение опроса бота + await bot.delete_webhook() await dp.start_polling(bot) -- 2.49.1 From cad15e0d3a4a4a53639d800c5d61dd6b24baf7a4 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:08:05 +0700 Subject: [PATCH 29/35] =?UTF-8?q?=D0=A0=D0=B0=D0=B7=D0=BB=D0=B8=D1=87?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5=20=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D0=B8?= =?UTF-8?q?=20=D1=81=20=D0=BC=D0=B5=D0=B4=D0=B8=D0=B0=20(=D1=81=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D1=8B=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Test/old_files/media_func.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Test/old_files/media_func.py b/Test/old_files/media_func.py index 65973ca..ac76469 100644 --- a/Test/old_files/media_func.py +++ b/Test/old_files/media_func.py @@ -12,7 +12,7 @@ router = Router(name="media_func") # @router.message(F.photo, ~F.caption) -async def handle_photo_wo_caption(message: types.Message): +async def handle_photo_wo_caption(message: types_msg.Message): caption = f"Простите, я не могу это увидеть. Вы можете описать что это?" await message.reply_photo( photo=message.photo[-1].file_id, @@ -22,14 +22,14 @@ async def handle_photo_wo_caption(message: types.Message): # @router.message(F.photo, F.caption.contains("please")) -async def handle_photo_with_please_caption(message: types.Message): +async def handle_photo_with_please_caption(message: types_msg.Message): text = f"Простите, я не могу это увидеть." await message.reply(text) return text # @router.message(any_media_filter, ~F.caption) -async def handle_any_media_wo_caption(message: types.Message): +async def handle_any_media_wo_caption(message: types_msg.Message): if message.document: await message.reply_document( document=message.document.file_id, @@ -49,7 +49,7 @@ async def handle_any_media_wo_caption(message: types.Message): # @router.message(any_media_filter, F.caption) -async def handle_any_media_w_caption(message: types.Message): +async def handle_any_media_w_caption(message: types_msg.Message): text = f"Что-то на медиа. Твой текст: {message.caption!r}" await message.reply(text) return text -- 2.49.1 From 4e63871c61995fd696720278658602f16aefd33b Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:08:23 +0700 Subject: [PATCH 30/35] =?UTF-8?q?=D0=A3=D0=BB=D1=83=D1=87=D1=88=D0=B5?= =?UTF-8?q?=D0=BD=D0=B8=D0=B5=20=D0=BB=D0=BE=D0=B3=D0=B3=D0=B5=D1=80=D0=BE?= =?UTF-8?q?=D0=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/library/logger.py | 52 ++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/BotLibrary/library/logger.py b/BotLibrary/library/logger.py index e69a2a7..c5da90f 100644 --- a/BotLibrary/library/logger.py +++ b/BotLibrary/library/logger.py @@ -3,21 +3,56 @@ import sys from loguru import logger -from config import ImportantPath, LogsSet -from ..analitics.message_to_file import write_message_to_file -from ..analitics.user_data_to_file import write_user_info_to_file + +from BotLibrary.configs import ProjectPath +from BotLibrary.analitics.message_to_file import write_message_to_file +from BotLibrary.analitics.user_data_to_file import write_user_info_to_file # Настройка экспорта модулей и логирования __all__ = ("logger", "setup_logger", "cmd_logginger", "error_cmd_logginger", "logginger", "common_msg_logginger", ) +# Класс для параметров логгера +class LogsSet: + # Максимальный размер лог-файла + max_size = "500 MB" + + # Шаблон логов для информации + info_text = ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "PRIMO-{extra[log_type]} | " + "{extra[user]} | {message}" + ) + + # Шаблон логов для ошибок + error_text = ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "ERROR-{extra[log_type]} | " + "{extra[user]} | {message}" + ) + + # Шаблон логов для отладки + debug_text = ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "DEBUG-{extra[log_type]} | " + "{extra[user]} | {message}" + ) + + # Шаблон логов для предупреждений + warning_text = ( + "{time:YYYY-MM-DD HH:mm:ss} | " + "WARNING-{extra[log_type]} | " + "{extra[user]} | {message}" + ) + + # Создание обычного логгера + логгер в файл async def setup_logger(): logger.remove() # Удаляем все логгеры # Пустой логгер для записи отступов в файл уровня TRACE - logger.add(ImportantPath.log_file, + logger.add(ProjectPath.log_file, rotation=LogsSet.max_size, format="\n\n\n", backtrace=True, @@ -32,7 +67,7 @@ async def setup_logger(): format=LogsSet.info_text, level="INFO", filter=lambda record: record["level"].name == "INFO") - logger.add(ImportantPath.log_file, + logger.add(ProjectPath.log_file, rotation=LogsSet.max_size, format=LogsSet.info_text, backtrace=True, @@ -46,21 +81,19 @@ async def setup_logger(): format=LogsSet.error_text, level="ERROR", filter=lambda record: record["level"].name == "ERROR") - logger.add(ImportantPath.log_error_file, + logger.add(ProjectPath.log_error_file, rotation=LogsSet.max_size, format=LogsSet.error_text, backtrace=True, diagnose=True, level="ERROR", filter=lambda record: record["level"].name == "ERROR") - return f"Логгеры - подключены!" # Запись сообщения в файл и информации о пользователи async def logginger(message): write_user_info_to_file(message.from_user) await write_message_to_file(message) - return f"Сообщение и информация о пользователи - успешно записаны!" # Создание функции логирования на обычные сообщения @@ -72,14 +105,12 @@ async def common_msg_logginger(message, name, message_type, log_type): else: logger.bind(log_type=log_type, user=f"@{message.from_user.username}").info( f"Получено сообщение из ({name}) : {message.text}") - return f"Логгер на обычный сообщения - успешно активирован" # Специальный логгер для команд. Вывод в консоль, файл и запись информации о пользователи async def cmd_logginger(message, log_type, text): await logginger(message) logger.bind(log_type=log_type, user=f"@{message.from_user.username}").info(text) - return f"Логгер на команду - успешно активирован" # Специальный логгер для ошибок с командами. Вывод в консоль, файл и запись информации о пользователи @@ -87,4 +118,3 @@ async def error_cmd_logginger(message, log_type, e): text_error = f"Ошибка при использовании команды /{log_type.lower()}: {str(e)}\n" await logginger(message) logger.bind(log_type=log_type, user=f"@{message.from_user.username}").error(text_error) - return text_error -- 2.49.1 From 7dd30d0d9561ca0f33055b824722fcadd5a628fc Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:08:35 +0700 Subject: [PATCH 31/35] =?UTF-8?q?=D0=9F=D0=BE=D0=B8=D1=81=D0=BA=20=D0=B0?= =?UTF-8?q?=D0=B9=D0=B4=D0=B8=20=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D1=82=D0=B5=D0=BB=D0=B5=D0=B9=20=D1=83=D0=BB=D1=83=D1=87?= =?UTF-8?q?=D1=88=D0=B5=D0=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/analitics/find_ids.py | 43 +++++++++++++------------------- 1 file changed, 18 insertions(+), 25 deletions(-) diff --git a/BotLibrary/analitics/find_ids.py b/BotLibrary/analitics/find_ids.py index c51397a..ecf868a 100644 --- a/BotLibrary/analitics/find_ids.py +++ b/BotLibrary/analitics/find_ids.py @@ -1,42 +1,35 @@ # BotLibrary/analitics/find_ids.py # Проверка пользователя на нахождение в списках бота -from aiogram import types -from config import ListId +from ..configs.list_ids import DataID # Настройка экспорта модулей и логирования -__all__ = ("find_people_id", "find_chat_id", "find_adm_id", "find_ban_id") +__all__ = ("find_imp_id", "find_adm_id", "find_ban_id") log_type = "ID" # Функция поиска человека в списке администраторов -def find_adm_id(message): - if message.from_user.id in ListId.adm_list_id: +def find_adm_id(admin_id): + admin_id = str(admin_id) + if admin_id in DataID.admins: return True else: - return f"Пользователь не является администратором!" + return f"Пользователь {admin_id} не является администратором!" -# Функция поиска человека в списке администраторов -def find_ban_id(message): - if message.from_user.id in ListId.ban_list_id: +# Функция поиска человека в списке забаненных пользователей +def find_ban_id(ban_id): + ban_id = str(ban_id) + if ban_id in DataID.ban_list: return True else: - return f"Пользователь не забанен!" + return f"Пользователь {ban_id} не забанен!" -# Функция поиска человека в списке "важных" пользователей -def find_people_id(user_id): - # Проверка на наличие пользователя в списке "важных" пользователей - if user_id in ListId.important_ids: - user_id = ListId.important_ids[user_id] - return user_id - - -# Проверка на наличие чата в списке "важных" чатов -def find_chat_id(message: types.Message): - chat_id = message.chat.id - # Проверка на наличие чата в списке "важных" чатов - if chat_id in ListId.important_ids: - chat_id = ListId.important_ids[chat_id] - return chat_id +# Функция поиска человека в списке "важных" чатов +def find_imp_id(user_id): + user_id = str(user_id) + if user_id in DataID.important: + return DataID.important[user_id] # Возвращаем имя пользователя + else: + return user_id -- 2.49.1 From 1b6c9725f58700eb321c0e055297074738cb8c99 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:09:16 +0700 Subject: [PATCH 32/35] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=D1=8B=20=D0=B1=D0=B0=D0=B3=D0=B8=20=D1=81=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D1=8C=D1=8E=20=D0=B2=20=D1=84?= =?UTF-8?q?=D0=B0=D0=B9=D0=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/analitics/message_to_file.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/BotLibrary/analitics/message_to_file.py b/BotLibrary/analitics/message_to_file.py index 4b3a516..a9110bc 100644 --- a/BotLibrary/analitics/message_to_file.py +++ b/BotLibrary/analitics/message_to_file.py @@ -5,9 +5,10 @@ import os from loguru import logger from datetime import datetime -from config import BotVariables -from .type_messages import * -from .find_ids import find_chat_id +from ..configs import * +from ..library.time import TimeVariable +from .types_msg import types_message, types_chat +from .find_ids import find_imp_id # Настройка экспорта модулей и логирования __all__ = ("write_message_to_file",) @@ -19,12 +20,12 @@ async def write_message_to_file(message): try: # Создание переменных с информацией message_type = types_message(message) - chat_id = find_chat_id(message) + chat_id = find_imp_id(message.from_user.id) file_path = types_chat(message) # Переменные для логов сообщений - date = datetime.now().strftime(BotVariables.time_format) - username = message.from_user.username if message.from_user.username else "No username" + date = datetime.now().strftime(TimeVariable.format) + username = message.from_user.username if message.from_user.username else "Нет @username" log_shablon = f"{date} | @{username} ({message.from_user.id}) |" # Проверка и создание директорий @@ -32,17 +33,14 @@ async def write_message_to_file(message): os.makedirs(os.path.dirname(file_path)) # Запись информации в файл - with open(file_path, "a", encoding=BotVariables.encoding) as file: + with open(file_path, "a", encoding=default_encod) as file: # Проверка на наличие текста if message.text is None: file.write(f"{log_shablon} Тип: {message_type}\n\n") else: file.write(f"{log_shablon} ChatID: {chat_id} | Текст: {message.text}\n\n") - return f"Сообщение пользователя успешно записано в файл." - # Проверка на ошибку и ее логирование except Exception as e: text_error = f"Ошибка в сохранении сообщения в файл: {str(e)}" logger.bind(custom_variable=log_type, user_var=f"@{message.from_user.username}").error(text_error) - return text_error -- 2.49.1 From f0560571dc901ea1302a3bb642b8b4467cd7768f Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:11:03 +0700 Subject: [PATCH 33/35] =?UTF-8?q?=D0=98=D0=BD=D0=BB=D0=B0=D0=B9=D0=BD-?= =?UTF-8?q?=D0=BF=D0=BE=D1=81=D1=82=D1=8B=20(=D0=B2=20=D1=80=D0=B0=D0=B7?= =?UTF-8?q?=D1=80=D0=B0=D0=B1=D0=BE=D1=82=D0=BA=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotCode/inline/posts_inline.py | 1 - 1 file changed, 1 deletion(-) diff --git a/BotCode/inline/posts_inline.py b/BotCode/inline/posts_inline.py index 006459a..2c4a0ff 100644 --- a/BotCode/inline/posts_inline.py +++ b/BotCode/inline/posts_inline.py @@ -1,7 +1,6 @@ # BotCode/routers/inline/posts_inline.py # Создание красивых постов по вкусу (в разработке) -import hashlib import uuid from aiogram import Router, types -- 2.49.1 From 46e975aa907086ef1eebb208d2a006249186b5b1 Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:11:36 +0700 Subject: [PATCH 34/35] =?UTF-8?q?=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE=D0=B2=D1=89?= =?UTF-8?q?=D0=B8=D0=BA=D0=B0=20=D0=B0=D0=B2=D0=B0=D1=82=D0=B0=D1=80=D0=BE?= =?UTF-8?q?=D0=BA=20=D0=B8=20=D0=B8=D0=BD=D1=84=D0=BE=D1=80=D0=BC=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20=D0=B2=20=D0=B1=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../administration/easteggs_handlers.py | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/BotCode/routers/administration/easteggs_handlers.py b/BotCode/routers/administration/easteggs_handlers.py index 80226ac..88df1a8 100644 --- a/BotCode/routers/administration/easteggs_handlers.py +++ b/BotCode/routers/administration/easteggs_handlers.py @@ -1,14 +1,13 @@ # BotCode/routers/administration/easteggs_handlers.py -# Функции с шуточными пасхалками (разобраться с логированием и ошибками) +# Небольшие шуточные пасхалки from aiogram import Router, types, F from aiogram.enums import ChatAction from BotLibrary import * - +from routers.msg_default import msg_default # Создание роутера и настройка экспорта -__all__ = ("router", "secret_admin_message_finaki", "secret_admin_message_lostik", - "secret_admin_message_rishkus", "secret_admin_message_finik", "secret_admin_message_skodavano",) +__all__ = ("router",) router = Router(name="easteggs_router") log_type = "EastEggs" @@ -27,7 +26,7 @@ async def secret_admin_message_finaki(message: types.Message): # Отправка фотографии try: await message.reply_photo( - photo=types.FSInputFile(path=f"{ImportantPath.bot_personal_media}/{ImportantPath.photo}/Undertale.jpg"), + photo=types.FSInputFile(path=f"{ProjectPath.personal_media}/{ProjectPath.personal_photo}/Undertale.jpg"), caption="ОНА МЕНЯ ЗАСТАВИЛА ПОМОГИТЕ😭... (Кст @fin_aki любит анал, тс..)", ) @@ -38,11 +37,12 @@ async def secret_admin_message_finaki(message: types.Message): # Дополнительное логирование await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст финикх -@router.message(F.from_user.id.in_(ListId.important_ids), F.text.lower() == "финикх") +@router.message(F.from_user.id.func(lambda user_id: str(user_id) in DataID.important.keys()), + F.text.lower() == "финикх") async def secret_admin_message_finik(message: types.Message): text = f"Пасхалка 2 финикx найдена!" await message.bot.send_chat_action( @@ -53,7 +53,7 @@ async def secret_admin_message_finik(message: types.Message): photo="https://vos-mo.ru/upload/iblock/329/g0s939ge8o1n8xp7rcqnw9kkz9mcfrg2/risunok.jpg", caption="Привет, это польза Фиников!") await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст андертейлкино @@ -68,7 +68,7 @@ async def secret_admin_message_finik(message: types.Message): photo="https://i.ytimg.com/vi/c-o4_p4YKIc/mqdefault.jpg", caption="Меня заставила Финаки, честно!") await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст ришкус + отправка с локального хранилища @@ -80,11 +80,11 @@ async def secret_admin_message_rishkus(message: types.Message): action=ChatAction.UPLOAD_PHOTO, ) await message.reply_photo( - photo=types.FSInputFile(path=f"{ImportantPath.bot_personal_media}/{ImportantPath.photo}/Кусь.jpg"), + photo=types.FSInputFile(path=f"{ProjectPath.personal_media}/{ProjectPath.personal_photo}/Кусь.jpg"), caption="Россия для грустных", ) await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст skodavano + отправка с локального хранилища @@ -96,11 +96,11 @@ async def secret_admin_message_skodavano(message: types.Message): action=ChatAction.UPLOAD_PHOTO, ) await message.reply_photo( - photo=types.FSInputFile(path=f"{ImportantPath.bot_personal_media}/{ImportantPath.photo}/Vano.jpg"), + photo=types.FSInputFile(path=f"{ProjectPath.personal_media}/{ProjectPath.personal_photo}/Vano.jpg"), caption="SkodaRacingVano24 -> Синяя изолента", ) await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст лостикслешик + отправка с локального хранилища @@ -117,12 +117,13 @@ async def secret_admin_message_lostik(message: types.Message): # Вывод сообщения-гифки пользователю await message.reply_animation( - animation=types.FSInputFile(path=f"{ImportantPath.bot_personal_media}/{ImportantPath.gif}/ЛжеРайяПрайм.mp4") + animation=types.FSInputFile(path=f"{ProjectPath.personal_media}" + f"/{ProjectPath.personal_gif}/ЛжеРайяПрайм.mp4") ) # Активация логгера await cmd_logginger(message, types_message, text) - return text + await msg_default(message) # Проверка на ошибку и ее логирование except Exception as e: @@ -159,7 +160,7 @@ async def secret_admin_message_finaki(message: types.Message): # Дополнительное логирование await cmd_logginger(message, log_type, text) - return text + await msg_default(message) # Хэндлер на текст маз @@ -189,5 +190,4 @@ async def secret_admin_message_finaki(message: types.Message): # Дополнительное логирование await cmd_logginger(message, log_type, text) - return text - + await msg_default(message) -- 2.49.1 From 7dec6de067a625338d4e321e4b1848b728e9643b Mon Sep 17 00:00:00 2001 From: Whyverum Date: Mon, 23 Dec 2024 22:11:53 +0700 Subject: [PATCH 35/35] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2?= =?UTF-8?q?=D0=BB=D0=B5=D0=BD=20=D0=B1=D0=B0=D0=B3=20=D1=81=20=D0=B8=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- BotLibrary/library/edit_bot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BotLibrary/library/edit_bot.py b/BotLibrary/library/edit_bot.py index 69415df..646ee4c 100644 --- a/BotLibrary/library/edit_bot.py +++ b/BotLibrary/library/edit_bot.py @@ -4,7 +4,7 @@ from aiogram.types import ChatAdministratorRights from loguru import logger -from config import BotEdit +from BotLibrary.configs import BotEdit from BotLibrary.library.bots import bot # Настройка экспорта модулей и логирования @@ -107,4 +107,4 @@ async def set_bot_short_description(): await bot.set_my_short_description(short_description=BotEdit.short_description) return f"Короткое описание бота изменено!" else: - return f"Короткое описание бота уже установлено и не требует изменений." + return f"Короткое описание бота уже установлено и не требует изменений." \ No newline at end of file -- 2.49.1