From a7a08639cfed1afae9c8fa1f57e98b144ac952c3 Mon Sep 17 00:00:00 2001 From: mihalin Date: Fri, 11 Feb 2022 02:02:28 +0300 Subject: [PATCH] inlines first iteration --- server/custom.py | 8 +++++++- server/inlines.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 server/inlines.py diff --git a/server/custom.py b/server/custom.py index 717f946..38f1146 100644 --- a/server/custom.py +++ b/server/custom.py @@ -11,7 +11,7 @@ import logging import typing as ty from olgram.settings import ServerSettings from olgram.models.models import Bot, GroupChat, BannedUser - +from server.inlines import inline_handler _logger = logging.getLogger(__name__) _logger.setLevel(logging.INFO) @@ -136,6 +136,11 @@ async def receive_left(message: types.Message): await bot.save() +async def receive_inline(inline_query): + bot = db_bot_instance.get() + return await inline_handler(inline_query, bot) + + async def receive_migrate(message: types.Message): bot = db_bot_instance.get() from_id = message.chat.id @@ -175,6 +180,7 @@ class CustomRequestHandler(WebhookRequestHandler): dp.register_message_handler(receive_left, content_types=[types.ContentType.LEFT_CHAT_MEMBER]) dp.register_message_handler(receive_migrate, content_types=[types.ContentType.MIGRATE_TO_CHAT_ID]) dp.register_message_handler(receive_group_create, content_types=[types.ContentType.GROUP_CHAT_CREATED]) + dp.register_inline_handler(receive_inline) return dp diff --git a/server/inlines.py b/server/inlines.py new file mode 100644 index 0000000..17c32ec --- /dev/null +++ b/server/inlines.py @@ -0,0 +1,36 @@ +from aiocache import cached +import hashlib +from aiogram.types import InlineQuery, InputTextMessageContent, InlineQueryResultArticle + +from olgram.models.models import Bot, DefaultAnswer +import typing as ty + + +@cached(ttl=1) +async def get_phrases(bot: int) -> ty.List: + objects = await DefaultAnswer.filter(bot_id=bot) + return [obj.text for obj in objects] + + +async def inline_handler(inline_query: InlineQuery, bot: Bot): + # Check permissions at first + # user_id = inline_query.from_user.id + # if bot.super_chat_id() != user_id: + # return await inline_query.answer([], cache_time=1) # forbidden + + all_phrases = await get_phrases(bot.id) + phrases = [phrase for phrase in all_phrases if inline_query.query.lower() in phrase.lower()] + + items = [] + for phrase in phrases: + + input_content = InputTextMessageContent(phrase) + result_id: str = hashlib.md5(phrase.encode()).hexdigest() + item = InlineQueryResultArticle( + id=result_id, + title=phrase, + input_message_content=input_content, + ) + items.append(item) + + await inline_query.answer(results=items, cache_time=1)