File size: 1,852 Bytes
4c610bf
 
 
 
 
d25b4c4
4c610bf
d25b4c4
4c610bf
 
 
 
 
e48a6c2
4c610bf
 
d25b4c4
4c610bf
 
 
 
 
 
e48a6c2
4c610bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from fastapi import FastAPI, Request
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
import openai
import os

app = FastAPI()

# Configura las claves de API desde las variables de entorno
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")

# Inicializa el cliente de Twilio
client = Client(twilio_account_sid, twilio_auth_token)

@app.post("/webhook")
async def whatsapp_webhook(request: Request):
    # Extraer el mensaje entrante y el número del remitente desde Twilio
    form = await request.form()
    incoming_msg = form.get('Body').strip()
    from_number = form.get('From').strip()

    # Generar una respuesta usando GPT-4
    response_text = get_gpt4_response(incoming_msg)

    # Enviar la respuesta de vuelta al usuario en WhatsApp a través de Twilio
    client.messages.create(
        body=response_text,
        from_=twilio_whatsapp_number,
        to=from_number
    )

    # Crear una respuesta TwiML (solo como confirmación)
    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  # Controla la creatividad de la respuesta
        )
        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."