forked from HSE_team/BetterCallPraskovia
подписка и фичи
This commit is contained in:
parent
fab9bd42cb
commit
56489de4f2
@ -9,7 +9,8 @@ from tg_bot.infrastructure.telegram.handlers import (
|
|||||||
help_handler,
|
help_handler,
|
||||||
stats_handler,
|
stats_handler,
|
||||||
question_handler,
|
question_handler,
|
||||||
buy_handler
|
buy_handler,
|
||||||
|
collection_handler
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@ -26,6 +27,7 @@ async def create_bot() -> tuple[Bot, Dispatcher]:
|
|||||||
dp.include_router(stats_handler.router)
|
dp.include_router(stats_handler.router)
|
||||||
dp.include_router(question_handler.router)
|
dp.include_router(question_handler.router)
|
||||||
dp.include_router(buy_handler.router)
|
dp.include_router(buy_handler.router)
|
||||||
|
dp.include_router(collection_handler.router)
|
||||||
return bot, dp
|
return bot, dp
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
183
tg_bot/infrastructure/telegram/handlers/collection_handler.py
Normal file
183
tg_bot/infrastructure/telegram/handlers/collection_handler.py
Normal file
@ -0,0 +1,183 @@
|
|||||||
|
from aiogram import Router
|
||||||
|
from aiogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
|
||||||
|
from aiogram.filters import Command
|
||||||
|
import aiohttp
|
||||||
|
|
||||||
|
router = Router()
|
||||||
|
|
||||||
|
BACKEND_URL = "http://localhost:8001/api/v1"
|
||||||
|
|
||||||
|
|
||||||
|
async def get_user_collections(telegram_id: str):
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(
|
||||||
|
f"{BACKEND_URL}/collections/",
|
||||||
|
headers={"X-Telegram-ID": telegram_id}
|
||||||
|
) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
return await response.json()
|
||||||
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error getting collections: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def get_collection_documents(collection_id: str, telegram_id: str):
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(
|
||||||
|
f"{BACKEND_URL}/documents/collection/{collection_id}",
|
||||||
|
headers={"X-Telegram-ID": telegram_id}
|
||||||
|
) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
return await response.json()
|
||||||
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error getting documents: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
async def search_in_collection(collection_id: str, query: str, telegram_id: str):
|
||||||
|
try:
|
||||||
|
async with aiohttp.ClientSession() as session:
|
||||||
|
async with session.get(
|
||||||
|
f"{BACKEND_URL}/documents/collection/{collection_id}",
|
||||||
|
params={"search": query},
|
||||||
|
headers={"X-Telegram-ID": telegram_id}
|
||||||
|
) as response:
|
||||||
|
if response.status == 200:
|
||||||
|
return await response.json()
|
||||||
|
return []
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error searching: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
@router.message(Command("mycollections"))
|
||||||
|
async def cmd_mycollections(message: Message):
|
||||||
|
telegram_id = str(message.from_user.id)
|
||||||
|
collections = await get_user_collections(telegram_id)
|
||||||
|
|
||||||
|
if not collections:
|
||||||
|
await message.answer(
|
||||||
|
"<b>У вас пока нет коллекций</b>\n\n"
|
||||||
|
"Обратитесь к администратору для создания коллекций и добавления документов.",
|
||||||
|
parse_mode="HTML"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
response = "<b>Ваши коллекции документов:</b>\n\n"
|
||||||
|
keyboard_buttons = []
|
||||||
|
|
||||||
|
for i, collection in enumerate(collections[:10], 1):
|
||||||
|
name = collection.get("name", "Без названия")
|
||||||
|
description = collection.get("description", "")
|
||||||
|
collection_id = collection.get("collection_id")
|
||||||
|
|
||||||
|
response += f"{i}. <b>{name}</b>\n"
|
||||||
|
if description:
|
||||||
|
response += f" <i>{description[:50]}...</i>\n"
|
||||||
|
response += f" ID: <code>{collection_id}</code>\n\n"
|
||||||
|
|
||||||
|
keyboard_buttons.append([
|
||||||
|
InlineKeyboardButton(
|
||||||
|
text=f"{name}",
|
||||||
|
callback_data=f"collection:{collection_id}"
|
||||||
|
)
|
||||||
|
])
|
||||||
|
|
||||||
|
keyboard = InlineKeyboardMarkup(inline_keyboard=keyboard_buttons)
|
||||||
|
|
||||||
|
response += "<i>Нажмите на коллекцию, чтобы посмотреть документы</i>"
|
||||||
|
|
||||||
|
await message.answer(response, parse_mode="HTML", reply_markup=keyboard)
|
||||||
|
|
||||||
|
|
||||||
|
@router.message(Command("search"))
|
||||||
|
async def cmd_search(message: Message):
|
||||||
|
parts = message.text.split(maxsplit=2)
|
||||||
|
if len(parts) < 3:
|
||||||
|
telegram_id = str(message.from_user.id)
|
||||||
|
collections = await get_user_collections(telegram_id)
|
||||||
|
|
||||||
|
if not collections:
|
||||||
|
await message.answer(
|
||||||
|
"<b>Использование:</b> /search <collection_id> <запрос>\n\n"
|
||||||
|
"У вас пока нет коллекций. Обратитесь к администратору.",
|
||||||
|
parse_mode="HTML"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
response = "<b>Выберите коллекцию для поиска:</b>\n\n"
|
||||||
|
response += "Использование: /search <collection_id> <запрос>\n\n"
|
||||||
|
response += "<b>Доступные коллекции:</b>\n"
|
||||||
|
for collection in collections[:5]:
|
||||||
|
name = collection.get("name", "Без названия")
|
||||||
|
collection_id = collection.get("collection_id")
|
||||||
|
response += f"• <b>{name}</b>\n <code>{collection_id}</code>\n\n"
|
||||||
|
response += "Пример: /search " + collections[0].get("collection_id", "")[:8] + "... Как оформить договор?"
|
||||||
|
|
||||||
|
await message.answer(response, parse_mode="HTML")
|
||||||
|
return
|
||||||
|
|
||||||
|
collection_id = parts[1]
|
||||||
|
query = parts[2]
|
||||||
|
telegram_id = str(message.from_user.id)
|
||||||
|
|
||||||
|
await message.bot.send_chat_action(message.chat.id, "typing")
|
||||||
|
|
||||||
|
results = await search_in_collection(collection_id, query, telegram_id)
|
||||||
|
|
||||||
|
if not results:
|
||||||
|
await message.answer(
|
||||||
|
f"<b>Ничего не найдено</b>\n\n"
|
||||||
|
f"По запросу <i>\"{query}\"</i> в коллекции ничего не найдено.\n\n"
|
||||||
|
f"Попробуйте другой запрос или используйте /mycollections для просмотра доступных коллекций.",
|
||||||
|
parse_mode="HTML"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
response = f"<b>Результаты поиска:</b> \"{query}\"\n\n"
|
||||||
|
for i, doc in enumerate(results[:5], 1):
|
||||||
|
title = doc.get("title", "Без названия")
|
||||||
|
content = doc.get("content", "")[:200]
|
||||||
|
response += f"{i}. <b>{title}</b>\n"
|
||||||
|
response += f" <i>{content}...</i>\n\n"
|
||||||
|
|
||||||
|
await message.answer(response, parse_mode="HTML")
|
||||||
|
|
||||||
|
|
||||||
|
@router.callback_query(lambda c: c.data.startswith("collection:"))
|
||||||
|
async def show_collection_documents(callback: CallbackQuery):
|
||||||
|
collection_id = callback.data.split(":")[1]
|
||||||
|
telegram_id = str(callback.from_user.id)
|
||||||
|
|
||||||
|
await callback.answer("Загружаю документы...")
|
||||||
|
|
||||||
|
documents = await get_collection_documents(collection_id, telegram_id)
|
||||||
|
|
||||||
|
if not documents:
|
||||||
|
await callback.message.answer(
|
||||||
|
f"<b>Коллекция пуста</b>\n\n"
|
||||||
|
f"В этой коллекции пока нет документов.\n"
|
||||||
|
f"Обратитесь к администратору для добавления документов.",
|
||||||
|
parse_mode="HTML"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
response = f"<b>Документы в коллекции:</b>\n\n"
|
||||||
|
for i, doc in enumerate(documents[:10], 1):
|
||||||
|
title = doc.get("title", "Без названия")
|
||||||
|
content_preview = doc.get("content", "")[:100]
|
||||||
|
response += f"{i}. <b>{title}</b>\n"
|
||||||
|
if content_preview:
|
||||||
|
response += f" <i>{content_preview}...</i>\n"
|
||||||
|
response += "\n"
|
||||||
|
|
||||||
|
if len(documents) > 10:
|
||||||
|
response += f"\n<i>Показано 10 из {len(documents)} документов</i>"
|
||||||
|
|
||||||
|
await callback.message.answer(response, parse_mode="HTML")
|
||||||
|
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user