diff --git a/src/gnomik/gnomik/__main__.py b/src/gnomik/gnomik/__main__.py index 71c4ab9..fd60b62 100644 --- a/src/gnomik/gnomik/__main__.py +++ b/src/gnomik/gnomik/__main__.py @@ -9,6 +9,7 @@ async def main(): await ocab.init_app( [ block_loader("standard", "config", safe=False), + block_loader("standard", "filters", safe=False), block_loader("standard", "database", safe=False), block_loader("standard", "statistics", safe=False), block_loader("standard", "chats", safe=False), @@ -21,7 +22,6 @@ async def main(): block_loader("standard", "help"), # block_loader("external", "yandexgpt", safe=False), # - # block_loader("standard", "filters"), # block_loader("standard", "admin"), # block_loader("standard", "message_processing"), # block_loader("standard", "miniapp", safe=False), diff --git a/src/karkas_blocks/karkas_blocks/standard/filters/filters.py b/src/karkas_blocks/karkas_blocks/standard/filters/filters.py index dfe98bd..f440d90 100644 --- a/src/karkas_blocks/karkas_blocks/standard/filters/filters.py +++ b/src/karkas_blocks/karkas_blocks/standard/filters/filters.py @@ -1,11 +1,14 @@ -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict -from aiogram import Bot +from aiogram import BaseMiddleware, Bot from aiogram.filters import BaseFilter -from aiogram.types import Message +from aiogram.types import Message, TelegramObject from typing_extensions import deprecated -from karkas_core.modules_system.public_api import get_module +from karkas_core.modules_system.public_api import ( + get_module, + register_outer_message_middleware, +) if TYPE_CHECKING: from karkas_blocks.standard.config import IConfig @@ -22,12 +25,46 @@ except Exception: pass +class GlobalFilter(BaseMiddleware): + def __init__(self) -> None: + super().__init__() + self.filter = ChatIDFilter() + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + if not isinstance(event, Message): + return await handler(event, data) + + if not config.get("filters::global::enabled"): + return await handler(event, data) + + if await self.filter(event, None): + return await handler(event, data) + + if event.chat.type == "private": + if config.get("filters::global::private_allowed"): + return await handler(event, data) + + await event.answer("НЕЛЬЗЯ!") + + return + + def module_init(): config.register( "filters::approved_chat_id", "int", multiple=True, shared=True, default_value=[] ) config.register("filters::default_chat_tag", "string", shared=True) + config.register("filters::global::enabled", "boolean", default_value=False) + config.register("filters::global::private_allowed", "boolean", default_value=False) + + register_outer_message_middleware(GlobalFilter()) + def get_approved_chat_id() -> list: return config.get("filters::approved_chat_id")