ragV98 commited on
Commit
a6c6341
·
1 Parent(s): 3eb899a
components/gateways/headlines_to_wa.py CHANGED
@@ -4,13 +4,12 @@ import redis
4
  import requests
5
  from fastapi import FastAPI
6
  from fastapi.responses import JSONResponse
7
- import logging
8
 
9
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
 
11
  # 🌐 Redis config
12
  REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379")
13
- # <<< CHANGE 1: Update the API URL to match the curl template >>>
14
  WHATSAPP_API_URL = os.environ.get("WHATSAPP_API_URL", "https://api.gupshup.io/wa/api/v1/msg")
15
  WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN")
16
  WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER") # e.g., "91xxxxxxxxxx"
@@ -29,6 +28,8 @@ except Exception as e:
29
  # 🧾 Fetch and format headlines
30
  def fetch_cached_headlines() -> str:
31
  try:
 
 
32
  raw = redis_client.get("detailed_news_feed_cache")
33
  if not raw:
34
  logging.warning("⚠️ No detailed news headlines found in cache.")
@@ -47,7 +48,7 @@ def fetch_cached_headlines() -> str:
47
  title = topic_key.replace("_", " ").title()
48
  message_parts.append(f"🏷️ *{title}*")
49
 
50
- sorted_story_ids = sorted(stories.keys(), key=int)
51
 
52
  for ref_id in sorted_story_ids:
53
  item = stories[ref_id]
@@ -67,16 +68,17 @@ def send_to_whatsapp(message_text: str) -> dict:
67
  logging.error(error_msg)
68
  return {"status": "failed", "error": error_msg, "code": 500}
69
 
 
70
  headers = {
71
  "Content-Type": "application/x-www-form-urlencoded",
72
  "apikey": WHATSAPP_TOKEN, # API key in 'apikey' header
73
- "Cache-Control": "no-cache" # <<< CHANGE 2: Add Cache-Control header
74
  }
75
 
