# buttons.py
import uuid
from typing import Callable, Optional, Union, Dict, List, Awaitable
import asyncio
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from DarkBot.darkData import DarkData
# Тип для функций-обработчиков
CallbackFunction = Callable[['DarkData'], Awaitable[None]]
class Button:
# Реестр для хранения функций-обработчиков
callback_registry: Dict[str, CallbackFunction] = {}
expiring_tasks: Dict[str, asyncio.Task] = {}
TTL = 300 # Время жизни записи в секундах (например, 5 минут)
def __init__(
self,
text: str,
callback_data: Optional[str] = None,
callback_func: Optional[CallbackFunction] = None
):
self.text = text
if callback_data and callback_func:
raise ValueError("Нельзя передавать одновременно callback_data и callback_func.")
self.callback_data = callback_data
self.callback_func = callback_func
if self.callback_func:
# Генерируем уникальный callback_data
unique_id = str(uuid.uuid4())
self.callback_data = unique_id
# Регистрация функции в реестре
Button.callback_registry[unique_id] = self.callback_func
# Запуск задачи удаления записи через TTL
Button.expiring_tasks[unique_id] = asyncio.create_task(self._remove_after_ttl(unique_id))
async def _remove_after_ttl(self, unique_id: str):
await asyncio.sleep(Button.TTL)
Button.callback_registry.pop(unique_id, None)
Button.expiring_tasks.pop(unique_id, None)
def to_aiogram_button(self) -> InlineKeyboardButton:
return InlineKeyboardButton(text=self.text, callback_data=self.callback_data)
class DButton(Button):
"""
Класс DButton наследуется от Button и предоставляет дополнительные возможности.
"""
def __init__(
self,
text: str,
callback_data: Optional[str] = None,
callback_func: Optional[CallbackFunction] = None
):
super().__init__(text, callback_data, callback_func)
class DKeyboard:
"""
Класс DKeyboard для удобного создания клавиатур из списков кнопок.
"""
def __init__(self, button_rows: List[List[Union[str, DButton]]]):
"""
:param button_rows: Список списков, где внутренние списки представляют строки кнопок.
Элементы могут быть строками (для стандартных callback_data) или экземплярами DButton.
"""
self.button_rows = button_rows
self.inline_keyboard = self._generate_keyboard()
def _generate_keyboard(self) -> InlineKeyboardMarkup:
keyboard = InlineKeyboardMarkup(inline_keyboard=[])
for row_data in self.button_rows:
row = []
for button in row_data:
if isinstance(button, DButton):
aiogram_button = button.to_aiogram_button()
elif isinstance(button, str):
# Создаем стандартную кнопку с callback_data равным имени
aiogram_button = InlineKeyboardButton(text=button.capitalize().replace("_", " "), callback_data=button)
else:
raise TypeError("Элементы ряда кнопок должны быть строками или экземплярами DButton.")
row.append(aiogram_button)
if row: # Не добавляем пустые строки
keyboard.inline_keyboard.append(row)
return keyboard
def to_aiogram_markup(self) -> InlineKeyboardMarkup:
return self.inline_keyboard
darkbot.py
py
# darkbot.py
import asyncio
import logging
import sys
from typing import Union, List, Callable, Dict, Awaitable
import aiogram
from aiogram import Bot, Dispatcher, types
from aiogram.client.default import DefaultBotProperties
from aiogram.enums import ParseMode
from aiogram.filters import Command, BaseFilter
from aiogram.types import Message, CallbackQuery
from DarkBot.darkData import DarkData
from DarkBot.filters import DarkCommand, DarkFilter, WaitingForFilter
from .buttons import Button, CallbackFunction
class DarkBot:
def __init__(self, token: str):
self.bot = Bot(
token=token,
default=DefaultBotProperties(parse_mode=ParseMode.HTML)
)
self.aiogram_dispatcher = Dispatcher()
# Регистрация универсального обработчика callback
self.aiogram_dispatcher.callback_query.register(self.handle_callback_query)
# Ваши собственные декораторы
def message(self, filter: Union[DarkFilter, BaseFilter]):
def decorator(func):
if isinstance(filter, DarkFilter):
aiogram_filter = filter.get_inst()
elif isinstance(filter, BaseFilter):
aiogram_filter = filter
else:
raise TypeError("Invalid filter type. Must be DarkFilter or aiogram.filters.BaseFilter.")
@self.aiogram_dispatcher.message(aiogram_filter)
async def wrapper(message: types.Message):
return await func(DarkData(message))
return wrapper
return decorator
def waiting_for(self, state_description: str, expected_types: List[str]):
def decorator(func):
filter = WaitingForFilter(state_description, expected_types)
@self.aiogram_dispatcher.message(filter)
async def wrapper(message: types.Message):
dark_data = DarkData(message)
# Очистка ожидаемого состояния после получения сообщения
await dark_data.user.clear_waiting_for()
return await func(dark_data)
return wrapper
return decorator
async def handle_callback_query(self, callback: CallbackQuery):
callback_data = callback.data
if callback_data in Button.callback_registry:
handler_func = Button.callback_registry.pop(callback_data)
# Отмена задачи удаления, если она ещё не выполнена
task = Button.expiring_tasks.pop(callback_data, None)
if task:
task.cancel()
# Создаем DarkData для передачи в функцию
dark_data = DarkData(callback.message)
try:
await handler_func(dark_data)
await callback.answer() # Отвечаем на callback, чтобы убрать "крутящуюся" иконку
except Exception as e:
logging.exception("Exception in callback handler:")
await callback.answer("Произошла ошибка при обработке команды.", show_alert=True)
else:
# Обработка стандартных callback_data
await self.handle_standard_callback(callback)
async def handle_standard_callback(self, callback: CallbackQuery):
# Здесь можно определить обработчики для стандартных callback_data
# Например, используя match-case или if-elif конструкции
match callback.data:
case "cancel":
await callback.answer("Действие отменено.", show_alert=True)
case _:
await callback.answer("Неизвестная команда.", show_alert=True)
def start(self, is_logging=False):
"""
Starts the bot with asyncio
:param logging:
:return:
"""
async def main() -> None:
await self.aiogram_dispatcher.start_polling(self.bot)
if is_logging:
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
asyncio.run(main())
darkData.py
py
# darkData.py
from typing import TYPE_CHECKING
from aiogram.types import Message
from DarkBot.db import DarkDB
if TYPE_CHECKING:
from aiogram import Bot
class DarkUser:
def __init__(self, aiogram_user):
self.id = aiogram_user.id
self.data = {}
self.db = DarkDB()
self._initialized = False
async def init(self):
if not self._initialized:
self.data = await self.db.get_user_data(self.id)
self._initialized = True
async def set_val(self, key, value):
await self.init()
self.data[key] = value
await self.db.set_user_data(self.id, self.data)
async def get_val(self, key, default=None):
await self.init()
print(f"self.data = {self.data}")
return self.data.get(key, default)
async def set_state(self, state: str):
await self.set_val('_state', state)
async def get_state(self):
return await self.get_val('_state', None)
# Метод для установки ожидаемого состояния
async def set_waiting_for(self, state_description: str, expected_type: str):
await self.set_val('_waiting_for', {'state': state_description, 'type': expected_type})
# Метод для получения ожидаемого состояния
async def get_waiting_for(self):
return await self.get_val('_waiting_for', None)
# Метод для очистки ожидаемого состояния
async def clear_waiting_for(self):
await self.set_val('_waiting_for', None)
class DarkData:
def __init__(self, message: Message):
self.message: Message = message
self.user = DarkUser(message.from_user)
db.py
py
# db.py
import aiosqlite
import json
import asyncio
class DarkDB:
def __init__(self, db_path="darkbot.db"):
self.db_path = db_path
self._init_lock = asyncio.Lock()
self._initialized = False
async def init_db(self):
async with self._init_lock:
if not self._initialized:
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
darkdata TEXT
)
''')
await db.commit()
self._initialized = True
async def get_user_data(self, user_id: int) -> dict:
await self.init_db()
async with aiosqlite.connect(self.db_path) as db:
async with db.execute('SELECT darkdata FROM users WHERE id = ?', (user_id,)) as cursor:
row = await cursor.fetchone()
if row:
return json.loads(row[0])
else:
return {}
async def set_user_data(self, user_id: int, data: dict):
await self.init_db()
darkdata_json = json.dumps(data)
async with aiosqlite.connect(self.db_path) as db:
await db.execute('''
INSERT INTO users (id, darkdata) VALUES (?, ?)
ON CONFLICT(id) DO UPDATE SET darkdata = excluded.darkdata
''', (user_id, darkdata_json))
await db.commit()
filters.py
py
from typing import Optional, List
from aiogram.filters import BaseFilter, Command
from aiogram.types import Message
from DarkBot.darkData import DarkUser
class DarkFilter:
def get_inst(self) -> BaseFilter:
raise NotImplementedError("You must implement get_inst() for your specific logic")
class DarkCommand(DarkFilter):
def __init__(
self,
commands: List[str], # Используем List[str] для type hinting
prefix: str = "/"
):
self.commands = commands
self.prefix = prefix
def get_inst(self) -> Command: # Указываем возвращаемый тип Command
return Command(commands=self.commands, prefix=self.prefix)
class WaitingForFilter(BaseFilter):
def __init__(self, state_description: str, expected_types: List[str]):
self.state_description = state_description
self.expected_types = expected_types
async def __call__(self, message: Message) -> bool:
user = DarkUser(message.from_user)
waiting_for = await user.get_waiting_for()
if waiting_for:
if waiting_for['state'] == self.state_description:
# Проверяем тип сообщения
for expected_type in self.expected_types:
if expected_type == 'text' and message.text:
return True
elif expected_type == 'voice' and message.voice:
return True
elif expected_type == 'document' and message.document:
return True
elif expected_type == 'video' and message.video:
return True
# Добавьте проверки для других типов по необходимости
return False
Главный файл использования бота:
main.py
from aiogram.filters import Command
from DarkBot import darkbot, darkData
from DarkBot import filters
from DarkBot.buttons import DButton, DKeyboard
from DarkBot.darkData import DarkData
from DarkBot.filters import DarkCommand
BOT_TOKEN = "7511323083:AAHWtUE_iwFn4u3j0fWMAsQPOrtxWz7mF9g"
DarkBot = darkbot.DarkBot(token=BOT_TOKEN)
@DarkBot.message(DarkCommand(["start"]))
async def start(data) -> None:
async def on_press_ok_button(dark_data: DarkData):
await dark_data.message.answer(f"Вы нажали OK")
ok_button = DButton(
text="OK",
callback_func=on_press_ok_button
)
cancel_button = DButton(
text="Отменить",
callback_data="cancel"
)
# Определяем конструкцию клавиатуры
button_rows = [
[ok_button, cancel_button]
]
# Создаем клавиатуру
keyboard = DKeyboard(button_rows)
await data.message.answer("Нажми кнопку OK или Отменить:", reply_markup=keyboard.to_aiogram_markup())
if __name__ == "__main__":
DarkBot.start(is_logging=True)
Это мой фреймворк для удобного создания ботов в телеграмм.
Я хочу модифицировать кнопк, добавить к ним функционал новый а именно - магические кнопки (MagicButton).
Пока будет только одна, но планирую еще добавить:
Будет кнопка MagicButton, она будет принимать: обязательный аргумент(тип: magicbutton.back), необязательный(текст кнопки).
Текст кнопки необязателен, т.к. для каждого типа magicbutton будет свой текст по умолчанию
так, у magicbutton.back будет текст по умолчанию - "Назад".
Как ты можешь заметить, в моем фреймворке есть возможность создавать функции в функциях и передавать в кнопки сами фукнции.
Я хочу сделать крутой фукнционал, чтобы если мы добавили в клавиатуру magicbutton.back, то при ее нажатии, она будет вовзращать предыдущее сообщение бота с предыдущими кнопками(как бы вернуться назад). Если сообщение было просто изменено, но мы также его изменяем обратно. Важно, чтобы это работало также, если в прошлом сообщении было изобрадение и файл, а в текущем нет.
Подумай как это модно сделать
To add the MagicButton functionality that allows users to go back to the previous message with its buttons, you'll need to implement the following features in your code:
Create a MagicButton Class: This class will represent magic buttons like "Back". It should accept a mandatory magic_type (e.g., 'back') and an optional text. If text is not provided, it uses a default text based on magic_type.
Store Message History: You need to keep track of the messages sent to the user so that when the "Back" button is pressed, you can retrieve and resend the previous message. This can be done by maintaining a history stack within the DarkUser class.
Modify Message Sending Methods: Adjust your DarkData class to include methods like send_message that not only send messages but also store them in the user's history. This ensures that every message sent can be retrieved later.
Handle the MagicButton Callback: In your DarkBot class, update the handle_standard_callback method to handle the magic button's callback. When the "Back" button is pressed, retrieve the previous message from the history and resend it.
Here’s how you can implement these features step by step:
1. Create the MagicButton Class
In your buttons.py, add the MagicButton class:
python
# buttons.py
class MagicButton(DButton):
def __init__(
self,
magic_type: str,
text: Optional[str] = None
):
default_texts = {
'back': 'Назад',
# Add default texts for other magic types here if needed
}
if magic_type not in default_texts:
raise ValueError(f"Unknown magic button type: {magic_type}")
if text is None:
text = default_texts[magic_type]
self.magic_type = magic_type
self.callback_data = f"magic_{magic_type}"
# No need to pass callback_func since it will be handled separately
super().__init__(text=text, callback_data=self.callback_data)
def to_aiogram_button(self) -> InlineKeyboardButton:
return InlineKeyboardButton(text=self.text, callback_data=self.callback_data)
2. Store Message History in DarkUser
In your darkData.py, modify the DarkUser class to include a history stack:
python
# darkData.py
class DarkUser:
def __init__(self, aiogram_user):
self.id = aiogram_user.id
self.data = {}
self.db = DarkDB()
self._initialized = False
self.history = []
async def init(self):
if not self._initialized:
self.data = await self.db.get_user_data(self.id)
self.history = self.data.get('history', [])
self._initialized = True
async def save_history(self):
self.data['history'] = self.history
await self.db.set_user_data(self.id, self.data)
async def push_history(self, content):
await self.init()
self.history.append(content)
# Limit the history size to prevent unbounded growth
MAX_HISTORY_SIZE = 10
if len(self.history) > MAX_HISTORY_SIZE:
self.history.pop(0)
await self.save_history()
async def pop_history(self):
await self.init()
if self.history:
# Remove the current entry
self.history.pop()
if self.history:
previous_content = self.history.pop()
await self.save_history()
return previous_content
return None
# ... rest of the class ...
3. Modify DarkData to Handle Message Sending and History
In darkData.py, add a send_message method to the DarkData class:
python
# darkData.py
class DarkData:
def __init__(self, message: Message, bot):
self.message: Message = message
self.user = DarkUser(message.from_user)
self.bot = bot
async def send_message(self, **kwargs):
"""
Send a message and store it in the user's history.
"""
chat_id = self.message.chat.id
if 'text' in kwargs:
sent_message = await self.bot.send_message(
chat_id=chat_id,
text=kwargs['text'],
reply_markup=kwargs.get('reply_markup')
)
elif 'photo' in kwargs:
sent_message = await self.bot.send_photo(
chat_id=chat_id,
photo=kwargs['photo'],
caption=kwargs.get('caption'),
reply_markup=kwargs.get('reply_markup')
)
else:
raise ValueError("Unsupported message type.")
# Store the message content in history
content = {
'message_id': sent_message.message_id,
'text': kwargs.get('text'),
'photo': kwargs.get('photo'),
'caption': kwargs.get('caption'),
'keyboard': kwargs.get('reply_markup')
# Include other fields as needed
}
await self.user.push_history(content)
4. Update Message Handlers to Use send_message
In your main.py and any other place where you send messages, use data.send_message instead of directly sending messages:
Ensure that everywhere in your code where you send messages, you're using the send_message method of DarkData to keep the history consistent.
Final Notes:
Limiting History Size: To prevent unbounded growth of the history, you can limit the size of the history stack (e.g., keep only the last 10 messages).
Handling Different Message Types: The provided code handles text and photo messages. If you need to handle more types (like documents, videos, etc.), you'll need to add additional conditions in the send_message and handle_magic_back methods.
User Experience: When the "Back" button is pressed, the previous message is either edited or resent. This mimics the behavior of going back to the previous state.
Further Enhancements: You can add more magic button types (e.g., 'next', 'home') by extending the default_texts dictionary in the MagicButton class and handling them in the handle_standard_callback method.
By following these steps, you can enhance your framework with the MagicButton functionality, allowing users to navigate back to previous messages seamlessly, even if those messages included images or files.