fastAPIv2 / components /gateways /headlines_to_wa.py
ragV98's picture
gupshup integration
1c8e081
raw
history blame
3.02 kB
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)