File size: 3,017 Bytes
64ef9f2
 
 
 
1c8e081
 
64ef9f2
 
 
1c8e081
 
 
 
 
64ef9f2
1c8e081
64ef9f2
 
1c8e081
64ef9f2
 
1c8e081
64ef9f2
 
 
 
 
 
 
 
 
 
 
 
 
 
1c8e081
64ef9f2
 
 
1c8e081
 
64ef9f2
1c8e081
64ef9f2
 
 
1c8e081
 
 
 
 
 
 
 
64ef9f2
 
1c8e081
 
 
 
 
 
64ef9f2
 
1c8e081
64ef9f2
1c8e081
64ef9f2
1c8e081
 
 
 
 
64ef9f2
1c8e081
 
 
 
 
 
 
 
 
 
64ef9f2
1c8e081
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import os
import json
import redis
import requests
from fastapi import FastAPI
from fastapi.responses import JSONResponse

# 🌐 Redis config
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")  # e.g., "91xxxxxxxxxx"
GUPSHUP_SOURCE_NUMBER = os.environ.get("GUPSHUP_SOURCE_NUMBER", "+1 555-792-6439")  # e.g., your WABA number
GUPSHUP_APP_NAME = os.environ.get("GUPSHUP_APP_NAME", "NuseAI")  # e.g., your Gupshup app name

# βœ… Redis connection
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)

# 🧾 Fetch and format headlines
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("")  # spacing between sections

    return "\n".join(message)

# πŸ“€ Send via Gupshup WhatsApp API
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, '')  # Gupshup uses Basic Auth (API key as username)
    )

    if response.status_code == 200:
        return {"status": "success", "details": response.json()}
    else:
        return {"status": "failed", "error": response.text, "code": response.status_code}

# πŸš€ FastAPI App
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

# πŸ§ͺ For local testing
if __name__ == "__main__":
    msg = fetch_cached_headlines()
    print("--- WhatsApp Message Preview ---\n")
    print(msg)
    result = send_to_whatsapp(msg)
    print(result)