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/wa/api/v1/msg") # e.g. "https://graph.facebook.com/v18.0/PHONE_NUMBER_ID/messages" WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN", "sk_e73f674b797549ed80c85105ded5a0d1") # Bearer token WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER") # e.g., "91xxxxxxxxxx" # Connect to Redis redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True) app = FastAPI() # ๐Ÿงพ Load and format cache def fetch_cached_headlines() -> str: try: raw = redis_client.get("daily_news_headline_json") # assuming this is your cache key 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("") # newline between sections return "\n".join(message) # ๐Ÿš€ Send WhatsApp message def send_to_whatsapp(message_text: str): headers = { "Authorization": f"Bearer {WHATSAPP_TOKEN}", "Content-Type": "application/json" } payload = { "messaging_product": "whatsapp", "to": "353899495777", "type": "text", "text": { "preview_url": False, "body": message_text } } response = requests.post(WHATSAPP_API_URL, headers=headers, json=payload) if response.status_code == 200: print("โœ… Message sent successfully.") else: print(f"โŒ Failed to send message: {response.status_code}") print(response.text) # ๐Ÿงช Entrypoint if __name__ == "__main__": message = fetch_cached_headlines() print("--- WhatsApp Message Preview ---\n") print(message) send_to_whatsapp(message)