Исправление обработчиков для детального просмотра: улучшение сообщений об ошибках и упрощение текста ответов

This commit is contained in:
2026-05-01 17:46:10 +03:00
parent fc9739018e
commit ea5c1b55fc

View File

@@ -1,8 +1,8 @@
""" """
Inline handlers for detailed item viewing with images Inline handlers for detailed item viewing with images (FIXED VERSION)
""" """
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup from telegram import Update
from telegram.ext import ContextTypes, CommandHandler, CallbackQueryHandler from telegram.ext import ContextTypes, CommandHandler
from vndb_client import VndbClient from vndb_client import VndbClient
from utils import ImageHandler from utils import ImageHandler
from config import Config from config import Config
@@ -13,279 +13,213 @@ vndb_client = VndbClient(use_sandbox=Config.USE_SANDBOX)
class DetailedHandlers: class DetailedHandlers:
"""Handlers for detailed item viewing"""
# =========================
# VN DETAIL
# =========================
@staticmethod @staticmethod
async def view_vn_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def view_vn_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""View detailed VN information with image"""
try: try:
if not context.args: if not context.args:
await update.message.reply_text( await update.message.reply_text(
"Пожалуйста, укажите ID визуальной новеллы\n" "Укажи ID VN\nПример: /vn_detail v2002"
"Пример: /vn_detail v17"
) )
return return
vn_id = context.args[0] vn_id = context.args[0].strip()
await update.message.reply_text(f"⏳ Загружаю информацию о {vn_id}...", parse_mode="Markdown")
await update.message.reply_text(
f"⏳ Загружаю информацию о {vn_id}..."
)
# Get detailed VN information
filters = ["id", "=", vn_id]
results = await vndb_client.query_vn( results = await vndb_client.query_vn(
filters=[filters], filters=["id", "=", vn_id],
fields=[ fields=[
"title", "original", "released", "rating", "votecount", "id", "title", "original", "released",
"description", "image{url,dims}", "length", "developer" "rating", "votecount", "description",
] "length", "developer", "image{url,dims}"
],
results=1
) )
if not results.get("results"): if not results.get("results"):
await update.message.reply_text(f"😞 ВН с ID {vn_id} не найдена") await update.message.reply_text(f"😞 VN {vn_id} не найдена")
return return
vn = results["results"][0] vn = results["results"][0]
# Build detailed text text = f"🎮 {vn.get('title','Unknown')} (`{vn_id}`)\n"
title = vn.get("title", "Unknown")
original = vn.get("original", "")
released = vn.get("released", "Unknown")
rating = vn.get("rating", 0)
votecount = vn.get("votecount", 0)
description = vn.get("description", "")
length = vn.get("length", "")
developer = vn.get("developer", "")
detail_text = f""" if vn.get("original"):
**🎮 {title}** (`{vn_id}`) text += f"Оригинал: {vn['original']}\n"
"""
if original: text += f"Релиз: {vn.get('released','?')}\n"
detail_text += f"Оригинал: {original}\n" text += f"Рейтинг: {vn.get('rating',0)/10:.1f} ({vn.get('votecount',0)} голосов)\n"
detail_text += f""" if vn.get("developer"):
Дата релиза: {released} text += f"Разработчик: {vn['developer']}\n"
Рейтинг: {rating/10:.1f}/10 ({votecount} голосов)
"""
if length: if vn.get("description"):
detail_text += f"Длительность: {length}\n" desc = vn["description"][:300]
text += f"\nОписание:\n{desc}...\n"
if developer: text += f"\nhttps://vndb.org/{vn_id}"
detail_text += f"Разработчик: {developer}\n"
if description: img = vn.get("image")
# Truncate long descriptions if img:
desc_truncated = description[:300] + "..." if len(description) > 300 else description url = ImageHandler.get_image_url(img)
detail_text += f"\nОписание:\n{desc_truncated}\n" if url:
await update.message.reply_photo(photo=url, caption=text)
return
detail_text += f"\n[Открыть на VNDB](https://vndb.org/{vn_id})" await update.message.reply_text(text)
# Send with image if available
image_data = vn.get("image")
if image_data:
image_url = ImageHandler.get_image_url(image_data)
if image_url:
try:
await update.message.reply_photo(
photo=image_url,
caption=detail_text,
parse_mode="Markdown"
)
except Exception as e:
logger.warning(f"Could not send VN image: {e}")
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
except Exception as e: except Exception as e:
logger.error(f"Error viewing VN detail: {e}") logger.error(f"VN detail error: {e}")
await update.message.reply_text(f"❌ Ошибка при загрузке информации: {str(e)}") await update.message.reply_text(f"❌ Ошибка: {e}")
# =========================
# CHARACTER DETAIL
# =========================
@staticmethod @staticmethod
async def view_character_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def view_character_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""View detailed character information with image"""
try: try:
if not context.args: if not context.args:
await update.message.reply_text( await update.message.reply_text("❌ Пример: /char_detail c6498")
"❌ Пожалуйста, укажите ID персонажа\n"
"Пример: /char_detail c1"
)
return return
char_id = context.args[0] char_id = context.args[0].strip()
await update.message.reply_text(f"⏳ Загружаю информацию о {char_id}...", parse_mode="Markdown")
await update.message.reply_text(f"⏳ Загружаю {char_id}...")
# Get detailed character information
filters = ["id", "=", char_id]
results = await vndb_client.query_character( results = await vndb_client.query_character(
filters=[filters], filters=["id", "=", char_id],
fields=[ fields=[
"name", "original", "gender", "bloodtype", "height", "weight", "id", "name", "original",
"bust", "waist", "hips", "description", "image{url,dims}", "vn" "gender", "bloodtype",
] "description", "image{url,dims}",
"vn"
],
results=1
) )
if not results.get("results"): if not results.get("results"):
await update.message.reply_text(f"😞 Персонаж с ID {char_id} не найден") await update.message.reply_text("😞 Персонаж не найден")
return return
char = results["results"][0] c = results["results"][0]
# Build detailed text text = f"👤 {c.get('name','Unknown')} (`{char_id}`)\n"
name = char.get("name", "Unknown")
original = char.get("original", "")
gender = char.get("gender", "")
bloodtype = char.get("bloodtype", "")
description = char.get("description", "")
vns = char.get("vn", [])
detail_text = f"**👤 {name}** (`{char_id}`)\n" if c.get("original"):
text += f"{c['original']}\n"
if original: if c.get("gender"):
detail_text += f"Оригинал: {original}\n" text += f"Пол: {c['gender']}\n"
if gender: if c.get("bloodtype"):
detail_text += f"Пол: {gender}\n" text += f"Кровь: {c['bloodtype']}\n"
if bloodtype: if c.get("vn"):
detail_text += f"Группа крови: {bloodtype}\n" text += "\nVN:\n"
for vn in c["vn"][:5]:
if vn.get("id"):
text += f"{vn['id']}\n"
if vns: if c.get("description"):
detail_text += f"\nПоявляется в:\n" text += f"\n{c['description'][:300]}...\n"
for vn in vns[:5]: # Show first 5 VNs
vn_id = vn.get("id", "")
if vn_id:
detail_text += f"• [{vn_id}](https://vndb.org/{vn_id})\n"
if description: text += f"\nhttps://vndb.org/{char_id}"
desc_truncated = description[:300] + "..." if len(description) > 300 else description
detail_text += f"\nОписание:\n{desc_truncated}\n"
detail_text += f"\n[Открыть на VNDB](https://vndb.org/{char_id})" img = c.get("image")
if img:
url = ImageHandler.get_image_url(img)
if url:
await update.message.reply_photo(photo=url, caption=text)
return
# Send with image if available await update.message.reply_text(text)
image_data = char.get("image")
if image_data:
image_url = ImageHandler.get_image_url(image_data)
if image_url:
try:
await update.message.reply_photo(
photo=image_url,
caption=detail_text,
parse_mode="Markdown"
)
except Exception as e:
logger.warning(f"Could not send character image: {e}")
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
except Exception as e: except Exception as e:
logger.error(f"Error viewing character detail: {e}") logger.error(f"CHAR detail error: {e}")
await update.message.reply_text(f"❌ Ошибка при загрузке информации: {str(e)}") await update.message.reply_text(f"❌ Ошибка: {e}")
# =========================
# RELEASE DETAIL
# =========================
@staticmethod @staticmethod
async def view_release_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def view_release_detail(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""View detailed release information with image"""
try: try:
if not context.args: if not context.args:
await update.message.reply_text( await update.message.reply_text("❌ Пример: /release_detail r3930")
"❌ Пожалуйста, укажите ID релиза\n"
"Пример: /release_detail r1"
)
return return
release_id = context.args[0] release_id = context.args[0].strip()
await update.message.reply_text(f"⏳ Загружаю информацию о {release_id}...", parse_mode="Markdown")
await update.message.reply_text(f"⏳ Загружаю {release_id}...")
# Get detailed release information
filters = ["id", "=", release_id]
results = await vndb_client.query_release( results = await vndb_client.query_release(
filters=[filters], filters=["id", "=", release_id],
fields=[ fields=[
"title", "original", "released", "platform", "type", "language", "id", "title", "original",
"edition", "description", "image{url,dims}", "vn" "released", "platform",
] "type", "language",
"description",
"image{url,dims}",
"vn"
],
results=1
) )
if not results.get("results"): if not results.get("results"):
await update.message.reply_text(f"😞 Релиз с ID {release_id} не найден") await update.message.reply_text("😞 Релиз не найден")
return return
release = results["results"][0] r = results["results"][0]
# Build detailed text text = f"🎬 {r.get('title','Unknown')} (`{release_id}`)\n"
title = release.get("title", "Unknown")
original = release.get("original", "")
released = release.get("released", "Unknown")
platform = release.get("platform", "")
rel_type = release.get("type", "")
language = release.get("language", [])
edition = release.get("edition", "")
description = release.get("description", "")
vns = release.get("vn", [])
detail_text = f"**🎬 {title}** (`{release_id}`)\n" if r.get("original"):
text += f"{r['original']}\n"
if original: text += f"Дата: {r.get('released','?')}\n"
detail_text += f"Оригинал: {original}\n" text += f"Платформа: {r.get('platform','?')}\n"
text += f"Тип: {r.get('type','?')}\n"
detail_text += f""" if r.get("language"):
Дата выпуска: {released} text += f"Языки: {', '.join(r['language'])}\n"
Платформа: {platform}
Тип: {rel_type}
"""
if language: if r.get("vn"):
lang_str = ", ".join(language) if isinstance(language, list) else str(language) text += "\nVN:\n"
detail_text += f"Языки: {lang_str}\n" for vn in r["vn"][:3]:
if vn.get("id"):
text += f"{vn['id']}\n"
if edition: if r.get("description"):
detail_text += f"Издание: {edition}\n" text += f"\n{r['description'][:200]}...\n"
if vns: text += f"\nhttps://vndb.org/{release_id}"
detail_text += f"\nЧасть из:\n"
for vn in vns[:3]:
vn_id = vn.get("id", "")
if vn_id:
detail_text += f"• [{vn_id}](https://vndb.org/{vn_id})\n"
if description: img = r.get("image")
desc_truncated = description[:200] + "..." if len(description) > 200 else description if img:
detail_text += f"\nОписание:\n{desc_truncated}\n" url = ImageHandler.get_image_url(img)
if url:
await update.message.reply_photo(photo=url, caption=text)
return
detail_text += f"\n[Открыть на VNDB](https://vndb.org/{release_id})" await update.message.reply_text(text)
# Send with image if available
image_data = release.get("image")
if image_data:
image_url = ImageHandler.get_image_url(image_data)
if image_url:
try:
await update.message.reply_photo(
photo=image_url,
caption=detail_text,
parse_mode="Markdown"
)
except Exception as e:
logger.warning(f"Could not send release image: {e}")
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
else:
await update.message.reply_text(detail_text, parse_mode="Markdown")
except Exception as e: except Exception as e:
logger.error(f"Error viewing release detail: {e}") logger.error(f"RELEASE detail error: {e}")
await update.message.reply_text(f"❌ Ошибка при загрузке информации: {str(e)}") await update.message.reply_text(f"❌ Ошибка: {e}")
# =========================
# REGISTER
# =========================
def get_detail_handlers(): def get_detail_handlers():
"""Get all detail view handlers"""
return [ return [
CommandHandler("vn_detail", DetailedHandlers.view_vn_detail), CommandHandler("vn_detail", DetailedHandlers.view_vn_detail),
CommandHandler("char_detail", DetailedHandlers.view_character_detail), CommandHandler("char_detail", DetailedHandlers.view_character_detail),