2025-12-24 06:28:01 +03:00

71 lines
2.3 KiB
Python

import logging
from aiogram import Bot, Dispatcher
from aiogram.enums import ParseMode
from aiogram.client.default import DefaultBotProperties
from tg_bot.config.settings import settings
from tg_bot.infrastructure.telegram.handlers import (
start_handler,
help_handler,
stats_handler,
question_handler,
buy_handler,
collection_handler,
document_handler
)
logger = logging.getLogger(__name__)
async def create_bot() -> tuple[Bot, Dispatcher]:
bot = Bot(
token=settings.TELEGRAM_BOT_TOKEN,
default=DefaultBotProperties(parse_mode=ParseMode.HTML)
)
dp = Dispatcher()
dp.include_router(start_handler.router)
dp.include_router(help_handler.router)
dp.include_router(stats_handler.router)
dp.include_router(buy_handler.router)
dp.include_router(collection_handler.router)
dp.include_router(document_handler.router)
dp.include_router(question_handler.router)
return bot, dp
async def start_bot():
bot = None
try:
if not settings.TELEGRAM_BOT_TOKEN or not settings.TELEGRAM_BOT_TOKEN.strip():
raise ValueError("TELEGRAM_BOT_TOKEN не установлен в переменных окружения или файле .env")
bot, dp = await create_bot()
try:
bot_info = await bot.get_me()
username = bot_info.username if bot_info.username else f"ID: {bot_info.id}"
logger.info(f"Бот успешно подключен: @{username}")
except Exception as e:
raise ValueError(f"Неверный токен Telegram бота: {e}")
try:
webhook_info = await bot.get_webhook_info()
if webhook_info.url:
await bot.delete_webhook(drop_pending_updates=True)
except Exception:
pass
print("=" * 50)
print("Telegram бот запускается")
print(f"Бот: @vibelawyer_bot")
print(f"Лимит: {settings.FREE_QUESTIONS_LIMIT} вопросов")
print(f"Команды: /start, /help, /buy, /stats, /mycollections, /search")
print("=" * 50)
await dp.start_polling(bot, drop_pending_updates=True)
except Exception as e:
logger.error(f"Ошибка запуска: {e}")
raise
finally:
if bot:
await bot.session.close()