79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
from uuid import uuid4
|
|
|
|
import requests
|
|
from telegram import Update, InlineKeyboardButton, InlineQueryResultArticle, InputTextMessageContent, \
|
|
InlineKeyboardMarkup
|
|
from telegram.constants import ParseMode
|
|
from telegram.ext import ContextTypes
|
|
|
|
from extensions import humanize_tags_from_json, format_rating
|
|
|
|
|
|
# noinspection PyUnusedLocal
|
|
async def inline_query(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
|
query = update.inline_query.query
|
|
|
|
if not query:
|
|
return
|
|
|
|
if not query.isdigit():
|
|
return
|
|
|
|
from main import config
|
|
response = requests.get(f"https://{config.get('Service', 'Domain')}/posts/{query}.json")
|
|
|
|
if response.status_code != 200:
|
|
await invalid_query(update, query)
|
|
return
|
|
|
|
data = response.json()
|
|
|
|
await answer_query(update, query, config, data)
|
|
|
|
|
|
async def answer_query(update, query, config, data):
|
|
characters = humanize_tags_from_json(data['tag_string_character'], "no characters")
|
|
copyrights = humanize_tags_from_json(data['tag_string_copyright'], "unknown copyright")
|
|
artists = humanize_tags_from_json(data['tag_string_artist'], "unknown artist")
|
|
rating = format_rating(data['rating'])
|
|
keyboard = [
|
|
[
|
|
InlineKeyboardButton(f"Open in {config.get('Service', 'Name')}",
|
|
url=f"https://{config.get('Service', 'Domain')}/posts/{query}"),
|
|
InlineKeyboardButton("View original", url=data['file_url'])
|
|
]
|
|
]
|
|
|
|
results = [
|
|
InlineQueryResultArticle(
|
|
id=str(uuid4()),
|
|
title=f"ID: {query}",
|
|
description=f"{characters} ({copyrights}) drawn by {artists}",
|
|
thumbnail_url=data['preview_file_url'],
|
|
input_message_content=InputTextMessageContent(
|
|
f"ID: <code>{query}</code> {rating}\n"
|
|
f"<a href='{data['large_file_url']}'><b>{characters} ({copyrights})</b> "
|
|
f"drawn by <b>{artists}</b></a>",
|
|
parse_mode=ParseMode.HTML
|
|
),
|
|
reply_markup=InlineKeyboardMarkup(keyboard)
|
|
)
|
|
]
|
|
|
|
await update.inline_query.answer(results)
|
|
|
|
|
|
async def invalid_query(update, query):
|
|
results = [
|
|
InlineQueryResultArticle(
|
|
id=str(uuid4()),
|
|
title=f"ID: {query}",
|
|
description="not found.",
|
|
input_message_content=InputTextMessageContent(
|
|
f"ID: <code>{query}</code>\n<b>requested post does not exist.</b>",
|
|
parse_mode=ParseMode.HTML
|
|
)
|
|
)
|
|
]
|
|
|
|
await update.inline_query.answer(results)
|