Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Form, Response, HTTPException
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
import json
|
| 4 |
+
import datetime
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# Модель для логування або подальшої роботи в коді
|
| 9 |
+
class SMSMessage(BaseModel):
|
| 10 |
+
message_sid: str
|
| 11 |
+
from_number: str
|
| 12 |
+
to_number: str
|
| 13 |
+
body: str
|
| 14 |
+
timestamp: str
|
| 15 |
+
|
| 16 |
+
@app.post("/sms/webhook")
|
| 17 |
+
async def twilio_sms_webhook(
|
| 18 |
+
MessageSid: str = Form(...),
|
| 19 |
+
From: str = Form(...),
|
| 20 |
+
To: str = Form(...),
|
| 21 |
+
Body: str = Form(...)
|
| 22 |
+
):
|
| 23 |
+
try:
|
| 24 |
+
# 1. Збираємо дані в чистий словник
|
| 25 |
+
sms_data = SMSMessage(
|
| 26 |
+
message_sid=MessageSid,
|
| 27 |
+
from_number=From,
|
| 28 |
+
to_number=To,
|
| 29 |
+
body=Body,
|
| 30 |
+
timestamp=datetime.datetime.utcnow().isoformat()
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
# 2. Перетворюємо в JSON для збереження в бакет
|
| 34 |
+
file_content = json.dumps(sms_data.dict(), indent=4, ensure_ascii=False)
|
| 35 |
+
file_name = f"sms_{MessageSid}.json"
|
| 36 |
+
|
| 37 |
+
# TODO: Твоя логіка завантаження в бакет "sms-storage" з шляхом /sms
|
| 38 |
+
# Наприклад, якщо юзаєш Supabase/S3:
|
| 39 |
+
# storage.from_("sms-storage").upload(path=f"sms/{file_name}", file=file_content)
|
| 40 |
+
|
| 41 |
+
print(f" New SMS from {From} saved to bucket as {file_name}")
|
| 42 |
+
|
| 43 |
+
# 3. Twilio ОБОВ'ЯЗКОВО вимагає у відповідь правильний TwiML (XML),
|
| 44 |
+
# навіть якщо він пустий <Response/>, інакше він буде сипати помилками в консоль.
|
| 45 |
+
twiml_response = "<Response></Response>"
|
| 46 |
+
return Response(content=twiml_response, media_type="application/xml")
|
| 47 |
+
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"❌ Error processing Twilio webhook: {str(e)}")
|
| 50 |
+
raise HTTPException(status_code=500, detail="Internal Server Error")
|