Spaces:
Build error
Build error
Commit
·
bcd422d
1
Parent(s):
6c03001
Add reply function
Browse files- app/services/message.py +51 -28
app/services/message.py
CHANGED
|
@@ -1,27 +1,31 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
from fastapi.exceptions import HTTPException
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
from typing import Dict, Any
|
| 6 |
from datetime import datetime
|
| 7 |
import logging
|
|
|
|
|
|
|
|
|
|
| 8 |
load_dotenv()
|
| 9 |
|
|
|
|
| 10 |
logging.basicConfig(
|
| 11 |
level=logging.INFO,
|
| 12 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 13 |
)
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
| 16 |
-
# Define the WhatsApp API URL
|
| 17 |
WHATSAPP_API_URL = os.environ.get("WHATSAPP_API_URL")
|
| 18 |
-
|
| 19 |
-
# Access the secret token
|
| 20 |
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
|
| 21 |
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Helper function to send a reply
|
| 24 |
-
def send_reply(to: str, body: str):
|
| 25 |
headers = {
|
| 26 |
"Authorization": f"Bearer {ACCESS_TOKEN}",
|
| 27 |
"Content-Type": "application/json"
|
|
@@ -34,36 +38,55 @@ def send_reply(to: str, body: str):
|
|
| 34 |
"body": body
|
| 35 |
}
|
| 36 |
}
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
if response.status_code != 200:
|
| 40 |
-
|
|
|
|
|
|
|
|
|
|
| 41 |
return response.json()
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
| 55 |
|
|
|
|
| 56 |
async def process_message_with_retry(
|
| 57 |
sender_id: str,
|
| 58 |
content: str,
|
| 59 |
timestamp: int
|
| 60 |
) -> Dict[str, Any]:
|
| 61 |
"""Process message with retry logic"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import httpx
|
|
|
|
| 3 |
from dotenv import load_dotenv
|
| 4 |
from typing import Dict, Any
|
| 5 |
from datetime import datetime
|
| 6 |
import logging
|
| 7 |
+
import asyncio
|
| 8 |
+
|
| 9 |
+
# Load environment variables
|
| 10 |
load_dotenv()
|
| 11 |
|
| 12 |
+
# Configure logging
|
| 13 |
logging.basicConfig(
|
| 14 |
level=logging.INFO,
|
| 15 |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 16 |
)
|
| 17 |
logger = logging.getLogger(__name__)
|
| 18 |
|
| 19 |
+
# Define the WhatsApp API URL and Access Token
|
| 20 |
WHATSAPP_API_URL = os.environ.get("WHATSAPP_API_URL")
|
|
|
|
|
|
|
| 21 |
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
|
| 22 |
|
| 23 |
+
# Validate environment variables
|
| 24 |
+
if not WHATSAPP_API_URL or not ACCESS_TOKEN:
|
| 25 |
+
logger.warning("Environment variables for WHATSAPP_API_URL or ACCESS_TOKEN are not set!")
|
| 26 |
|
| 27 |
# Helper function to send a reply
|
| 28 |
+
async def send_reply(to: str, body: str) -> Dict[str, Any]:
|
| 29 |
headers = {
|
| 30 |
"Authorization": f"Bearer {ACCESS_TOKEN}",
|
| 31 |
"Content-Type": "application/json"
|
|
|
|
| 38 |
"body": body
|
| 39 |
}
|
| 40 |
}
|
| 41 |
+
|
| 42 |
+
async with httpx.AsyncClient() as client:
|
| 43 |
+
response = await client.post(WHATSAPP_API_URL, json=data, headers=headers)
|
| 44 |
+
|
| 45 |
if response.status_code != 200:
|
| 46 |
+
error_detail = response.json()
|
| 47 |
+
logger.error(f"Failed to send reply: {error_detail}")
|
| 48 |
+
raise Exception(f"Failed to send reply with status code {response.status_code}: {error_detail}")
|
| 49 |
+
|
| 50 |
return response.json()
|
| 51 |
|
| 52 |
+
# Helper function to generate a reply based on message content
|
| 53 |
+
async def generate_reply(sender: str, content: str, timestamp: int) -> str:
|
| 54 |
+
try:
|
| 55 |
+
received_time = datetime.fromtimestamp(int(timestamp) / 1000) # Assuming timestamp is in milliseconds
|
| 56 |
+
if "hello" in content.lower():
|
| 57 |
+
return f"Hi {sender}, how can I assist you today?"
|
| 58 |
+
elif "test" in content.lower():
|
| 59 |
+
return f"Hi {sender}, this is a reply to your test message."
|
| 60 |
+
elif received_time.hour < 12:
|
| 61 |
+
return f"Good morning, {sender}! How can I help you?"
|
| 62 |
+
else:
|
| 63 |
+
return f"Hello {sender}, I hope you're having a great day!"
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"Error generating reply: {str(e)}", exc_info=True)
|
| 66 |
+
return f"Sorry {sender}, I couldn't process your message. Please try again."
|
| 67 |
|
| 68 |
+
# Process message with retry logic
|
| 69 |
async def process_message_with_retry(
|
| 70 |
sender_id: str,
|
| 71 |
content: str,
|
| 72 |
timestamp: int
|
| 73 |
) -> Dict[str, Any]:
|
| 74 |
"""Process message with retry logic"""
|
| 75 |
+
retries = 3
|
| 76 |
+
delay = 2 # Initial delay in seconds
|
| 77 |
+
|
| 78 |
+
for attempt in range(retries):
|
| 79 |
+
try:
|
| 80 |
+
generated_reply = await generate_reply(sender_id, content, timestamp)
|
| 81 |
+
response = await send_reply(sender_id, generated_reply)
|
| 82 |
+
return {"status": "success", "reply": generated_reply, "response": response}
|
| 83 |
+
except Exception as e:
|
| 84 |
+
logger.error(f"Attempt {attempt + 1} failed: {str(e)}", exc_info=True)
|
| 85 |
+
if attempt < retries - 1:
|
| 86 |
+
await asyncio.sleep(delay)
|
| 87 |
+
delay *= 2 # Exponential backoff
|
| 88 |
+
else:
|
| 89 |
+
raise Exception(f"All {retries} attempts failed.") from e
|
| 90 |
|
| 91 |
+
# Example usage
|
| 92 |
+
# asyncio.run(process_message_with_retry("1234567890", "hello", 1700424056000))
|