import os from fastapi import APIRouter, Request, HTTPException from aiogram import Bot, Dispatcher, F from aiogram.types import Update, Message from aiogram.fsm.state import State, StatesGroup from aiogram.fsm.context import FSMContext from aiogram.fsm.storage.memory import MemoryStorage from aiogram.filters import CommandStart, CommandObject from app.services.auth import AuthService router = APIRouter() BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN") WEBHOOK_SECRET = os.getenv("TELEGRAM_WEBHOOK_SECRET", "") bot = Bot(token=BOT_TOKEN) dp = Dispatcher(storage=MemoryStorage()) auth_service = AuthService() # ===== FSM ===== class Register(StatesGroup): username = State() code = State() # ===== Handlers ===== @dp.message(CommandStart()) async def start(message: Message, state: FSMContext, command: CommandObject): if command.args: await state.update_data(username=command.args) await state.set_state(Register.code) await message.answer("πŸ“‹ Π’Π²Π΅Π΄ΠΈΡ‚Π΅ ΠΊΠΎΠ΄ ΠΈΠ· Π»Π°ΡƒΠ½Ρ‡Π΅Ρ€Π°:") else: await state.set_state(Register.username) await message.answer("πŸ”‘ Π’Π²Π΅Π΄ΠΈΡ‚Π΅ ваш ΠΈΠ³Ρ€ΠΎΠ²ΠΎΠΉ Π½ΠΈΠΊΠ½Π΅ΠΉΠΌ:") @dp.message(Register.username) async def process_username(message: Message, state: FSMContext): await state.update_data(username=message.text.strip()) await state.set_state(Register.code) await message.answer("πŸ“‹ Π’Π΅ΠΏΠ΅Ρ€ΡŒ Π²Π²Π΅Π΄ΠΈΡ‚Π΅ ΠΊΠΎΠ΄ ΠΈΠ· Π»Π°ΡƒΠ½Ρ‡Π΅Ρ€Π°:") @dp.message(Register.code) async def process_code(message: Message, state: FSMContext): data = await state.get_data() username = data["username"] code = message.text.strip() try: await auth_service.verify_code( username=username, code=code, telegram_chat_id=message.chat.id, ) await message.answer("βœ… Аккаунт ΠΏΠΎΠ΄Ρ‚Π²Π΅Ρ€ΠΆΠ΄Π΅Π½!") await state.clear() except Exception as e: await message.answer(f"❌ Ошибка: {e}") await state.clear() # ===== Webhook endpoint ===== @router.post("/telegram/webhook") async def telegram_webhook(request: Request): if WEBHOOK_SECRET: token = request.headers.get("X-Telegram-Bot-Api-Secret-Token") if token != WEBHOOK_SECRET: raise HTTPException(status_code=403, detail="Forbidden") data = await request.json() update = Update.model_validate(data) await dp.feed_update(bot, update) return {"ok": True}