0.9. переделаны шаблоны, теперь есть возможность отправлять несколько медиа в команде.. надеюсь

This commit is contained in:
Verum
2025-02-25 08:44:06 +07:00
parent 05e6bb5c96
commit 47896a0597
7 changed files with 189 additions and 133 deletions

2
.idea/PRIMOWORLD.iml generated
View File

@@ -16,9 +16,9 @@
<sourceFolder url="file://$MODULE_DIR$/BotCode" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/BotCode" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/BotLibrary/samples" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/BotLibrary/samples" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/Test" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/Test" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/Test/GUI" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/Test/commands" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/Test/commands" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/Test/old_files" isTestSource="true" /> <sourceFolder url="file://$MODULE_DIR$/Test/old_files" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/GUI" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/.venv" /> <excludeFolder url="file://$MODULE_DIR$/.venv" />
</content> </content>
<orderEntry type="jdk" jdkName="Python 3.13 (PRIMOWORLD)" jdkType="Python SDK" /> <orderEntry type="jdk" jdkName="Python 3.13 (PRIMOWORLD)" jdkType="Python SDK" />

View File

@@ -3,21 +3,17 @@
from BotLibrary import CommandHandler from BotLibrary import CommandHandler
from BotCode.keyboards import get_start_kb from BotCode.keyboards import get_start_kb
user = "2"
# Создание команды /start # Создание команды /start с несколькими медиа
start_cmd = CommandHandler( start_cmd = CommandHandler(
name="start", name="start",
description="Добро пожаловать!", description="Добро пожаловать!",
keywords=["start", "старт", "запуск", "пуск", "on", "вкл", "с", "s", "ы", keywords=["start"],
"ыефке", "cnfhn", "pfgecr", "gecr", "щт", "drk", "restart", "куыефке"],
callbackdata="keywords",
keyboard=get_start_kb, keyboard=get_start_kb,
media="photo", media="photo",
path_to_media="ProjectsFiles/media/Banners/start_banner.jpg", path_to_media=[
tg_links=True, "ProjectsFiles/media/Banners/start_banner.jpg",
text_msg=f""" ],
Здравствуй, <b><a href="tg://user?id==<users>">дорогой Путник</a></b>. tg_links=False,
Мое имя - <i>Эми</i>! Я - ваш <i>путеводитель</i> в этом прекрасном месте! text_msg="Привет! Вот группа фото!",
Вы <b>готовы</b> отправиться в этот дивный мир?
""",
) )

View File

@@ -4,6 +4,7 @@
from aiogram import Router, types, F from aiogram import Router, types, F
from aiogram.enums import ChatAction from aiogram.enums import ChatAction
from aiogram.filters import Command from aiogram.filters import Command
from aiogram.types import InputMediaPhoto
from BotLibrary import valid_url from BotLibrary import valid_url
from ProjectsFiles import BotVar from ProjectsFiles import BotVar
@@ -13,16 +14,16 @@ from BotLibrary.loggers import Logs
# Настройки экспорта в модули # Настройки экспорта в модули
__all__ = ("CommandHandler",) __all__ = ("CommandHandler",)
# Класс-шаблон для команд # Класс-шаблон для команд
class CommandHandler: class CommandHandler:
def __init__(self, text_msg, name: str, keywords : list, chat_action : bool = False, def __init__(self, text_msg, name: str, keywords: list, chat_action: bool = False,
description: str = "Описание команды", tg_links : bool = False, description: str = "Описание команды", tg_links: bool = False,
keyboard = None, prefix = BotVar.prefix, callbackdata = None, keyboard=None, prefix=BotVar.prefix, callbackdata=None,
ignore_case : bool = True, activate_keywoards : bool = True, ignore_case: bool = True, activate_keywoards: bool = True,
activate_commands : bool = True, activate_callback : bool = True, activate_commands: bool = True, activate_callback: bool = True,
media : str = "message", path_to_media : str = None, parse_mode : str = BotVar.parse_mode, media: str = "message", path_to_media=None, parse_mode: str = BotVar.parse_mode,
disable_notification : bool = False, disable_notification: bool = False):
):
self.router = Router(name=f"{name}_router") self.router = Router(name=f"{name}_router")
self.name = name self.name = name
@@ -37,14 +38,20 @@ class CommandHandler:
self.disable_notification = disable_notification self.disable_notification = disable_notification
self.media = media.lower() self.media = media.lower()
self.path_to_media = path_to_media # Поддержка до 10 медиафайлов через список
if path_to_media is None:
self.path_to_media = []
elif isinstance(path_to_media, (str, types.FSInputFile)):
self.path_to_media = [path_to_media]
elif isinstance(path_to_media, list):
self.path_to_media = path_to_media[:10] # Ограничение до 10 элементов
self.tg_links = tg_links self.tg_links = tg_links
if callbackdata == "keywords": if callbackdata == "keywords":
self.callbackdata = keywords self.callbackdata = keywords
else: else:
self.callbackdata = callbackdata self.callbackdata = callbackdata
# Привязываем хэндлер к роутеру # Привязываем хэндлер к роутеру
if activate_commands: if activate_commands:
self.router.message(Command(*keywords, prefix=prefix, ignore_case=ignore_case))(self.handler) self.router.message(Command(*keywords, prefix=prefix, ignore_case=ignore_case))(self.handler)
@@ -53,15 +60,14 @@ class CommandHandler:
if activate_callback: if activate_callback:
self.router.message(F.text.lower().in_(callbackdata))(self.handler) self.router.message(F.text.lower().in_(callbackdata))(self.handler)
async def handler(self, message: types.Message): async def handler(self, message: types.Message):
"""Основной хэндлер команды.""" """Основной хэндлер команды."""
try: try:
url : bool = valid_url(self.path_to_media)
if self.tg_links: if self.tg_links:
self.text_msg = self.text_msg.replace("<users>", str(message.from_user.id)) self.text_msg = self.text_msg.replace("<users>", str(message.from_user.id))
Logs.info(log_type=self.log_type, user=username(message), text=f"использовал(а) команду /{self.name}") Logs.info(log_type=self.log_type, user=username(message), text=f"использовал(а) команду /{self.name}")
if self.media == "message": if self.media == "message":
await message.reply( await message.reply(
text=self.text_msg, text=self.text_msg,
@@ -75,121 +81,179 @@ class CommandHandler:
action=ChatAction.TYPING, action=ChatAction.TYPING,
) )
else: else:
if self.media == "photo": if self.media == "photo" and len(self.path_to_media) > 1:
if url: # Отправка медиагруппы для фотографий
await message.reply_photo(photo=self.path_to_media, media_group = []
caption=self.text_msg, for media_path in self.path_to_media:
reply_markup=self.keyboard() if self.keyboard else None, url = valid_url(media_path)
parse_mode=self.parse_mode, if url:
disable_notification=self.disable_notification) media_group.append(InputMediaPhoto(media=media_path))
else: else:
await message.reply_photo(photo=types.FSInputFile(path=self.path_to_media), media_group.append(InputMediaPhoto(media=types.FSInputFile(path=media_path)))
caption=self.text_msg,
reply_markup=self.keyboard() if self.keyboard else None,
parse_mode=self.parse_mode,
disable_notification=self.disable_notification)
# Добавляем подпись и клавиатуру к последнему элементу
media_group[-1].caption = self.text_msg
media_group[-1].parse_mode = self.parse_mode
await message.reply_media_group(
media=media_group,
disable_notification=self.disable_notification
)
# Отправка клавиатуры отдельным сообщением, если есть
if self.keyboard:
await message.reply(
text=" ",
reply_markup=self.keyboard(),
disable_notification=self.disable_notification
)
if self.chat_action: if self.chat_action:
await message.bot.send_chat_action( await message.bot.send_chat_action(
chat_id=message.chat.id, chat_id=message.chat.id,
action=ChatAction.UPLOAD_PHOTO, action=ChatAction.UPLOAD_PHOTO,
) )
else:
# Одиночное медиа или другие типы
for idx, media_path in enumerate(self.path_to_media):
is_last = idx == len(self.path_to_media) - 1
url = valid_url(media_path)
elif self.media == "gif": if self.media == "photo":
if url: if url:
await message.reply_animation(animation=self.path_to_media, await message.reply_photo(
caption=self.text_msg, photo=media_path,
reply_markup=self.keyboard() if self.keyboard else None, caption=self.text_msg if is_last else None,
parse_mode=self.parse_mode, reply_markup=self.keyboard() if is_last and self.keyboard else None,
disable_notification=self.disable_notification) parse_mode=self.parse_mode,
else: disable_notification=self.disable_notification
await message.reply_animation(animation=types.FSInputFile(path=self.path_to_media), )
caption=self.text_msg, else:
reply_markup=self.keyboard() if self.keyboard else None, await message.reply_photo(
parse_mode=self.parse_mode, photo=types.FSInputFile(path=media_path),
disable_notification=self.disable_notification) caption=self.text_msg if is_last else None,
if self.chat_action: reply_markup=self.keyboard() if is_last and self.keyboard else None,
await message.bot.send_chat_action( parse_mode=self.parse_mode,
chat_id=message.chat.id, disable_notification=self.disable_notification
action=ChatAction.UPLOAD_VIDEO, )
) if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_PHOTO,
)
elif self.media == "gif":
if url:
await message.reply_animation(
animation=media_path,
caption=self.text_msg if is_last else None,
reply_markup=self.keyboard() if is_last and self.keyboard else None,
parse_mode=self.parse_mode,
disable_notification=self.disable_notification
)
else:
await message.reply_animation(
animation=types.FSInputFile(path=media_path),
caption=self.text_msg if is_last else None,
reply_markup=self.keyboard() if is_last and self.keyboard else None,
parse_mode=self.parse_mode,
disable_notification=self.disable_notification
)
if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_VIDEO,
)
elif self.media == "video": elif self.media == "video":
if url: if url:
await message.reply_video(video=self.path_to_media, await message.reply_video(
caption=self.text_msg, video=media_path,
reply_markup=self.keyboard() if self.keyboard else None, caption=self.text_msg if is_last else None,
parse_mode=self.parse_mode, reply_markup=self.keyboard() if is_last and self.keyboard else None,
disable_notification=self.disable_notification) parse_mode=self.parse_mode,
else: disable_notification=self.disable_notification
await message.reply_video(video=types.FSInputFile(path=self.path_to_media), )
caption=self.text_msg, else:
reply_markup=self.keyboard() if self.keyboard else None, await message.reply_video(
parse_mode=self.parse_mode, video=types.FSInputFile(path=media_path),
disable_notification=self.disable_notification) caption=self.text_msg if is_last else None,
if self.chat_action: reply_markup=self.keyboard() if is_last and self.keyboard else None,
await message.bot.send_chat_action( parse_mode=self.parse_mode,
chat_id=message.chat.id, disable_notification=self.disable_notification
action=ChatAction.UPLOAD_VIDEO, )
) if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_VIDEO,
)
elif self.media == "videonote": elif self.media == "videonote":
if url: if url:
await message.reply_video_note(video_note=self.path_to_media, await message.reply_video_note(
caption=self.text_msg, video_note=media_path,
reply_markup=self.keyboard() if self.keyboard else None, caption=self.text_msg if is_last else None,
parse_mode=self.parse_mode, reply_markup=self.keyboard() if is_last and self.keyboard else None,
disable_notification=self.disable_notification) parse_mode=self.parse_mode,
else: disable_notification=self.disable_notification
await message.reply_video_note(video_note=types.FSInputFile(path=self.path_to_media), )
caption=self.text_msg, else:
reply_markup=self.keyboard() if self.keyboard else None, await message.reply_video_note(
parse_mode=self.parse_mode, video_note=types.FSInputFile(path=media_path),
disable_notification=self.disable_notification) caption=self.text_msg if is_last else None,
if self.chat_action: reply_markup=self.keyboard() if is_last and self.keyboard else None,
await message.bot.send_chat_action( parse_mode=self.parse_mode,
chat_id=message.chat.id, disable_notification=self.disable_notification
action=ChatAction.UPLOAD_VIDEO_NOTE, )
) if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_VIDEO_NOTE,
)
elif self.media == "audio": elif self.media == "audio":
if url: if url:
await message.reply_audio(audio=self.path_to_media, await message.reply_audio(
caption=self.text_msg, audio=media_path,
reply_markup=self.keyboard() if self.keyboard else None, caption=self.text_msg if is_last else None,
parse_mode=self.parse_mode, reply_markup=self.keyboard() if is_last and self.keyboard else None,
disable_notification=self.disable_notification) parse_mode=self.parse_mode,
else: disable_notification=self.disable_notification
await message.reply_audio(audio=types.FSInputFile(path=self.path_to_media), )
caption=self.text_msg, else:
reply_markup=self.keyboard() if self.keyboard else None, await message.reply_audio(
parse_mode=self.parse_mode, audio=types.FSInputFile(path=media_path),
disable_notification=self.disable_notification) caption=self.text_msg if is_last else None,
if self.chat_action: reply_markup=self.keyboard() if is_last and self.keyboard else None,
await message.bot.send_chat_action( parse_mode=self.parse_mode,
chat_id=message.chat.id, disable_notification=self.disable_notification
action=ChatAction.UPLOAD_VOICE, )
) if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_VOICE,
)
elif self.media == "file": elif self.media == "file":
if url: if url:
await message.reply_document(document=self.path_to_media, await message.reply_document(
caption=self.text_msg, document=media_path,
reply_markup=self.keyboard() if self.keyboard else None, caption=self.text_msg if is_last else None,
parse_mode=self.parse_mode, reply_markup=self.keyboard() if is_last and self.keyboard else None,
disable_notification=self.disable_notification) parse_mode=self.parse_mode,
else: disable_notification=self.disable_notification
await message.reply_document(document=types.FSInputFile(path=self.path_to_media), )
caption=self.text_msg, else:
reply_markup=self.keyboard() if self.keyboard else None, await message.reply_document(
parse_mode=self.parse_mode, document=types.FSInputFile(path=media_path),
disable_notification=self.disable_notification) caption=self.text_msg if is_last else None,
if self.chat_action: reply_markup=self.keyboard() if is_last and self.keyboard else None,
await message.bot.send_chat_action( parse_mode=self.parse_mode,
chat_id=message.chat.id, disable_notification=self.disable_notification
action=ChatAction.UPLOAD_DOCUMENT, )
) if self.chat_action and is_last:
await message.bot.send_chat_action(
chat_id=message.chat.id,
action=ChatAction.UPLOAD_DOCUMENT,
)
# Проверка на ошибку # Проверка на ошибку
except Exception as e: except Exception as e:

View File

@@ -3,10 +3,6 @@
# Импортируем библиотеки для экспорта # Импортируем библиотеки для экспорта
from aiogram import Router from aiogram import Router
from .commands import *
from .GUI import *
from .old_files import *
# Создание роутера "test_router" # Создание роутера "test_router"
router = Router(name="test_router") router = Router(name="test_router")