67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from httpx import AsyncClient
|
|
from pydantic import BaseModel, EmailStr
|
|
|
|
from settings import settings
|
|
|
|
|
|
class NotifyBody(BaseModel):
|
|
name: str
|
|
email: EmailStr
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
app.state.http = AsyncClient(timeout=30.0)
|
|
yield
|
|
await app.state.http.aclose()
|
|
|
|
|
|
|
|
app = FastAPI(lifespan=lifespan)
|
|
|
|
_raw_cors = settings.cors_origins.strip()
|
|
_cors_allow = ['*'] if _raw_cors == '*' else [o.strip() for o in _raw_cors.split(',') if o.strip()]
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=_cors_allow,
|
|
allow_methods=['*'],
|
|
allow_headers=['*'],
|
|
allow_credentials=False,
|
|
)
|
|
|
|
|
|
async def send_telegram_message(client: AsyncClient, text: str) -> None:
|
|
url = f'https://api.telegram.org/bot{settings.telegram_bot_token}/sendMessage'
|
|
payload = {
|
|
'chat_id': settings.telegram_chat_id,
|
|
'message_thread_id': settings.telegram_message_thread_id,
|
|
'text': text,
|
|
}
|
|
resp = await client.post(url, json=payload)
|
|
try:
|
|
data = resp.json()
|
|
except Exception:
|
|
data = {}
|
|
if resp.status_code != 200 or not data.get('ok'):
|
|
detail = data.get('description') or resp.text or f'HTTP {resp.status_code}'
|
|
code = data.get('error_code')
|
|
if code is not None:
|
|
detail = f'{detail} (error_code={code})'
|
|
raise HTTPException(status_code=502, detail=detail)
|
|
|
|
|
|
@app.post('/notify')
|
|
async def notify(body: NotifyBody):
|
|
text = f'Новая заявка\nИмя: {body.name}\nПочта: {body.email}'
|
|
try:
|
|
await send_telegram_message(app.state.http, text)
|
|
except HTTPException:
|
|
raise
|
|
except Exception as exc:
|
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
return {'ok': True}
|