Files
popa_minecraft_launcher_api/app/webhooks/telegram.py

78 lines
2.4 KiB
Python

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}