|
import os |
|
import json |
|
import redis |
|
import requests |
|
from fastapi import FastAPI |
|
from fastapi.responses import JSONResponse |
|
|
|
|
|
REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379") |
|
WHATSAPP_API_URL = os.environ.get("WHATSAPP_API_URL", "https://api.gupshup.io/sm/api/v1/msg") |
|
WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN", "sk_e73f674b797549ed80c85105ded5a0d1") |
|
WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER", "353899495777") |
|
GUPSHUP_SOURCE_NUMBER = os.environ.get("GUPSHUP_SOURCE_NUMBER", "+1 555-792-6439") |
|
GUPSHUP_APP_NAME = os.environ.get("GUPSHUP_APP_NAME", "NuseAI") |
|
|
|
|
|
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True) |
|
|
|
|
|
def fetch_cached_headlines() -> str: |
|
try: |
|
raw = redis_client.get("daily_news_headline_json") |
|
if not raw: |
|
return "β οΈ No daily headlines found in cache." |
|
data = json.loads(raw) |
|
except Exception as e: |
|
return f"β Error reading from Redis: {e}" |
|
|
|
message = ["ποΈ *Your Daily Digest* π‘\n"] |
|
for topic, stories in data.items(): |
|
title = topic.replace("_", " ").title() |
|
message.append(f"π·οΈ *{title}*") |
|
for ref, item in stories.items(): |
|
summary = item.get("summary", "") |
|
explanation = item.get("explanation", "") |
|
message.append(f"{ref}. {summary}\n_Why this matters_: {explanation}") |
|
message.append("") |
|
|
|
return "\n".join(message) |
|
|
|
|
|
def send_to_whatsapp(message_text: str) -> dict: |
|
headers = { |
|
"Content-Type": "application/x-www-form-urlencoded" |
|
} |
|
|
|
payload = { |
|
"channel": "whatsapp", |
|
"source": GUPSHUP_SOURCE_NUMBER, |
|
"destination": WHATSAPP_TO_NUMBER, |
|
"message": json.dumps({ |
|
"type": "text", |
|
"text": message_text |
|
}), |
|
"src.name": GUPSHUP_APP_NAME, |
|
} |
|
|
|
response = requests.post( |
|
WHATSAPP_API_URL, |
|
headers=headers, |
|
data=payload, |
|
auth=(WHATSAPP_TOKEN, '') |
|
) |
|
|
|
if response.status_code == 200: |
|
return {"status": "success", "details": response.json()} |
|
else: |
|
return {"status": "failed", "error": response.text, "code": response.status_code} |
|
|
|
|
|
app = FastAPI() |
|
|
|
@app.get("/send-daily-whatsapp") |
|
def send_daily_whatsapp_digest(): |
|
message = fetch_cached_headlines() |
|
|
|
if message.startswith("β") or message.startswith("β οΈ"): |
|
return JSONResponse(status_code=404, content={"error": message}) |
|
|
|
result = send_to_whatsapp(message) |
|
return result |
|
|
|
|
|
if __name__ == "__main__": |
|
msg = fetch_cached_headlines() |
|
print("--- WhatsApp Message Preview ---\n") |
|
print(msg) |
|
result = send_to_whatsapp(msg) |
|
print(result) |
|
|