diff --git a/docker-compose-debug.yaml b/docker-compose-debug.yaml index 609d98a..fcbd801 100644 --- a/docker-compose-debug.yaml +++ b/docker-compose-debug.yaml @@ -7,7 +7,7 @@ services: - POSTGRES_PASSWORD=test_passwd - POSTGRES_DB=olgram ports: - - '5430:5432' + - '5400:5432' volumes: - database:/var/lib/postgresql/data redis: diff --git a/extendedinstance/bot.py b/extendedinstance/bot.py index 1c1de0f..6d8607a 100644 --- a/extendedinstance/bot.py +++ b/extendedinstance/bot.py @@ -21,18 +21,6 @@ class BotInstanceDatabase(BotInstance): # Polling только для отладки asyncio.get_event_loop().create_task(cls._instances[bot.id].start_polling()) - @classmethod - async def on_delete(cls, instance: Bot): - # Polling только для отладки - cls._instances[instance.id].stop_polling() - cls._instances.pop(instance.id) - - @classmethod - async def on_create(cls, instance: Bot): - # Polling только для отладки - cls._instances[instance.id] = BotInstanceDatabase(instance) - asyncio.get_event_loop().create_task(cls._instances[instance.id].start_polling()) - @aiocache.cached(ttl=5) async def _properties(self) -> BotProperties: await self._bot.refresh_from_db() diff --git a/instance/bot.py b/instance/bot.py index 7c36b74..1b514f5 100644 --- a/instance/bot.py +++ b/instance/bot.py @@ -30,6 +30,7 @@ class BotInstance(ABC): raise NotImplemented() def stop_polling(self): + print("stop polling") self._dp.stop_polling() async def _setup(self): @@ -52,6 +53,7 @@ class BotInstance(ABC): types.ContentType.VOICE]) async def start_polling(self): + print("start polling") await self._setup() await self._dp.start_polling() diff --git a/main.py b/main.py index d2918c3..c017a53 100644 --- a/main.py +++ b/main.py @@ -1,35 +1,12 @@ import asyncio - -from aiogram import Bot as AioBot, Dispatcher -from aiogram.contrib.fsm_storage.memory import MemoryStorage -from tortoise.signals import post_delete, post_save from tortoise import Tortoise -from olgram.settings import BotSettings, TORTOISE_ORM +from olgram.router import dp +from olgram.settings import TORTOISE_ORM -from olgram.commands.bots import router as bots_router -from olgram.commands.start import router as start_router -from olgram.commands.bot import router as bot_router - -from olgram.models.models import Bot -from extendedinstance.bot import BotInstanceDatabase - - -@post_save(Bot) -async def signal_post_save( - sender, - instance: Bot, - created: bool, - using_db, - update_fields, -) -> None: - if created: - await BotInstanceDatabase.on_create(instance) - - -@post_delete(Bot) -async def signal_post_delete(sender, instance: Bot, using_db) -> None: - await BotInstanceDatabase.on_delete(instance) +import olgram.commands.bot +import olgram.commands.bots +import olgram.commands.start async def init_database(): @@ -43,14 +20,6 @@ def main(): loop = asyncio.get_event_loop() loop.run_until_complete(init_database()) - bot = AioBot(BotSettings.token()) - dp = Dispatcher(bot, storage=MemoryStorage()) - - start_router.setup(dp) - bots_router.setup(dp) - bot_router.setup(dp) - - loop.run_until_complete(BotInstanceDatabase.run_all()) loop.create_task(dp.start_polling()) loop.run_forever() diff --git a/olgram/commands/bot.py b/olgram/commands/bot.py index 196a1bd..e0e8a4a 100644 --- a/olgram/commands/bot.py +++ b/olgram/commands/bot.py @@ -6,11 +6,10 @@ from aiogram.dispatcher import FSMContext from aiogram.utils.callback_data import CallbackData from textwrap import dedent -from olgram.utils.router import Router from olgram.utils.mix import try_delete_message from olgram.models.models import Bot, User -router = Router() +from olgram.router import dp # Пользователь выбрал бота select_bot = CallbackData('bot_select', 'bot_id') @@ -37,7 +36,7 @@ def check_bot_owner(handler): return wrapped -@router.callback_query_handler(select_bot.filter(), state="*") +@dp.callback_query_handler(select_bot.filter(), state="*") @check_bot_owner async def select_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ @@ -62,7 +61,7 @@ async def select_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data """), reply_markup=keyboard) -@router.callback_query_handler(bot_operation.filter(operation="delete"), state="*") +@dp.callback_query_handler(bot_operation.filter(operation="delete"), state="*") @check_bot_owner async def delete_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ @@ -73,7 +72,7 @@ async def delete_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data await try_delete_message(call.message) -@router.callback_query_handler(bot_operation.filter(operation="chat"), state="*") +@dp.callback_query_handler(bot_operation.filter(operation="chat"), state="*") @check_bot_owner async def chats_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ @@ -102,7 +101,7 @@ async def chats_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data: """), reply_markup=keyboard) -@router.callback_query_handler(select_bot_chat.filter(), state="*") +@dp.callback_query_handler(select_bot_chat.filter(), state="*") @check_bot_owner async def chat_selected_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ @@ -118,7 +117,7 @@ async def chat_selected_callback(bot: Bot, call: types.CallbackQuery, callback_d await call.answer(f"Выбран чат {chat.name}") -@router.callback_query_handler(select_bot_chat_personal.filter(), state="*") +@dp.callback_query_handler(select_bot_chat_personal.filter(), state="*") @check_bot_owner async def chat_selected_personal_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ @@ -129,7 +128,7 @@ async def chat_selected_personal_callback(bot: Bot, call: types.CallbackQuery, c await call.answer(f"Выбран личный чат") -@router.callback_query_handler(bot_operation.filter(operation="text"), state="*") +@dp.callback_query_handler(bot_operation.filter(operation="text"), state="*") @check_bot_owner async def text_bot_callback(bot: Bot, call: types.CallbackQuery, callback_data: dict, state: FSMContext): """ diff --git a/olgram/commands/bots.py b/olgram/commands/bots.py index 88a1200..67d1fa2 100644 --- a/olgram/commands/bots.py +++ b/olgram/commands/bots.py @@ -8,16 +8,16 @@ from tortoise.exceptions import IntegrityError import re from textwrap import dedent -from ..utils.router import Router from .bot import select_bot from olgram.models.models import Bot, User from olgram.settings import OlgramSettings -router = Router() +from olgram.router import dp + token_pattern = r'[0-9]{8,10}:[a-zA-Z0-9_-]{35}' -@router.message_handler(commands=["mybots"], state="*") +@dp.message_handler(commands=["mybots"], state="*") async def my_bots(message: types.Message, state: FSMContext): """ Команда /mybots (список ботов) @@ -39,7 +39,7 @@ async def my_bots(message: types.Message, state: FSMContext): await message.answer("Ваши боты", reply_markup=keyboard) -@router.message_handler(commands=["addbot"], state="*") +@dp.message_handler(commands=["addbot"], state="*") async def add_bot(message: types.Message, state: FSMContext): """ Команда /addbot (добавить бота) @@ -63,7 +63,7 @@ async def add_bot(message: types.Message, state: FSMContext): await state.set_state("add_bot") -@router.message_handler(state="add_bot", content_types="text", regexp="^[^/].+") # Not command +@dp.message_handler(state="add_bot", content_types="text", regexp="^[^/].+") # Not command async def bot_added(message: types.Message, state: FSMContext): """ Пользователь добавляет бота и мы ждём от него токен diff --git a/olgram/commands/start.py b/olgram/commands/start.py index 1ac8348..a821787 100644 --- a/olgram/commands/start.py +++ b/olgram/commands/start.py @@ -5,12 +5,11 @@ from aiogram import types from aiogram.dispatcher import FSMContext from textwrap import dedent -from ..utils.router import Router -router = Router() +from olgram.router import dp -@router.message_handler(commands=["start"], state="*") +@dp.message_handler(commands=["start"], state="*") async def start(message: types.Message, state: FSMContext): """ Команда /start @@ -33,7 +32,7 @@ async def start(message: types.Message, state: FSMContext): """)) -@router.message_handler(commands=["help"], state="*") +@dp.message_handler(commands=["help"], state="*") async def help(message: types.Message, state: FSMContext): """ Команда /help diff --git a/olgram/router.py b/olgram/router.py new file mode 100644 index 0000000..ff9a101 --- /dev/null +++ b/olgram/router.py @@ -0,0 +1,7 @@ +from aiogram import Dispatcher, Bot +from aiogram.contrib.fsm_storage.memory import MemoryStorage +from .settings import BotSettings + + +bot = Bot(BotSettings.token()) +dp = Dispatcher(bot, storage=MemoryStorage()) diff --git a/olgram/utils/router.py b/olgram/utils/router.py deleted file mode 100644 index fd62b47..0000000 --- a/olgram/utils/router.py +++ /dev/null @@ -1,79 +0,0 @@ -from dataclasses import dataclass -from typing import Any, Dict, List, Tuple - -from aiogram.dispatcher import Dispatcher - - -@dataclass() -class Handler: - callback: Any - custom_filters: Tuple[Any] - kwargs: Dict[Any, Any] - commands: Any = None - regexp: Any = None - content_types: Any = None - state: Any = None - run_task: Any = None - - -class Router: - def __init__(self): - self._message_handlers: List[Handler] = [] - self._inline_handlers: List[Handler] = [] - self._callback_handlers: List[Handler] = [] - - def message_handler( - self, *custom_filters, commands=None, regexp=None, content_types=None, state=None, run_task=None, **kwargs - ): - def decorator(callback): - self._message_handlers.append( - Handler(callback, custom_filters, kwargs, commands, regexp, content_types, state, run_task) - ) - return callback - - return decorator - - def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs): - def decorator(callback): - self._inline_handlers.append(Handler(callback, custom_filters, kwargs, state=state, run_task=run_task)) - return callback - - return decorator - - def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs): - def decorator(callback): - self._callback_handlers.append(Handler(callback, custom_filters, kwargs, state=state, run_task=run_task)) - return callback - - return decorator - - def setup(self, dp: Dispatcher): - for handler in self._message_handlers: - dp.register_message_handler( - handler.callback, - *handler.custom_filters, - commands=handler.commands, - regexp=handler.regexp, - content_types=handler.content_types, - state=handler.state, - run_task=handler.run_task, - **handler.kwargs - ) - - for handler in self._inline_handlers: - dp.register_inline_handler( - handler.callback, - *handler.custom_filters, - state=handler.state, - run_task=handler.run_task, - **handler.kwargs - ) - - for handler in self._callback_handlers: - dp.register_callback_query_handler( - handler.callback, - *handler.custom_filters, - state=handler.state, - run_task=handler.run_task, - **handler.kwargs - )