import os import time import praw import logging from dotenv import load_dotenv # Load environment variables load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '..', '.env')) # Initialize logging (optional: configure this in your app entrypoint) logging.basicConfig(level=logging.INFO) # Load multiple Reddit clients clients = [] for i in range(1, 4): cid = os.getenv(f"REDDIT_CLIENT_ID_{i}") csecret = os.getenv(f"REDDIT_CLIENT_SECRET_{i}") agent = os.getenv(f"REDDIT_USER_AGENT_{i}") if cid and csecret and agent: try: reddit = praw.Reddit( client_id=cid, client_secret=csecret, user_agent=agent ) reddit.read_only = True clients.append(reddit) except Exception as e: logging.error(f"Failed to initialize Reddit client #{i}: {e}") if not clients: raise ValueError("❌ No valid Reddit clients loaded from environment variables.") # Rotate between clients to avoid rate limits def get_reddit_client(): return clients[int(time.time()) % len(clients)] # Main function to search Reddit def search_reddit(brand, limit=10, retries=3): """ Search Reddit for a given brand keyword. Args: brand (str): Keyword to search. limit (int): Number of posts to fetch. Default is 10. retries (int): Retry attempts in case of failure. Returns: list: List of PRAW submission objects. """ for attempt in range(retries): try: reddit = get_reddit_client() posts = list( reddit.subreddit("all").search( brand, sort="new", limit=limit ) ) logging.info(f"✅ Fetched {len(posts)} Reddit posts for brand: {brand}") return posts except Exception as e: logging.warning(f"[Retry {attempt + 1}/{retries}] Reddit search failed: {e}") time.sleep(2) logging.error(f"❌ All retries failed for brand '{brand}'") return []