ragV98 commited on
Commit
64ef9f2
Β·
1 Parent(s): 994a0a2

new endpoint

Browse files
Files changed (2) hide show
  1. app.py +3 -1
  2. components/gateways/headlines_to_wa.py +81 -0
app.py CHANGED
@@ -19,6 +19,7 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "rout
19
  from routes.api import ingest as ingest_router_module
20
  from routes.api import descriptive as descriptive_router_module
21
  from routes.api import headlines as headlines_router_module
 
22
  # query.py is ignored as per your instruction
23
 
24
  # Configure basic logging for the application
@@ -48,4 +49,5 @@ def greet():
48
  # Include your routers with specific prefixes and tags
49
  app.include_router(ingest_router_module.router, prefix="/api/ingest", tags=["Data Ingestion & Summaries"])
50
  app.include_router(descriptive_router_module.router, prefix="/api/descriptive", tags=["Detailed Explanations"])
51
- app.include_router(headlines_router_module.router, prefix="/api/headlines", tags=["Headlines (Placeholder)"])
 
 
19
  from routes.api import ingest as ingest_router_module
20
  from routes.api import descriptive as descriptive_router_module
21
  from routes.api import headlines as headlines_router_module
22
+ from components.gateways.headlines_to_wa import send_digest as wa_digest
23
  # query.py is ignored as per your instruction
24
 
25
  # Configure basic logging for the application
 
49
  # Include your routers with specific prefixes and tags
50
  app.include_router(ingest_router_module.router, prefix="/api/ingest", tags=["Data Ingestion & Summaries"])
51
  app.include_router(descriptive_router_module.router, prefix="/api/descriptive", tags=["Detailed Explanations"])
52
+ app.include_router(headlines_router_module.router, prefix="/api/headlines", tags=["Headlines (Placeholder)"])
53
+ app.include_router(wa_digest, prefix="/api/wa-digest", tags=["Headlines (Placeholder)"])
components/gateways/headlines_to_wa.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import redis
4
+ import requests
5
+ from fastapi import FastAPI
6
+ from fastapi.responses import JSONResponse
7
+
8
+ # 🌐 Redis config
9
+ REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379")
10
+ 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"
11
+ WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN", "sk_e73f674b797549ed80c85105ded5a0d1") # Bearer token
12
+ WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER") # e.g., "91xxxxxxxxxx"
13
+
14
+ # Connect to Redis
15
+ redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
16
+
17
+ app = FastAPI()
18
+
19
+ # 🧾 Load and format cache
20
+ def fetch_cached_headlines() -> str:
21
+ try:
22
+ raw = redis_client.get("daily_news_headline_json") # assuming this is your cache key
23
+ if not raw:
24
+ return "⚠️ No daily headlines found in cache."
25
+ data = json.loads(raw)
26
+ except Exception as e:
27
+ return f"❌ Error reading from Redis: {e}"
28
+
29
+ message = ["πŸ—žοΈ *Your Daily Digest* 🟑\n"]
30
+ for topic, stories in data.items():
31
+ title = topic.replace("_", " ").title()
32
+ message.append(f"🏷️ *{title}*")
33
+ for ref, item in stories.items():
34
+ summary = item.get("summary", "")
35
+ explanation = item.get("explanation", "")
36
+ message.append(f"{ref}. {summary}\n_Why this matters_: {explanation}")
37
+ message.append("") # newline between sections
38
+
39
+ return "\n".join(message)
40
+
41
+ # πŸš€ Send WhatsApp message
42
+ def send_to_whatsapp(message_text: str):
43
+ headers = {
44
+ "Authorization": f"Bearer {WHATSAPP_TOKEN}",
45
+ "Content-Type": "application/json"
46
+ }
47
+
48
+ payload = {
49
+ "messaging_product": "whatsapp",
50
+ "to": "353899495777",
51
+ "type": "text",
52
+ "text": {
53
+ "preview_url": False,
54
+ "body": message_text
55
+ }
56
+ }
57
+
58
+ response = requests.post(WHATSAPP_API_URL, headers=headers, json=payload)
59
+
60
+ if response.status_code == 200:
61
+ print("βœ… Message sent successfully.")
62
+ else:
63
+ print(f"❌ Failed to send message: {response.status_code}")
64
+ print(response.text)
65
+
66
+ # πŸ§ͺ Entrypoint
67
+ if __name__ == "__main__":
68
+ message = fetch_cached_headlines()
69
+ print("--- WhatsApp Message Preview ---\n")
70
+ print(message)
71
+ send_to_whatsapp(message)
72
+
73
+ # πŸ”Œ Endpoint to trigger sending
74
+ @app.post("/send-digest")
75
+ def send_digest():
76
+ message = fetch_cached_headlines()
77
+ if not message:
78
+ return JSONResponse(status_code=404, content={"error": "No digest found in cache."})
79
+
80
+ result = send_to_whatsapp(message)
81
+ return result