GAS17 commited on
Commit
4ceb6f6
verified
1 Parent(s): 73d6b09

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request
2
+ from twilio.rest import Client
3
+ from twilio.twiml.messaging_response import MessagingResponse
4
+ import openai
5
+ import os
6
+
7
+ app = FastAPI()
8
+
9
+ # Configuraci贸n de las claves de API desde las variables de entorno
10
+ openai.api_key = os.getenv("OPENAI_API_KEY")
11
+ twilio_account_sid = os.getenv("TWILIO_ACCOUNT_SID")
12
+ twilio_auth_token = os.getenv("TWILIO_AUTH_TOKEN")
13
+ twilio_whatsapp_number = os.getenv("TWILIO_WHATSAPP_NUMBER")
14
+
15
+ # Inicializa el cliente de Twilio
16
+ client = Client(twilio_account_sid, twilio_auth_token)
17
+
18
+ @app.post("/webhook")
19
+ async def whatsapp_webhook(request: Request):
20
+ # Extraer el mensaje entrante y el n煤mero del remitente desde Twilio
21
+ form = await request.form()
22
+ incoming_msg = form.get('Body').strip()
23
+ from_number = form.get('From').strip()
24
+
25
+ # Generar una respuesta usando GPT-4
26
+ response_text = get_gpt4_response(incoming_msg)
27
+
28
+ # Enviar la respuesta de vuelta al usuario en WhatsApp a trav茅s de Twilio
29
+ client.messages.create(
30
+ body=response_text,
31
+ from_=twilio_whatsapp_number,
32
+ to=from_number
33
+ )
34
+
35
+ # Crear una respuesta TwiML para confirmar recepci贸n
36
+ twilio_resp = MessagingResponse()
37
+ twilio_resp.message("Procesando tu mensaje...")
38
+ return str(twilio_resp)
39
+
40
+ def get_gpt4_response(message):
41
+ try:
42
+ response = openai.ChatCompletion.create(
43
+ model="gpt-4",
44
+ messages=[{"role": "user", "content": message}],
45
+ temperature=0.7
46
+ )
47
+ return response.choices[0].message['content']
48
+ except Exception as e:
49
+ print(f"Error con la API de GPT-4: {e}")
50
+ return "Lo siento, hubo un problema al procesar tu mensaje."