|
import os |
|
import json |
|
import redis |
|
import requests |
|
from fastapi import FastAPI |
|
from fastapi.responses import JSONResponse |
|
import logging |
|
|
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') |
|
|
|
|
|
|
|
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") |
|
WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN") |
|
WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER", "353899495777") |
|
GUPSHUP_SOURCE_NUMBER = os.environ.get("GUPSHUP_SOURCE_NUMBER") |
|
GUPSHUP_APP_NAME = os.environ.get("GUPSHUP_APP_NAME") |
|
|
|
|
|
try: |
|
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True) |
|
redis_client.ping() |
|
logging.info("Redis client connected successfully.") |
|
except Exception as e: |
|
logging.error(f"β Failed to connect to Redis: {e}") |
|
raise |
|
|
|
|
|
def fetch_cached_headlines() -> str: |
|
try: |
|
raw = redis_client.get("detailed_news_feed_cache") |
|
if not raw: |
|
logging.warning("β οΈ No detailed news headlines found in cache.") |
|
return "β οΈ No daily headlines found in cache." |
|
data = json.loads(raw) |
|
except Exception as e: |
|
logging.error(f"β Error reading from Redis: {e}") |
|
return f"β Error reading from Redis: {e}" |
|
|
|
message_parts = ["ποΈ *Your Daily Digest* π‘\n"] |
|
|
|
sorted_topics = sorted(data.keys()) |
|
|
|
for topic_key in sorted_topics: |
|
stories = data[topic_key] |
|
title = topic_key.replace("_", " ").title() |
|
message_parts.append(f"\nπ·οΈ *{title}*") |
|
|
|
sorted_story_ids = sorted(stories.keys(), key=int) |
|
|
|
for ref_id in sorted_story_ids: |
|
item = stories[ref_id] |
|
summary = item.get("title", "") |
|
description = item.get("description", "") |
|
|
|
message_parts.append(f"{ref_id}. {summary}\n_Why this matters_: {description}") |
|
|
|
|
|
return "\n".join(message_parts) |
|
|
|
|
|
def send_to_whatsapp(message_text: str) -> dict: |
|
|
|
if not WHATSAPP_TOKEN or \ |
|
not WHATSAPP_TO_NUMBER or \ |
|
not GUPSHUP_SOURCE_NUMBER or \ |
|
not GUPSHUP_APP_NAME: |
|
error_msg = "β Missing one or more critical WhatsApp API environment variables (WHATSAPP_TOKEN, WHATSAPP_TO_NUMBER, GUPSHUP_SOURCE_NUMBER, GUPSHUP_APP_NAME)." |
|
logging.error(error_msg) |
|
return {"status": "failed", "error": error_msg, "code": 500} |
|
|
|
headers = { |
|
"Content-Type": "application/x-www-form-urlencoded", |
|
"apikey": WHATSAPP_TOKEN, |
|
"Cache-Control": "no-cache" |
|
} |
|
|
|
whatsapp_message_content = { |
|
"type": "text", |
|
"text": message_text |
|
} |
|
|
|
payload = { |
|
"channel": "whatsapp", |
|
"source": GUPSHUP_SOURCE_NUMBER, |
|
"destination": WHATSAPP_TO_NUMBER, |
|
"src.name": GUPSHUP_APP_NAME, |
|
"message": json.dumps(whatsapp_message_content) |
|
} |
|
|
|
try: |
|
logging.info(f"Attempting to send standard text WhatsApp message to {WHATSAPP_TO_NUMBER} via Gupshup. API URL: {WHATSAPP_API_URL}") |
|
response = requests.post( |
|
WHATSAPP_API_URL, |
|
headers=headers, |
|
data=payload, |
|
) |
|
response.raise_for_status() |
|
|
|
return {"status": "success", "details": response.json()} |
|
except requests.exceptions.RequestException as e: |
|
logging.error(f"β Failed to send WhatsApp message: {e}") |
|
return {"status": "failed", "error": str(e), "code": e.response.status_code if e.response else 500} |
|
except Exception as e: |
|
logging.error(f"β An unexpected error occurred during WhatsApp send: {e}") |
|
return {"status": "failed", "error": str(e), "code": 500} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|