ragV98 commited on
Commit
1c8e081
Β·
1 Parent(s): 714bcf5

gupshup integration

Browse files
components/gateways/headlines_to_wa.py CHANGED
@@ -2,20 +2,24 @@ import os
2
  import json
3
  import redis
4
  import requests
 
 
5
 
6
  # 🌐 Redis config
7
  REDIS_URL = os.environ.get("UPSTASH_REDIS_URL", "redis://localhost:6379")
8
- 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"
9
- WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN", "sk_e73f674b797549ed80c85105ded5a0d1") # Bearer token
10
- WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER") # e.g., "91xxxxxxxxxx"
 
 
11
 
12
- # Connect to Redis
13
  redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
14
 
15
- # 🧾 Load and format cache
16
  def fetch_cached_headlines() -> str:
17
  try:
18
- raw = redis_client.get("daily_news_headline_json") # assuming this is your cache key
19
  if not raw:
20
  return "⚠️ No daily headlines found in cache."
21
  data = json.loads(raw)
@@ -30,38 +34,56 @@ def fetch_cached_headlines() -> str:
30
  summary = item.get("summary", "")
31
  explanation = item.get("explanation", "")
32
  message.append(f"{ref}. {summary}\n_Why this matters_: {explanation}")
33
- message.append("") # newline between sections
34
 
35
  return "\n".join(message)
36
 
37
- # πŸš€ Send WhatsApp message
38
- def send_to_whatsapp(message_text: str):
39
  headers = {
40
- "Authorization": f"Bearer {WHATSAPP_TOKEN}",
41
- "Content-Type": "application/json"
42
  }
43
 
44
  payload = {
45
- "messaging_product": "whatsapp",
46
- "to": "353899495777",
47
- "type": "text",
48
- "text": {
49
- "preview_url": False,
50
- "body": message_text
51
- }
 
52
  }
53
 
54
- response = requests.post(WHATSAPP_API_URL, headers=headers, json=payload)
 
 
 
 
 
55
 
56
  if response.status_code == 200:
57
- print("βœ… Message sent successfully.")
58
  else:
59
- print(f"❌ Failed to send message: {response.status_code}")
60
- print(response.text)
61
 
62
- # πŸ§ͺ Entrypoint
63
- if __name__ == "__main__":
 
 
 
64
  message = fetch_cached_headlines()
 
 
 
 
 
 
 
 
 
 
65
  print("--- WhatsApp Message Preview ---\n")
66
- print(message)
67
- send_to_whatsapp(message)
 
 
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/sm/api/v1/msg")
11
+ WHATSAPP_TOKEN = os.environ.get("WHATSAPP_TOKEN", "sk_e73f674b797549ed80c85105ded5a0d1")
12
+ WHATSAPP_TO_NUMBER = os.environ.get("WHATSAPP_TO_NUMBER", "353899495777") # e.g., "91xxxxxxxxxx"
13
+ GUPSHUP_SOURCE_NUMBER = os.environ.get("GUPSHUP_SOURCE_NUMBER", "+1 555-792-6439") # e.g., your WABA number
14
+ GUPSHUP_APP_NAME = os.environ.get("GUPSHUP_APP_NAME", "NuseAI") # e.g., your Gupshup app name
15
 
16
+ # βœ… Redis connection
17
  redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
18
 
19
+ # 🧾 Fetch and format headlines
20
  def fetch_cached_headlines() -> str:
21
  try:
22
+ raw = redis_client.get("daily_news_headline_json")
23
  if not raw:
24
  return "⚠️ No daily headlines found in cache."
25
  data = json.loads(raw)
 
34
  summary = item.get("summary", "")
35
  explanation = item.get("explanation", "")
36
  message.append(f"{ref}. {summary}\n_Why this matters_: {explanation}")
37
+ message.append("") # spacing between sections
38
 
39
  return "\n".join(message)
40
 
41
+ # πŸ“€ Send via Gupshup WhatsApp API
42
+ def send_to_whatsapp(message_text: str) -> dict:
43
  headers = {
44
+ "Content-Type": "application/x-www-form-urlencoded"
 
45
  }
46
 
47
  payload = {
48
+ "channel": "whatsapp",
49
+ "source": GUPSHUP_SOURCE_NUMBER,
50
+ "destination": WHATSAPP_TO_NUMBER,
51
+ "message": json.dumps({
52
+ "type": "text",
53
+ "text": message_text
54
+ }),
55
+ "src.name": GUPSHUP_APP_NAME,
56
  }
57
 
58
+ response = requests.post(
59
+ WHATSAPP_API_URL,
60
+ headers=headers,
61
+ data=payload,
62
+ auth=(WHATSAPP_TOKEN, '') # Gupshup uses Basic Auth (API key as username)
63
+ )
64
 
65
  if response.status_code == 200:
66
+ return {"status": "success", "details": response.json()}
67
  else:
68
+ return {"status": "failed", "error": response.text, "code": response.status_code}
 
69
 
70
+ # πŸš€ FastAPI App
71
+ app = FastAPI()
72
+
73
+ @app.get("/send-daily-whatsapp")
74
+ def send_daily_whatsapp_digest():
75
  message = fetch_cached_headlines()
76
+
77
+ if message.startswith("❌") or message.startswith("⚠️"):
78
+ return JSONResponse(status_code=404, content={"error": message})
79
+
80
+ result = send_to_whatsapp(message)
81
+ return result
82
+
83
+ # πŸ§ͺ For local testing
84
+ if __name__ == "__main__":
85
+ msg = fetch_cached_headlines()
86
  print("--- WhatsApp Message Preview ---\n")
87
+ print(msg)
88
+ result = send_to_whatsapp(msg)
89
+ print(result)