diff --git a/.env.example b/.env.example index 50d561f..416b805 100644 --- a/.env.example +++ b/.env.example @@ -1,3 +1,4 @@ TELEGRAM_BOT_TOKEN= TELEGRAM_CHAT_ID= TELEGRAM_MESSAGE_THREAD_ID= +CORS_ORIGINS=* diff --git a/main.py b/main.py index 3f835e1..f4d28c6 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,7 @@ from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware from httpx import AsyncClient from pydantic import BaseModel, EmailStr @@ -22,6 +23,16 @@ async def lifespan(app: FastAPI): 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' @@ -31,9 +42,15 @@ async def send_telegram_message(client: AsyncClient, text: str) -> None: 'text': text, } resp = await client.post(url, json=payload) - data = resp.json() + try: + data = resp.json() + except Exception: + data = {} if resp.status_code != 200 or not data.get('ok'): - detail = data.get('description', resp.text) + 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) diff --git a/settings.py b/settings.py index d1d72b8..1d39d8a 100644 --- a/settings.py +++ b/settings.py @@ -7,6 +7,7 @@ class Settings(BaseSettings): telegram_bot_token: str telegram_chat_id: str telegram_message_thread_id: int + cors_origins: str = '*' settings = Settings()