Files
2025-12-20 15:48:15 +05:00

92 lines
3.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 and command.args.startswith("qr_"):
token = command.args.removeprefix("qr_").strip()
tg_user = message.from_user
try:
await auth_service.approve_qr_login(token=token, telegram_user_id=tg_user.id)
await message.answer("✅ Вход подтверждён. Вернитесь в лаунчер.")
except Exception as e:
await message.answer(f"Не удалось подтвердить вход: {e}")
return
# старое поведение регистрации/верификации:
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()
tg_user = message.from_user
try:
await auth_service.verify_code(
username=username,
code=code,
telegram_user_id=tg_user.id,
telegram_username=tg_user.username,
)
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}