|
from fastapi import FastAPI, Request |
|
from twilio.rest import Client |
|
from twilio.twiml.messaging_response import MessagingResponse |
|
import openai |
|
import os |
|
|
|
app = FastAPI() |
|
|
|
|
|
openai.api_key = os.getenv("OPENAI_API_KEY") |
|
twilio_account_sid = os.getenv("TWILIO_ACCOUNT_SID") |
|
twilio_auth_token = os.getenv("TWILIO_AUTH_TOKEN") |
|
twilio_whatsapp_number = os.getenv("TWILIO_WHATSAPP_NUMBER") |
|
|
|
|
|
client = Client(twilio_account_sid, twilio_auth_token) |
|
|
|
@app.post("/webhook") |
|
async def whatsapp_webhook(request: Request): |
|
|
|
form = await request.form() |
|
incoming_msg = form.get('Body', '').strip() |
|
from_number = form.get('From', '').strip() |
|
|
|
|
|
response_text = get_gpt4_response(incoming_msg) |
|
|
|
|
|
client.messages.create( |
|
body=response_text, |
|
from_=twilio_whatsapp_number, |
|
to=from_number |
|
) |
|
|
|
|
|
twilio_resp = MessagingResponse() |
|
twilio_resp.message("Procesando tu mensaje...") |
|
return str(twilio_resp) |
|
|
|
def get_gpt4_response(message): |
|
""" |
|
Envía el mensaje del usuario a GPT-4 y devuelve la respuesta generada. |
|
""" |
|
try: |
|
response = openai.ChatCompletion.create( |
|
model="gpt-4", |
|
messages=[{"role": "user", "content": message}], |
|
temperature=0.7 |
|
) |
|
return response.choices[0].message['content'] |
|
except Exception as e: |
|
print(f"Error con la API de GPT-4: {e}") |
|
return "Lo siento, hubo un problema al procesar tu mensaje. Inténtalo de nuevo más tarde." |
|
|