2022-02-11 02:02:28 +03:00
|
|
|
from aiocache import cached
|
|
|
|
import hashlib
|
|
|
|
from aiogram.types import InlineQuery, InputTextMessageContent, InlineQueryResultArticle
|
2022-02-11 04:24:11 +03:00
|
|
|
from aiogram.bot import Bot as AioBot
|
2022-02-11 02:02:28 +03:00
|
|
|
|
2022-02-11 04:08:14 +03:00
|
|
|
from olgram.models.models import Bot
|
2022-02-11 02:02:28 +03:00
|
|
|
import typing as ty
|
|
|
|
|
|
|
|
|
|
|
|
@cached(ttl=1)
|
2022-02-11 04:06:28 +03:00
|
|
|
async def get_phrases(bot: Bot) -> ty.List:
|
|
|
|
objects = await bot.answers
|
2022-02-11 02:02:28 +03:00
|
|
|
return [obj.text for obj in objects]
|
|
|
|
|
|
|
|
|
2022-02-11 04:24:11 +03:00
|
|
|
@cached(ttl=1)
|
|
|
|
async def check_chat_member(chat_id: int, user_id: int, bot: AioBot) -> bool:
|
|
|
|
member = await bot.get_chat_member(chat_id, user_id)
|
|
|
|
return member.is_chat_member()
|
|
|
|
|
|
|
|
|
|
|
|
@cached(ttl=1)
|
|
|
|
async def check_permissions(inline_query: InlineQuery, bot: Bot):
|
|
|
|
user_id = inline_query.from_user.id
|
|
|
|
super_chat_id = await bot.super_chat_id()
|
|
|
|
|
|
|
|
if super_chat_id == user_id:
|
|
|
|
return True
|
|
|
|
|
|
|
|
if super_chat_id < 0: # Group chat
|
|
|
|
is_member = await check_chat_member(super_chat_id, user_id, inline_query.bot)
|
|
|
|
return is_member
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
2022-02-11 02:02:28 +03:00
|
|
|
async def inline_handler(inline_query: InlineQuery, bot: Bot):
|
|
|
|
# Check permissions at first
|
2022-02-11 04:24:11 +03:00
|
|
|
allow = await check_permissions(inline_query, bot)
|
|
|
|
if not allow:
|
|
|
|
return await inline_query.answer([], cache_time=1) # forbidden
|
2022-02-11 02:02:28 +03:00
|
|
|
|
2022-02-11 04:06:28 +03:00
|
|
|
all_phrases = await get_phrases(bot)
|
2022-02-11 02:02:28 +03:00
|
|
|
phrases = [phrase for phrase in all_phrases if inline_query.query.lower() in phrase.lower()]
|
2022-02-11 04:26:09 +03:00
|
|
|
items = []
|
2022-02-11 02:02:28 +03:00
|
|
|
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)
|