76
  payload = {
77
  "channel": "whatsapp",
78
  "source": GUPSHUP_SOURCE_NUMBER,
79
- "destination": WHATSAPP_TO_NUMBER, # Ensure this holds the full number, not just '91'
80
  "message": json.dumps({
81
  "type": "text",
82
  "text": message_text
@@ -87,7 +89,7 @@ def send_to_whatsapp(message_text: str) -> dict:
87
  try:
88
  logging.info(f"Attempting to send WhatsApp message to {WHATSAPP_TO_NUMBER} via Gupshup. API URL: {WHATSAPP_API_URL}")
89
  response = requests.post(
90
- WHATSAPP_API_URL, # Uses the updated URL
91
  headers=headers,
92
  data=payload, # requests will correctly url-encode this dict
93
  )
@@ -119,12 +121,22 @@ def send_daily_whatsapp_digest():
119
  logging.info("✅ WhatsApp message sent successfully.")
120
  return JSONResponse(status_code=200, content=result)
121
  else:
122
- logging.error(f"❌ Failed to send WhatsApp message: {result.get("error")}")
123
  return JSONResponse(status_code=result.get("code", 500), content=result)
124
 
125
  # 🧪 For local testing
126
  if __name__ == "__main__":
127
-
 
 
 
 
 
 
 
 
 
 
128
  dummy_cached_detailed_feed = {
129
  "india": {
130
  "1": {"title": "India's Economy Surges", "description": "Rapid growth in manufacturing and services sectors signals a strong economic recovery, boosting investor confidence and job creation.", "sources": ["Times of India"]},
@@ -144,5 +156,6 @@ if __name__ == "__main__":
144
  print(msg_preview)
145
 
146
  logging.info("\n--- Sending WhatsApp Message (Test) ---\n")
 
147
  test_result = send_to_whatsapp(msg_preview)
148
  print(test_result)
 
4
  import requests
5
  from fastapi import FastAPI
6
  from fastapi.responses import JSONResponse
7
+ import logging # Import logging for better output
8
 
9
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
10
 
11
  # 🌐 Redis config
12
  REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379")
 
13
  WHATSAPP_API_URL = os.environ.get("WHATSAPP_API_URL", "https://api.gupshup.io/wa/api/v1/msg")
14
  WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN")
15
  WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER") # e.g., "91xxxxxxxxxx"
 
28
  # 🧾 Fetch and format headlines
29
  def fetch_cached_headlines() -> str:
30
  try:
31
+ # Assuming 'detailed_news_feed_cache' is the key for the final detailed headlines
32
+ # This key should match what's used in components/generators/detailed_explainer.py
33
  raw = redis_client.get("detailed_news_feed_cache")
34
  if not raw:
35
  logging.warning("⚠️ No detailed news headlines found in cache.")
 
48
  title = topic_key.replace("_", " ").title()
49
  message_parts.append(f"🏷️ *{title}*")
50
 
51
+ sorted_story_ids = sorted(stories.keys(), key=int) # Ensure keys are treated as integers for sorting
52
 
53
  for ref_id in sorted_story_ids:
54
  item = stories[ref_id]
 
68
  logging.error(error_msg)
69
  return {"status": "failed", "error": error_msg, "code": 500}
70
 
71
+ # Gupshup requires the API key in the 'apikey' header
72
  headers = {
73
  "Content-Type": "application/x-www-form-urlencoded",
74
  "apikey": WHATSAPP_TOKEN, # API key in 'apikey' header
75
+ "Cache-Control": "no-cache" # Add Cache-Control header
76
  }
77
 
78
  payload = {
79
  "channel": "whatsapp",
80
  "source": GUPSHUP_SOURCE_NUMBER,
81
+ "destination": WHATSAPP_TO_NUMBER, # Ensure this holds the full number
82
  "message": json.dumps({
83
  "type": "text",
84
  "text": message_text
 
89
  try:
90
  logging.info(f"Attempting to send WhatsApp message to {WHATSAPP_TO_NUMBER} via Gupshup. API URL: {WHATSAPP_API_URL}")
91
  response = requests.post(
92
+ WHATSAPP_API_URL,
93
  headers=headers,
94
  data=payload, # requests will correctly url-encode this dict
95
  )
 
121
  logging.info("✅ WhatsApp message sent successfully.")
122
  return JSONResponse(status_code=200, content=result)
123
  else:
124
+ logging.error(f"❌ Failed to send WhatsApp message: {result.get('error')}")
125
  return JSONResponse(status_code=result.get("code", 500), content=result)
126
 
127
  # 🧪 For local testing
128
  if __name__ == "__main__":
129
+ # --- IMPORTANT: For local testing, ensure these environment variables are set
130
+ # in your shell, via a .env file, or your IDE's configuration.
131
+ # Example:
132
+ # export WHATSAPP_API_URL="https://api.gupshup.io/wa/api/v1/msg"
133
+ # export WHATSAPP_TOKEN="YOUR_GUPSHUP_API_KEY"
134
+ # export WHATSAPP_TO_NUMBER="919999999999"
135
+ # export GUPSHUP_SOURCE_NUMBER="15557926439"
136
+ # export GUPSHUP_APP_NAME="NuseAI"
137
+ # -----------------------------------------------------------------------------
138
+
139
+ # Simulate a cached detailed feed for testing
140
  dummy_cached_detailed_feed = {
141
  "india": {
142
  "1": {"title": "India's Economy Surges", "description": "Rapid growth in manufacturing and services sectors signals a strong economic recovery, boosting investor confidence and job creation.", "sources": ["Times of India"]},
 
156
  print(msg_preview)
157
 
158
  logging.info("\n--- Sending WhatsApp Message (Test) ---\n")
159
+ # This will attempt to send a real message if your env vars are valid
160
  test_result = send_to_whatsapp(msg_preview)
161
  print(test_result)