50 lines
1.3 KiB
Python
50 lines
1.3 KiB
Python
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, HTTPException
|
|
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)
|
|
|
|
|
|
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)
|
|
data = resp.json()
|
|
if resp.status_code != 200 or not data.get('ok'):
|
|
detail = data.get('description', resp.text)
|
|
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}
|