Spaces:
Sleeping
Sleeping
Update main.py
Browse files12345630 unmodified lines37383940414243444516 unmodified lines62636465666768697071727317 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412528 unmodified lines15415515615715815916016145 unmodified lines2072082092102112122 unmodified lines2152162172182192202215 unmodified lines2272282292302312322 unmodified lines2352362372382392402412422432442452462472482492502512522532542552563 unmodified lines2602612622632642652662672682692702712722732749 unmodified lines2842852862872882892904 unmodified lines2952962972982993003014 unmodified lines30630730830931031131213 unmodified lines3263273283293303313326 unmodified lines33934034134234334434537 unmodified lines3833843853863873883893903913923933943953963973983994004014024034044054064074084094104114127 unmodified lines4204214224234244254264 unmodified lines4314324334344354364374384394404414424432 unmodified lines44644744844945045145245345445545645711 unmodified lines4694704714724734744754 unmodified lines4804814824834844854864874884894904911 unmodified line49349449549649749849916 unmodified lines5165175185195205215225235245255262 unmodified lines5295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725731 unmodified line5755765775785795805815 unmodified lines5875885895905915925935945952 unmodified lines5985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426433 unmodified lines6476486496506516526536546555 unmodified lines6616626636646656666676686693 unmodified lines6736746756766776786796806816826836846856866872 unmodified lines6906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357362 unmodified lines7397407417427437447457467477487497507517527537547555 unmodified lines7617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917921 unmodified line794795796797798799800801802803804805# --- START OF FILE main.py ---# main.pyfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel30 unmodified lines# Google Sheets Config# Spreadsheet containing Scammer and DWC infoSCAMMER_DWC_SPREADSHEET_ID = '1sgkhBNGw_r6tBIxvdeXaI0bVmWBeACN4jiw_oDEeXLw'# Spreadsheet containing Value lists and Dupe listVALUES_DUPE_SPREADSHEET_ID = '1Toe07o3P517q8sm9Qb1e5xyFWCuwgskj71IKJwJNfNU'SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']16 unmodified linesVALUES_RANGE = 'B6:P' # Range within each category sheet# Cache Update IntervalCACHE_UPDATE_INTERVAL_SECONDS = 60 * 5 # 5 minutes# --- Global Cache ---cache = {"values": {}, # Dict mapping category name to list of items"value_changes": {}, # Dict mapping category name to list of changes"user_scammers": [],"server_scammers": [],"dwc": [],17 unmodified linesreturn namedef init_google_sheets(scopes=SCOPES):"""Initialize Google Sheets credentials from environment variable"""global sheets_service, cachetry:creds_json_str = os.getenv('CREDENTIALS_JSON')if not creds_json_str:logger.error("CREDENTIALS_JSON environment variable not found")raise ValueError("CREDENTIALS_JSON environment variable not found")creds_json = json.loads(creds_json_str)creds = ServiceAccountCredentials.from_service_account_info(creds_json,scopes=scopes)sheets_service = build('sheets', 'v4', credentials=creds, cache_discovery=False) # Disable discovery cachelogger.info("Google Sheets service initialized successfully from ENV VAR.")cache["service_available"] = Truereturn sheets_serviceexcept Exception as e:logger.error(f"Error initializing Google Sheets from ENV VAR: {e}")# Fallback attempttry:logger.info("Falling back to loading credentials from file 'credentials.json'")creds = ServiceAccountCredentials.from_service_account_file('credentials.json',scopes=scopes)sheets_service = build('sheets', 'v4', credentials=creds, cache_discovery=False)logger.info("Google Sheets service initialized successfully from file.")cache["service_available"] = Truereturn sheets_serviceexcept Exception as file_e:logger.error(f"Error loading credentials from file: {file_e}")logger.critical("Google Sheets service could not be initialized. API will be limited.")28 unmodified linesif formula.startswith('=IMAGE('):match = re.search(r'=IMAGE\("([^"]+)"', formula)if match: return match.group(1)# If it wasn't a formula or direct URL, and no drive_url, return empty or original?# Let's assume if it's not a recognizable URL/formula, it's not an image source.return '' # Return empty string if no valid URL founddef format_currency(value: Any) -> Optional[str]:45 unmodified linesdata = await response.json()if data and data.get("data") and len(data["data"]) > 0:return data["data"][0].get("id")return Noneexcept asyncio.TimeoutError:logger.warning(f"Timeout fetching Roblox User ID for {username}")2 unmodified lineslogger.warning(f"Network error fetching Roblox User ID for {username}: {e}")return Noneexcept Exception as e:logger.error(f"Unexpected exception fetching Roblox User ID for {username}: {e}")return Noneasync def get_roblox_avatar_url(session: aiohttp.ClientSession, user_id: int):5 unmodified linesdata = await response.json()if data and data.get("data") and len(data["data"]) > 0:return data["data"][0].get("imageUrl")return Noneexcept asyncio.TimeoutError:logger.warning(f"Timeout fetching Roblox avatar for User ID {user_id}")2 unmodified lineslogger.warning(f"Network error fetching Roblox avatar for User ID {user_id}: {e}")return Noneexcept Exception as e:logger.error(f"Unexpected exception fetching Roblox avatar for User ID {user_id}: {e}")return None# --- Data Processing Functions ---# These functions take raw rows from the sheet and process them.# They are now independent of *which* sheet they came from, as long as the structure matches.def process_sheet_data(values): # For Value Categoriesif not values: return []processed_data = []for row in values: # Expected range like B6:Pif not row or not any(str(cell).strip() for cell in row if cell is not None): continue# Indices based on B6:P (0-indexed from B)# B=0, C=1, D=2, E=3, F=4, G=5, H=6, I=7, J=8, K=9, L=10, M=11, N=12, O=13, P=14icon_formula = row[0] if len(row) > 0 else ''name = row[2] if len(row) > 2 else 'N/A'value_raw = row[4] if len(row) > 4 else 'N/A'3 unmodified linesnotes = row[12] if len(row) > 12 else ''drive_url = row[14] if len(row) > 14 else None # Column P# Skip header-like rows (e.g., "LEVEL 1 | HYPERCHROMES" in column F/index 4)if len(row) > 4 and isinstance(row[4], str) and re.search(r'LEVEL \d+ \|', row[4]):continueif clean_string(name) == 'N/A':continueprocessed_item = {'icon': extract_image_url(icon_formula, drive_url),'name': clean_string(name, 'N/A'),'value': format_currency(value_raw),'dupedValue': format_currency(duped_value_raw),'marketValue': format_currency(market_value_raw),9 unmodified linesfor row in values: # Expected range like B6:Gif not row or len(row) < 2: continue# Indices based on B6:G (0-indexed from B)# B=0, C=1, D=2, E=3, F=4, G=5discord_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Broblox_username = clean_string_optional(row[1]) if len(row) > 1 else None # Col Cif not discord_id and not roblox_username: continue4 unmodified lines'explanation': clean_string(row[3]) if len(row) > 3 else 'N/A', # Col E'evidence_link': clean_string_optional(row[4]) if len(row) > 4 else None, # Col F'alt_accounts': parse_alt_accounts(row[5]) if len(row) > 5 else [], # Col G'roblox_avatar_url': None}processed_data.append(processed_item)return processed_data4 unmodified linesfor row in values: # Expected range like B6:Fif not row or len(row) < 2: continue# Indices based on B6:F (0-indexed from B)# B=0, C=1, D=2, E=3, F=4server_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Bserver_name = clean_string_optional(row[1]) if len(row) > 1 else None # Col Cif not server_id and not server_name: continue13 unmodified linesfor row in values: # Expected range like B6:Gif not row or len(row) < 3: continue# Indices based on B6:G (0-indexed from B)# B=0, C=1, D=2, E=3, F=4, G=5user_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Bserver_id = clean_string_optional(row[1]) if len(row) > 1 else None # Col Croblox_user = clean_string_optional(row[2]) if len(row) > 2 else None # Col D6 unmodified lines'explanation': clean_string(row[3]) if len(row) > 3 else 'N/A', # Col E'evidence_link': clean_string_optional(row[4]) if len(row) > 4 else None, # Col F'alt_accounts': parse_alt_accounts(row[5]) if len(row) > 5 else [], # Col G'roblox_avatar_url': None}processed_data.append(processed_item)return processed_data37 unmodified linesstatus = error_details.get('status')message = error_details.get('message')logger.error(f"Google API HTTP Error during batch fetch for {spreadsheet_id}: Status={status}, Message={message}")raise eexcept Exception as e:logger.error(f"Error during batch fetching from {spreadsheet_id} for ranges {ranges}: {e}")raise e# --- Background Cache Update Task (Refactored for Batching per Spreadsheet) ---async def update_cache_periodically():"""Fetches data using batchGet per spreadsheet, processes, detects changes, and updates cache."""global cacheasync with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=25)) as session: # Slightly longer timeoutwhile True:if not cache["service_available"]:logger.info("Attempting to re-initialize Google Sheets service...")init_google_sheets()if not cache["service_available"]:logger.warning("Google Sheets service still unavailable, skipping cache update cycle.")await asyncio.sleep(CACHE_UPDATE_INTERVAL_SECONDS * 2)continueelse:logger.info("Google Sheets service re-initialized. Proceeding with cache update.")logger.info("Starting cache update cycle...")start_time = datetime.now(timezone.utc)# Prepare temporary storage for fetched datafetched_values_categories = {} # { "CategoryName": [items...] }7 unmodified linestry:# --- Define Ranges and Processors ---# Scammer/DWC Spreadsheetscammer_dwc_ranges = [f"{quote_sheet_name(USER_SCAMMER_SHEET)}!{USER_SCAMMER_RANGE}",f"{quote_sheet_name(SERVER_SCAMMER_SHEET)}!{SERVER_SCAMMER_RANGE}",4 unmodified linesSERVER_SCAMMER_SHEET: process_server_scammer_data,DWC_SHEET: process_dwc_data,}scammer_dwc_target_key_map = { # Map sheet name to cache keyUSER_SCAMMER_SHEET: "user_scammers",SERVER_SCAMMER_SHEET: "server_scammers",DWC_SHEET: "dwc",}# Values/Dupes Spreadsheetvalues_dupes_ranges = [f"{quote_sheet_name(DUPE_LIST_SHEET)}!{DUPE_LIST_RANGE}"]values_dupes_ranges.extend([f"{quote_sheet_name(cat)}!{VALUES_RANGE}" for cat in CATEGORIES])2 unmodified lines"scammer_dwc_batch": fetch_batch_ranges_async(SCAMMER_DWC_SPREADSHEET_ID,scammer_dwc_ranges,value_render_option='FORMATTED_VALUE' # These don't need formulas),"values_dupes_batch": fetch_batch_ranges_async(VALUES_DUPE_SPREADSHEET_ID,values_dupes_ranges,value_render_option='FORMATTED_VALUE' # These don't need formulas)}11 unmodified lineslogger.error(f"Failed to fetch batch data for {key}: {result}")current_errors[key] = str(result)else:# Store the raw valueRanges listif key == "scammer_dwc_batch":raw_scammer_dwc_results = resultelif key == "values_dupes_batch":4 unmodified lineslogger.info(f"Processing {len(raw_scammer_dwc_results)} valueRanges from Scammer/DWC sheet...")for vr in raw_scammer_dwc_results:range_str = vr.get('range', '')# Extract sheet name (handle quotes)match = re.match(r"^'?([^'!]+)'?!", range_str)if not match:logger.warning(f"Could not extract sheet name from range '{range_str}' in Scammer/DWC response.")continuesheet_name = match.group(1).replace("''", "'") # Unescape quotesif sheet_name in scammer_dwc_processor_map:processor = scammer_dwc_processor_map[sheet_name]1 unmodified linevalues = vr.get('values', [])try:processed_data = processor(values)new_cache_data[target_key] = processed_datalogger.info(f"Processed {len(processed_data)} items for {sheet_name} -> {target_key}")except Exception as e:logger.error(f"Error processing data for {sheet_name} using {processor.__name__}: {e}", exc_info=True)16 unmodified linestry:if sheet_name == DUPE_LIST_SHEET:processed_data = process_dupe_list_data(values)new_cache_data["dupes"] = processed_datalogger.info(f"Processed {len(processed_data)} items for {DUPE_LIST_SHEET} -> dupes")elif sheet_name in CATEGORIES:processed_data = process_sheet_data(values)fetched_values_categories[sheet_name] = processed_datalogger.info(f"Processed {len(processed_data)} items for Category: {sheet_name}")else:logger.warning(f"Unrecognized sheet name '{sheet_name}' derived from range '{range_str}' in Values/Dupes sheet.")2 unmodified lineslogger.error(f"Error processing data for {sheet_name}: {e}", exc_info=True)current_errors[f"process_{target_key}"] = str(e)# --- Detect Value Changes ---logger.info("Comparing fetched values with cached values...")current_time = datetime.now(timezone.utc)detected_value_changes = {}fields_to_compare = ['value', 'dupedValue', 'marketValue']if "values" not in cache: cache["values"] = {} # Ensure existsfor category, new_items in fetched_values_categories.items():old_items_dict = {item['name']: item for item in cache["values"].get(category, [])}category_changes = []for new_item in new_items:item_name = new_item.get('name')if not item_name or item_name == 'N/A': continueold_item = old_items_dict.get(item_name)if old_item: # Check existing item for changesfor field in fields_to_compare:old_val_str = old_item.get(field, 'N/A')new_val_str = new_item.get(field, 'N/A')old_norm = parse_cached_currency(old_val_str) if parse_cached_currency(old_val_str) is not None else old_val_strnew_norm = parse_cached_currency(new_val_str) if parse_cached_currency(new_val_str) is not None else new_val_strif old_norm != new_norm:logger.info(f"Change detected in {category}: {item_name} - {field}: '{old_val_str}' -> '{new_val_str}'")category_changes.append({"item_name": item_name, "field": field,"old_value": old_val_str if old_val_str is not None else "N/A","new_value": new_val_str if new_val_str is not None else "N/A","timestamp": current_time.isoformat()})if category_changes:detected_value_changes[category] = category_changes# --- Fetch Roblox Avatars ---logger.info("Fetching Roblox avatars...")avatar_tasks = []# Combine lists needing avatars (only user scammers and DWC have roblox usernames)entries_needing_avatars = new_cache_data.get("user_scammers", []) + new_cache_data.get("dwc", [])for entry in entries_needing_avatars:if entry.get('roblox_username'):1 unmodified lineavatar_tasks.append(fetch_avatar_for_entry_update(session, entry))if avatar_tasks:await asyncio.gather(*avatar_tasks) # Exceptions logged within helperlogger.info(f"Finished fetching avatars for {len(avatar_tasks)} potential entries.")# --- Final Cache Update ---5 unmodified linescache["server_scammers"] = new_cache_data["server_scammers"]cache["dwc"] = new_cache_data["dwc"]cache["dupes"] = new_cache_data["dupes"]cache["value_changes"] = detected_value_changescache["last_updated"] = current_timecache["is_ready"] = Trueupdate_occurred = Truelogger.info(f"Cache update cycle completed successfully.")else: # Errors occurred, attempt partial update2 unmodified lines# Update values only if the values/dupes batch succeeded AND processing succeededif "values_dupes_batch" not in current_errors and not any(k.startswith("process_values_") for k in current_errors):if cache["values"] != fetched_values_categories:cache["values"] = fetched_values_categoriescache["value_changes"] = detected_value_changes # Update changes along with valuespartial_update_details.append("values")update_occurred = True# Update dupes only if the values/dupes batch succeeded AND processing succeededif "values_dupes_batch" not in current_errors and "process_dupes" not in current_errors:if cache["dupes"] != new_cache_data["dupes"]:cache["dupes"] = new_cache_data["dupes"]partial_update_details.append("dupes")update_occurred = True# Update scammer/DWC sections if their batch succeeded AND processing succeededif "scammer_dwc_batch" not in current_errors:for key in ["user_scammers", "server_scammers", "dwc"]:process_error_key = f"process_{key}"if process_error_key not in current_errors:if cache[key] != new_cache_data[key]:cache[key] = new_cache_data[key]partial_update_details.append(key)update_occurred = Trueif update_occurred:cache["last_updated"] = current_time # Mark partial update timecache["is_ready"] = True # Allow access even if partiallogger.info(f"Partially updated cache sections: {', '.join(partial_update_details)}")else:logger.error(f"Cache update cycle failed, and no parts could be updated based on errors. Errors: {current_errors}")# Keep cache["is_ready"] as it was.except Exception as e:logger.exception(f"Critical error during cache update cycle: {e}")if isinstance(e, (aiohttp.ClientError, HttpError, asyncio.TimeoutError)):logger.warning("Communication error detected, will re-check service availability next cycle.")# --- Wait for the next cycle ---end_time = datetime.now(timezone.utc)duration = (end_time - start_time).total_seconds()wait_time = max(10, CACHE_UPDATE_INTERVAL_SECONDS - duration)logger.info(f"Cache update cycle duration: {duration:.2f}s. Waiting {wait_time:.2f}s for next cycle.")await asyncio.sleep(wait_time)3 unmodified linesroblox_username = entry.get('roblox_username')if not roblox_username: returncurrent_avatar = entry.get('roblox_avatar_url')new_avatar = None # Default to Nonetry:user_id = await get_roblox_user_id(session, roblox_username)if user_id:5 unmodified lines# Keep new_avatar as None on errorfinally:# Update the dict only if the value has actually changedif current_avatar != new_avatar:entry['roblox_avatar_url'] = new_avatar# --- FastAPI Startup Event ---3 unmodified linesif not cache["service_available"]:logger.warning("Google Sheets service not available at startup. Will attempt re-init in background task.")logger.info("Starting background cache update task...")asyncio.create_task(update_cache_periodically())# --- API Endpoints (Largely unchanged, rely on cache state) ---def check_cache_readiness():"""Reusable check for API endpoints - Checks cache readiness"""if not cache["is_ready"]:raise HTTPException(status_code=503, detail="Cache is initializing or data is currently unavailable. Please try again shortly.")@app.get("/")async def root():2 unmodified lines@app.get("/api/status")async def get_status():"""Returns the current status of the cache and service availability"""return {"cache_ready": cache["is_ready"],"sheets_service_available": cache["service_available"],"last_updated": cache["last_updated"].isoformat() if cache["last_updated"] else None,"cached_items": {"value_categories": len(cache["values"]),"user_scammers": len(cache["user_scammers"]),"server_scammers": len(cache["server_scammers"]),"dwc_entries": len(cache["dwc"]),"duped_usernames": len(cache["dupes"]),},"value_change_categories": len(cache.get("value_changes", {}))}@app.get("/api/values")async def get_values():"""Get all values data from cache"""check_cache_readiness()return cache["values"]@app.get("/api/values/{category}")async def get_category_values(category: str):"""Get values data for a specific category from cache"""check_cache_readiness()matched_category = next((c for c in CATEGORIES if c.lower() == category.lower()), None)if not matched_category:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")return {matched_category: cache["values"].get(matched_category, [])}@app.get("/api/value-changes/{category}")async def get_category_value_changes(category: str):"""Get detected value changes for a specific category."""check_cache_readiness()matched_category = next((c for c in CATEGORIES if c.lower() == category.lower()), None)if not matched_category:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")return {matched_category: cache.get("value_changes", {}).get(matched_category, [])}@app.get("/api/value-changes")async def get_all_value_changes():"""Get all detected value changes from the last cycle."""check_cache_readiness()return cache.get("value_changes", {})2 unmodified lines"""Get all scammer and DWC data (users, servers, dwc) from cache"""check_cache_readiness()return {"users": cache["user_scammers"],"servers": cache["server_scammers"],"dwc": cache["dwc"]}@app.get("/api/dupes")async def get_dupes():"""Get all duped usernames from cache"""check_cache_readiness()# Handle case where dupes might be None temporarily during init failurereturn {"usernames": cache.get("dupes") or []}class UsernameCheck(BaseModel):5 unmodified linescheck_cache_readiness() # Use the standard readiness checkusername_to_check = data.username.strip().lower()is_duped = username_to_check in (cache.get("dupes") or [])# Webhook notification (runs in background)if not is_duped:webhook_url = os.getenv("WEBHOOK_URL")if webhook_url:async def send_webhook_notification():try:async with aiohttp.ClientSession() as session:webhook_data = {"content": None,"embeds": [{"title": "New Dupe Check - Not Found","description": f"Username `{data.username}` was checked but not found in the dupe database.","color": 16776960, # Yellow"timestamp": datetime.now(timezone.utc).isoformat()}]}async with session.post(webhook_url, json=webhook_data) as response:if response.status not in [200, 204]:logger.warning(f"Failed to send webhook (Status: {response.status}): {await response.text()}")except Exception as e:logger.error(f"Error sending webhook: {e}")asyncio.create_task(send_webhook_notification())else:logger.info("Webhook URL not configured. Skipping notification.")return {"username": data.username, "is_duped": is_duped}1 unmodified line@app.get("/health")def health_check():"""Provides a health status of the API and its cache."""if not cache["is_ready"]:return {"status": "initializing"}if not cache["service_available"]:return {"status": "degraded", "reason": "Sheets service connection issue"}if cache["last_updated"] and (datetime.now(timezone.utc) - cache["last_updated"]).total_seconds() > CACHE_UPDATE_INTERVAL_SECONDS * 3:return {"status": "degraded", "reason": "Cache potentially stale (last update > 3 intervals ago)"}return {"status": "ok"}# --- END OF FILE main.py ---12330 unmodified lines34353637383940414216 unmodified lines596061626364656667686970717273747517 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513628 unmodified lines16516616716816917045 unmodified lines2162172182192202212222232 unmodified lines2262272282292302312325 unmodified lines2382392402412422432442452 unmodified lines2482492502512522532542552562572582592602612622632642652662672682692703 unmodified lines2742752762772782792802812822832842852869 unmodified lines2962972982993003014 unmodified lines3063073083093103113124 unmodified lines31731831932032132213 unmodified lines3363373383393403416 unmodified lines34834935035135235335437 unmodified lines3923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524537 unmodified lines4614624634644654664 unmodified lines4714724734744754764774784794804814822 unmodified lines48548648748848949049149249349449549611 unmodified lines5085095105115125134 unmodified lines5185195205215225235245255265275281 unmodified line53053153253353453553616 unmodified lines5535545555565575585595605615625632 unmodified lines5665675685695705715725735745751 unmodified line5775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317325 unmodified lines7387397407417427437447457467472 unmodified lines7507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088093 unmodified lines8138148158168178188195 unmodified lines8258268278288298308318323 unmodified lines8368378388398408418428438448458468478488498508518528538548558568578588598608618622 unmodified lines8658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229232 unmodified lines9269279289299309319329339349359369379389399409415 unmodified lines9479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789791 unmodified line981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014from fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel30 unmodified lines# Google Sheets Config# Spreadsheet containing Scammer and DWC infoSCAMMER_DWC_SPREADSHEET_ID = os.getenv('SCAMMER_DWC_SPREADSHEET_ID', '1sgkhBNGw_r6tBIxvdeXaI0bVmWBeACN4jiw_oDEeXLw')# Spreadsheet containing Value lists and Dupe listVALUES_DUPE_SPREADSHEET_ID = os.getenv('VALUES_DUPE_SPREADSHEET_ID', '1Toe07o3P517q8sm9Qb1e5xyFWCuwgskj71IKJwJNfNU')SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']16 unmodified linesVALUES_RANGE = 'B6:P' # Range within each category sheet# Cache Update IntervalCACHE_UPDATE_INTERVAL_SECONDS = int(os.getenv('CACHE_UPDATE_INTERVAL_SECONDS', 60 * 5)) # 5 minutes default# Webhook URLsSCAMMER_WEBHOOK_URL = os.getenv("SCAMMER_WEBHOOK_URL")VALUE_WEBHOOK_URL = os.getenv("VALUE_WEBHOOK_URL")# --- Global Cache ---cache = {"values": {}, # Dict mapping category name to list of items"value_changes": {}, # Dict mapping category name to list of recent changes (for API endpoint)"user_scammers": [],"server_scammers": [],"dwc": [],17 unmodified linesreturn namedef init_google_sheets(scopes=SCOPES):"""Initialize Google Sheets credentials from environment variable or file"""global sheets_service, cachetry:creds_json_str = os.getenv('CREDENTIALS_JSON')if creds_json_str:logger.info("Attempting to load credentials from CREDENTIALS_JSON environment variable.")creds_json = json.loads(creds_json_str)creds = ServiceAccountCredentials.from_service_account_info(creds_json,scopes=scopes)sheets_service = build('sheets', 'v4', credentials=creds, cache_discovery=False) # Disable discovery cachelogger.info("Google Sheets service initialized successfully from ENV VAR.")cache["service_available"] = Truereturn sheets_serviceelse:logger.info("CREDENTIALS_JSON environment variable not found. Falling back to file.")raise ValueError("CREDENTIALS_JSON not set") # Trigger fallback explicitlyexcept Exception as e:logger.warning(f"Error initializing Google Sheets from ENV VAR: {e}. Trying file...")try:# Fallback to loading credentials from file 'credentials.json'creds_file = 'credentials.json'if os.path.exists(creds_file):logger.info(f"Attempting to load credentials from file '{creds_file}'")creds = ServiceAccountCredentials.from_service_account_file(creds_file,scopes=scopes)sheets_service = build('sheets', 'v4', credentials=creds, cache_discovery=False)logger.info("Google Sheets service initialized successfully from file.")cache["service_available"] = Truereturn sheets_serviceelse:logger.error(f"Credentials file '{creds_file}' not found.")raise FileNotFoundError(f"'{creds_file}' not found")except Exception as file_e:logger.error(f"Error loading credentials from file: {file_e}")logger.critical("Google Sheets service could not be initialized. API will be limited.")28 unmodified linesif formula.startswith('=IMAGE('):match = re.search(r'=IMAGE\("([^"]+)"', formula)if match: return match.group(1)return '' # Return empty string if no valid URL founddef format_currency(value: Any) -> Optional[str]:45 unmodified linesdata = await response.json()if data and data.get("data") and len(data["data"]) > 0:return data["data"][0].get("id")else:logger.warning(f"Roblox API returned status {response.status} for username '{username}'")return Noneexcept asyncio.TimeoutError:logger.warning(f"Timeout fetching Roblox User ID for {username}")2 unmodified lineslogger.warning(f"Network error fetching Roblox User ID for {username}: {e}")return Noneexcept Exception as e:logger.error(f"Unexpected exception fetching Roblox User ID for {username}: {e}", exc_info=True)return Noneasync def get_roblox_avatar_url(session: aiohttp.ClientSession, user_id: int):5 unmodified linesdata = await response.json()if data and data.get("data") and len(data["data"]) > 0:return data["data"][0].get("imageUrl")else:logger.warning(f"Roblox Thumbnail API returned status {response.status} for user ID {user_id}")return Noneexcept asyncio.TimeoutError:logger.warning(f"Timeout fetching Roblox avatar for User ID {user_id}")2 unmodified lineslogger.warning(f"Network error fetching Roblox avatar for User ID {user_id}: {e}")return Noneexcept Exception as e:logger.error(f"Unexpected exception fetching Roblox avatar for User ID {user_id}: {e}", exc_info=True)return None# --- Data Processing Functions ---# These functions take raw rows from the sheet and process them.def process_sheet_data(values): # For Value Categoriesif not values: return []processed_data = []for row in values: # Expected range like B6:Pif not row or not any(str(cell).strip() for cell in row if cell is not None): continue# Skip header-like rows (e.g., "LEVEL 1 | HYPERCHROMES" in column F/index 4)if len(row) > 4 and isinstance(row[4], str) and re.search(r'LEVEL \d+ \|', row[4]):continue# Indices based on B6:P (0-indexed from B)icon_formula = row[0] if len(row) > 0 else ''name = row[2] if len(row) > 2 else 'N/A'value_raw = row[4] if len(row) > 4 else 'N/A'3 unmodified linesnotes = row[12] if len(row) > 12 else ''drive_url = row[14] if len(row) > 14 else None # Column Pcleaned_name = clean_string(name)if cleaned_name == 'N/A': # Skip rows without a valid namecontinueprocessed_item = {'icon': extract_image_url(icon_formula, drive_url),'name': cleaned_name,'value': format_currency(value_raw),'dupedValue': format_currency(duped_value_raw),'marketValue': format_currency(market_value_raw),9 unmodified linesfor row in values: # Expected range like B6:Gif not row or len(row) < 2: continue# Indices based on B6:G (0-indexed from B)discord_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Broblox_username = clean_string_optional(row[1]) if len(row) > 1 else None # Col Cif not discord_id and not roblox_username: continue4 unmodified lines'explanation': clean_string(row[3]) if len(row) > 3 else 'N/A', # Col E'evidence_link': clean_string_optional(row[4]) if len(row) > 4 else None, # Col F'alt_accounts': parse_alt_accounts(row[5]) if len(row) > 5 else [], # Col G'roblox_avatar_url': None # Will be filled later}processed_data.append(processed_item)return processed_data4 unmodified linesfor row in values: # Expected range like B6:Fif not row or len(row) < 2: continue# Indices based on B6:F (0-indexed from B)server_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Bserver_name = clean_string_optional(row[1]) if len(row) > 1 else None # Col Cif not server_id and not server_name: continue13 unmodified linesfor row in values: # Expected range like B6:Gif not row or len(row) < 3: continue# Indices based on B6:G (0-indexed from B)user_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Bserver_id = clean_string_optional(row[1]) if len(row) > 1 else None # Col Croblox_user = clean_string_optional(row[2]) if len(row) > 2 else None # Col D6 unmodified lines'explanation': clean_string(row[3]) if len(row) > 3 else 'N/A', # Col E'evidence_link': clean_string_optional(row[4]) if len(row) > 4 else None, # Col F'alt_accounts': parse_alt_accounts(row[5]) if len(row) > 5 else [], # Col G'roblox_avatar_url': None # Will be filled later}processed_data.append(processed_item)return processed_data37 unmodified linesstatus = error_details.get('status')message = error_details.get('message')logger.error(f"Google API HTTP Error during batch fetch for {spreadsheet_id}: Status={status}, Message={message}")# Handle potential API key/permission issues explicitlyif status == 'PERMISSION_DENIED' or status == 'UNAUTHENTICATED':logger.critical(f"Authentication/Permission Error accessing {spreadsheet_id}. Please check credentials/API access.")cache["service_available"] = False # Mark service as downsheets_service = None # Reset serviceelif status == 'NOT_FOUND':logger.error(f"Spreadsheet or Range not found error for {spreadsheet_id}. Ranges: {ranges}. Check IDs and Sheet Names.")raise e # Re-raise after loggingexcept Exception as e:logger.error(f"Error during batch fetching from {spreadsheet_id} for ranges {ranges}: {e}", exc_info=True)raise e# --- Webhook Sending ---async def send_webhook_notification(session: aiohttp.ClientSession, webhook_url: str, embed: Dict):"""Sends a Discord webhook notification with the provided embed."""if not webhook_url:# logger.debug("Webhook URL not configured. Skipping notification.") # Optional: Log less verboselyreturnif not embed:logger.warning("Attempted to send webhook with empty embed.")returnwebhook_data = {"embeds": [embed]}try:async with session.post(webhook_url, json=webhook_data, timeout=aiohttp.ClientTimeout(total=10)) as response:if response.status not in [200, 204]:logger.warning(f"Failed to send webhook (Status: {response.status}): {await response.text()}")# else: # Optional: Log success, can be verbose# logger.info(f"Webhook notification sent successfully to {webhook_url[:30]}...")except asyncio.TimeoutError:logger.warning(f"Timeout sending webhook to {webhook_url[:30]}...")except aiohttp.ClientError as e:logger.error(f"Network error sending webhook to {webhook_url[:30]}...: {e}")except Exception as e:logger.error(f"Unexpected error sending webhook: {e}", exc_info=True)# --- Background Cache Update Task (Refactored for Batching & Webhooks) ---async def update_cache_periodically():"""Fetches data, processes, detects changes/new entries, sends webhooks, and updates cache."""global cacheasync with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30)) as session: # Overall session timeoutwhile True:if not cache["service_available"]:logger.info("Attempting to re-initialize Google Sheets service...")init_google_sheets()if not cache["service_available"]:logger.warning("Google Sheets service still unavailable, skipping cache update cycle.")await asyncio.sleep(CACHE_UPDATE_INTERVAL_SECONDS * 2) # Wait longer if service is downcontinueelse:logger.info("Google Sheets service re-initialized. Proceeding with cache update.")logger.info("Starting cache update cycle...")start_time = datetime.now(timezone.utc)webhook_tasks = [] # Store webhook sending tasks# Prepare temporary storage for fetched datafetched_values_categories = {} # { "CategoryName": [items...] }7 unmodified linestry:# --- Define Ranges and Processors ---scammer_dwc_ranges = [f"{quote_sheet_name(USER_SCAMMER_SHEET)}!{USER_SCAMMER_RANGE}",f"{quote_sheet_name(SERVER_SCAMMER_SHEET)}!{SERVER_SCAMMER_RANGE}",4 unmodified linesSERVER_SCAMMER_SHEET: process_server_scammer_data,DWC_SHEET: process_dwc_data,}scammer_dwc_target_key_map = {USER_SCAMMER_SHEET: "user_scammers",SERVER_SCAMMER_SHEET: "server_scammers",DWC_SHEET: "dwc",}values_dupes_ranges = [f"{quote_sheet_name(DUPE_LIST_SHEET)}!{DUPE_LIST_RANGE}"]values_dupes_ranges.extend([f"{quote_sheet_name(cat)}!{VALUES_RANGE}" for cat in CATEGORIES])2 unmodified lines"scammer_dwc_batch": fetch_batch_ranges_async(SCAMMER_DWC_SPREADSHEET_ID,scammer_dwc_ranges,value_render_option='FORMATTED_VALUE'),"values_dupes_batch": fetch_batch_ranges_async(VALUES_DUPE_SPREADSHEET_ID,values_dupes_ranges,value_render_option='FORMATTED_VALUE')}11 unmodified lineslogger.error(f"Failed to fetch batch data for {key}: {result}")current_errors[key] = str(result)else:if key == "scammer_dwc_batch":raw_scammer_dwc_results = resultelif key == "values_dupes_batch":4 unmodified lineslogger.info(f"Processing {len(raw_scammer_dwc_results)} valueRanges from Scammer/DWC sheet...")for vr in raw_scammer_dwc_results:range_str = vr.get('range', '')match = re.match(r"^'?([^'!]+)'?!", range_str)if not match:logger.warning(f"Could not extract sheet name from range '{range_str}' in Scammer/DWC response.")continuesheet_name = match.group(1).replace("''", "'")if sheet_name in scammer_dwc_processor_map:processor = scammer_dwc_processor_map[sheet_name]1 unmodified linevalues = vr.get('values', [])try:processed_data = processor(values)new_cache_data[target_key] = processed_data # Store fetched data temporarilylogger.info(f"Processed {len(processed_data)} items for {sheet_name} -> {target_key}")except Exception as e:logger.error(f"Error processing data for {sheet_name} using {processor.__name__}: {e}", exc_info=True)16 unmodified linestry:if sheet_name == DUPE_LIST_SHEET:processed_data = process_dupe_list_data(values)new_cache_data["dupes"] = processed_data # Store fetched data temporarilylogger.info(f"Processed {len(processed_data)} items for {DUPE_LIST_SHEET} -> dupes")elif sheet_name in CATEGORIES:processed_data = process_sheet_data(values)fetched_values_categories[sheet_name] = processed_data # Store fetched data temporarilylogger.info(f"Processed {len(processed_data)} items for Category: {sheet_name}")else:logger.warning(f"Unrecognized sheet name '{sheet_name}' derived from range '{range_str}' in Values/Dupes sheet.")2 unmodified lineslogger.error(f"Error processing data for {sheet_name}: {e}", exc_info=True)current_errors[f"process_{target_key}"] = str(e)# --- Fetch Roblox Avatars (for new data before comparison/webhook) ---logger.info("Fetching Roblox avatars for newly processed data...")avatar_tasks = []# Combine lists needing avatars from the *newly fetched* dataentries_needing_avatars = new_cache_data.get("user_scammers", []) + new_cache_data.get("dwc", [])for entry in entries_needing_avatars:if entry.get('roblox_username'):1 unmodified lineavatar_tasks.append(fetch_avatar_for_entry_update(session, entry))if avatar_tasks:await asyncio.gather(*avatar_tasks) # Exceptions logged within helperlogger.info(f"Finished fetching avatars for {len(avatar_tasks)} potential new entries.")# --- Change Detection & Webhook Preparation (BEFORE Cache Update) ---current_time = datetime.now(timezone.utc)timestamp_iso = current_time.isoformat()# 1. Value Changes (Existing Logic + Webhook Prep)detected_value_changes_for_api = {} # For the /api/value-changes endpointif "values" not in cache: cache["values"] = {} # Ensure exists for comparisonif VALUE_WEBHOOK_URL and not any(k.startswith("process_values_") for k in current_errors) and "values_dupes_batch" not in current_errors:logger.info("Detecting value changes for webhooks...")fields_to_compare = ['value', 'dupedValue', 'marketValue']for category, new_items in fetched_values_categories.items():old_items_dict = {item['name']: item for item in cache["values"].get(category, [])}category_changes_for_api = []for new_item in new_items:item_name = new_item.get('name')if not item_name or item_name == 'N/A': continueold_item = old_items_dict.get(item_name)if old_item: # Check existing item for changesfor field in fields_to_compare:old_val_str = old_item.get(field, 'N/A')new_val_str = new_item.get(field, 'N/A')# Simple string comparison is sufficient here as they are formatted consistentlyif old_val_str != new_val_str:logger.info(f"Change detected in {category}: {item_name} - {field}: '{old_val_str}' -> '{new_val_str}'")change_info = {"item_name": item_name, "field": field,"old_value": old_val_str if old_val_str is not None else "N/A","new_value": new_val_str if new_val_str is not None else "N/A","timestamp": timestamp_iso}category_changes_for_api.append(change_info)# Prepare webhook embedembed = {"title": f"Value Update: {item_name} ({category})","color": 3447003, # Blue"fields": [{"name": "Field Changed", "value": field, "inline": True},{"name": "Old Value", "value": f"`{change_info['old_value']}`", "inline": True},{"name": "New Value", "value": f"`{change_info['new_value']}`", "inline": True},{"name": "Item Notes", "value": new_item.get('notes', 'N/A')[:1020] or 'N/A', "inline": False}, # Limit notes length],"timestamp": timestamp_iso}if new_item.get('icon'):embed["thumbnail"] = {"url": new_item['icon']}webhook_tasks.append(send_webhook_notification(session, VALUE_WEBHOOK_URL, embed))if category_changes_for_api:detected_value_changes_for_api[category] = category_changes_for_apilogger.info(f"Prepared {len(webhook_tasks)} value change webhooks.")elif not VALUE_WEBHOOK_URL:logger.info("VALUE_WEBHOOK_URL not set, skipping value change webhook detection.")else:logger.warning("Skipping value change webhook detection due to fetch/processing errors.")# 2. New Scammers / DWC (New Logic + Webhook Prep)if SCAMMER_WEBHOOK_URL and "scammer_dwc_batch" not in current_errors and not any(k.startswith("process_") and k in ["process_user_scammers", "process_server_scammers", "process_dwc"] for k in current_errors):logger.info("Detecting new scammer/DWC entries for webhooks...")initial_webhook_task_count = len(webhook_tasks)# User Scammersold_user_keys = set((item.get('discord_id'), item.get('roblox_username')) for item in cache.get("user_scammers", []))for item in new_cache_data.get("user_scammers", []):key = (item.get('discord_id'), item.get('roblox_username'))if key not in old_user_keys:logger.info(f"New User Scammer detected: Discord={item.get('discord_id')}, Roblox={item.get('roblox_username')}")embed = {"title": "🚨 New User Scammer Added","color": 15158332, # Red"fields": [{"name": "Discord ID", "value": f"`{item.get('discord_id', 'N/A')}`", "inline": True},{"name": "Roblox User", "value": f"`{item.get('roblox_username', 'N/A')}`", "inline": True},{"name": "Scam Type", "value": item.get('scam_type', 'N/A'), "inline": False},{"name": "Explanation", "value": item.get('explanation', 'N/A')[:1020] or 'N/A', "inline": False},],"timestamp": timestamp_iso}if item.get('evidence_link'):embed["fields"].append({"name": "Evidence", "value": item['evidence_link'], "inline": False})if item.get('alt_accounts'):embed["fields"].append({"name": "Alt Accounts", "value": ", ".join([f"`{a}`" for a in item['alt_accounts']]), "inline": False})if item.get('roblox_avatar_url'):embed["thumbnail"] = {"url": item['roblox_avatar_url']}webhook_tasks.append(send_webhook_notification(session, SCAMMER_WEBHOOK_URL, embed))# Server Scammersold_server_keys = set((item.get('server_id'), item.get('server_name')) for item in cache.get("server_scammers", []))for item in new_cache_data.get("server_scammers", []):key = (item.get('server_id'), item.get('server_name'))if key not in old_server_keys:logger.info(f"New Server Scammer detected: ID={item.get('server_id')}, Name={item.get('server_name')}")embed = {"title": "🚨 New Server Scammer Added","color": 15158332, # Red"fields": [{"name": "Server ID", "value": f"`{item.get('server_id', 'N/A')}`", "inline": True},{"name": "Server Name", "value": f"`{item.get('server_name', 'N/A')}`", "inline": True},{"name": "Scam Type", "value": item.get('scam_type', 'N/A'), "inline": False},{"name": "Explanation", "value": item.get('explanation', 'N/A')[:1020] or 'N/A', "inline": False},],"timestamp": timestamp_iso}if item.get('evidence_link'):embed["fields"].append({"name": "Evidence", "value": item['evidence_link'], "inline": False})webhook_tasks.append(send_webhook_notification(session, SCAMMER_WEBHOOK_URL, embed))# DWC Entriesold_dwc_keys = set((item.get('discord_user_id'), item.get('discord_server_id'), item.get('roblox_username')) for item in cache.get("dwc", []))for item in new_cache_data.get("dwc", []):key = (item.get('discord_user_id'), item.get('discord_server_id'), item.get('roblox_username'))if key not in old_dwc_keys:logger.info(f"New DWC Entry detected: User={item.get('discord_user_id')}, Server={item.get('discord_server_id')}, Roblox={item.get('roblox_username')}")embed = {"title": "⚠️ New DWC Entry Added","color": 15105570, # Orange/Dark Yellow"fields": [{"name": "Discord User ID", "value": f"`{item.get('discord_user_id', 'N/A')}`", "inline": True},{"name": "Discord Server ID", "value": f"`{item.get('discord_server_id', 'N/A')}`", "inline": True},{"name": "Roblox User", "value": f"`{item.get('roblox_username', 'N/A')}`", "inline": True},{"name": "Explanation", "value": item.get('explanation', 'N/A')[:1020] or 'N/A', "inline": False},],"timestamp": timestamp_iso}if item.get('evidence_link'):embed["fields"].append({"name": "Evidence", "value": item['evidence_link'], "inline": False})if item.get('alt_accounts'):embed["fields"].append({"name": "Alt Accounts", "value": ", ".join([f"`{a}`" for a in item['alt_accounts']]), "inline": False})if item.get('roblox_avatar_url'):embed["thumbnail"] = {"url": item['roblox_avatar_url']}webhook_tasks.append(send_webhook_notification(session, SCAMMER_WEBHOOK_URL, embed))logger.info(f"Prepared {len(webhook_tasks) - initial_webhook_task_count} new scammer/DWC webhooks.")elif not SCAMMER_WEBHOOK_URL:logger.info("SCAMMER_WEBHOOK_URL not set, skipping new scammer webhook detection.")else:logger.warning("Skipping new scammer webhook detection due to fetch/processing errors.")# --- Send Webhooks Concurrently ---if webhook_tasks:logger.info(f"Sending {len(webhook_tasks)} webhook notifications...")await asyncio.gather(*webhook_tasks)logger.info("Finished sending webhook notifications.")else:logger.info("No webhooks to send for this cycle.")# --- Final Cache Update ---5 unmodified linescache["server_scammers"] = new_cache_data["server_scammers"]cache["dwc"] = new_cache_data["dwc"]cache["dupes"] = new_cache_data["dupes"]cache["value_changes"] = detected_value_changes_for_api # Store the detected changescache["last_updated"] = current_timecache["is_ready"] = Truecache["service_available"] = True # Mark as available on successupdate_occurred = Truelogger.info(f"Cache update cycle completed successfully.")else: # Errors occurred, attempt partial update2 unmodified lines# Update values only if the values/dupes batch succeeded AND processing succeededif "values_dupes_batch" not in current_errors and not any(k.startswith("process_values_") for k in current_errors):# Check if fetched data is different from cache before updatingif cache.get("values") != fetched_values_categories:cache["values"] = fetched_values_categoriescache["value_changes"] = detected_value_changes_for_api # Update changes along with valuespartial_update_details.append("values")update_occurred = Trueelse:logger.warning("Skipping update for 'values' due to errors.")# Update dupes only if the values/dupes batch succeeded AND processing succeededif "values_dupes_batch" not in current_errors and "process_dupes" not in current_errors:if cache.get("dupes") != new_cache_data["dupes"]:cache["dupes"] = new_cache_data["dupes"]partial_update_details.append("dupes")update_occurred = Trueelse:logger.warning("Skipping update for 'dupes' due to errors.")# Update scammer/DWC sections if their batch succeeded AND processing succeededif "scammer_dwc_batch" not in current_errors:for key in ["user_scammers", "server_scammers", "dwc"]:process_error_key = f"process_{key}"if process_error_key not in current_errors:if cache.get(key) != new_cache_data[key]:cache[key] = new_cache_data[key]partial_update_details.append(key)update_occurred = Trueelse:logger.warning(f"Skipping update for '{key}' due to processing error.")else:logger.warning("Skipping update for 'user_scammers', 'server_scammers', 'dwc' due to batch fetch error.")if update_occurred:cache["last_updated"] = current_time # Mark partial update timecache["is_ready"] = True # Allow access even if partial# Keep service_available as potentially false if there were fetch errorslogger.info(f"Partially updated cache sections: {', '.join(partial_update_details)}")else:logger.error(f"Cache update cycle failed, and no parts could be updated based on errors. Errors: {current_errors}")# Keep cache["is_ready"] as it was. Don't update timestamp.except Exception as e:logger.exception(f"Critical error during cache update cycle: {e}")# If a critical error happens (e.g., network error during fetch), mark service potentially unavailableif isinstance(e, (aiohttp.ClientError, HttpError, asyncio.TimeoutError)):logger.warning("Communication error detected, will re-check service availability next cycle.")# service_available might have already been set to False by fetch_batch_ranges_async# --- Wait for the next cycle ---end_time = datetime.now(timezone.utc)duration = (end_time - start_time).total_seconds()wait_time = max(10, CACHE_UPDATE_INTERVAL_SECONDS - duration) # Ensure at least 10s waitlogger.info(f"Cache update cycle duration: {duration:.2f}s. Waiting {wait_time:.2f}s for next cycle.")await asyncio.sleep(wait_time)3 unmodified linesroblox_username = entry.get('roblox_username')if not roblox_username: returnnew_avatar = None # Default to Nonetry:user_id = await get_roblox_user_id(session, roblox_username)if user_id:5 unmodified lines# Keep new_avatar as None on errorfinally:# Update the entry dict directly (no need to check if changed, just set it)entry['roblox_avatar_url'] = new_avatar# --- FastAPI Startup Event ---3 unmodified linesif not cache["service_available"]:logger.warning("Google Sheets service not available at startup. Will attempt re-init in background task.")logger.info("Starting background cache update task...")# Check for webhook URLs at startupif not SCAMMER_WEBHOOK_URL:logger.warning("SCAMMER_WEBHOOK_URL environment variable not set. New scammer notifications disabled.")if not VALUE_WEBHOOK_URL:logger.warning("VALUE_WEBHOOK_URL environment variable not set. Value change notifications disabled.")asyncio.create_task(update_cache_periodically())# --- API Endpoints ---def check_cache_readiness():"""Reusable check for API endpoints - Checks cache readiness"""if not cache["is_ready"]:# Be more specific if service is known to be downif not cache["service_available"]:raise HTTPException(status_code=503, detail="Service temporarily unavailable due to backend connection issues. Please try again later.")else:raise HTTPException(status_code=503, detail="Cache is initializing or data is currently unavailable. Please try again shortly.")# Optional: Add check for staleness?# if cache["last_updated"] and (datetime.now(timezone.utc) - cache["last_updated"]).total_seconds() > CACHE_UPDATE_INTERVAL_SECONDS * 3:# raise HTTPException(status_code=503, detail="Data may be stale. Update in progress or backend issue.")@app.get("/")async def root():2 unmodified lines@app.get("/api/status")async def get_status():"""Returns the current status of the cache and service availability"""last_updated_iso = cache["last_updated"].isoformat() if cache["last_updated"] else Nonereturn {"cache_ready": cache["is_ready"],"sheets_service_available": cache["service_available"],"last_updated": last_updated_iso,"cached_items": {"value_categories": len(cache.get("values", {})),"user_scammers": len(cache.get("user_scammers", [])),"server_scammers": len(cache.get("server_scammers", [])),"dwc_entries": len(cache.get("dwc", [])),"duped_usernames": len(cache.get("dupes", [])),},"value_change_categories_in_last_cycle": len(cache.get("value_changes", {}))}@app.get("/api/values")async def get_values():"""Get all values data from cache"""check_cache_readiness()return cache.get("values", {})@app.get("/api/values/{category}")async def get_category_values(category: str):"""Get values data for a specific category from cache"""check_cache_readiness()# Case-insensitive matching for category namematched_category = next((c for c in cache.get("values", {}).keys() if c.lower() == category.lower()), None)if not matched_category:# Check if the category *exists* conceptually even if emptyif category.lower() in [c.lower() for c in CATEGORIES]:return {category: []} # Return empty list if category is valid but has no itemselse:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")return {matched_category: cache.get("values", {}).get(matched_category, [])}@app.get("/api/value-changes/{category}")async def get_category_value_changes(category: str):"""Get detected value changes for a specific category from the last cache update cycle."""check_cache_readiness()# Case-insensitive matching for category namematched_category = next((c for c in cache.get("value_changes", {}).keys() if c.lower() == category.lower()), None)if not matched_category:# Check if the category *exists* conceptually even if emptyif category.lower() in [c.lower() for c in CATEGORIES]:return {category: []} # Return empty list if category is valid but had no changeselse:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")return {matched_category: cache.get("value_changes", {}).get(matched_category, [])}@app.get("/api/value-changes")async def get_all_value_changes():"""Get all detected value changes from the last cache update cycle."""check_cache_readiness()return cache.get("value_changes", {})2 unmodified lines"""Get all scammer and DWC data (users, servers, dwc) from cache"""check_cache_readiness()return {"users": cache.get("user_scammers", []),"servers": cache.get("server_scammers", []),"dwc": cache.get("dwc", [])}@app.get("/api/dupes")async def get_dupes():"""Get all duped usernames from cache"""check_cache_readiness()return {"usernames": cache.get("dupes", [])} # Return empty list if not ready or emptyclass UsernameCheck(BaseModel):5 unmodified linescheck_cache_readiness() # Use the standard readiness checkusername_to_check = data.username.strip().lower()# Ensure dupes list is populated before checkingdupes_list = cache.get("dupes", [])is_duped = username_to_check in dupes_list# Webhook notification for checks resulting in "Not Found" (runs in background)# Note: This uses the *value* webhook URL per original code, not the scammer one.# If this needs to go to a *different* webhook, adjust the env var name.if not is_duped:webhook_url = os.getenv("WEBHOOK_URL") # Keep original env var name for this specific checkif webhook_url:# Use a new session for this one-off task or pass the main one if safeasync def send_check_webhook():try:async with aiohttp.ClientSession() as session: # Create a short-lived sessionembed = {"title": "User Dupe Check - Not Found","description": f"Username `{data.username}` was checked against the dupe list but was **not** found.","color": 16776960, # Yellow"timestamp": datetime.now(timezone.utc).isoformat()}await send_webhook_notification(session, webhook_url, embed)except Exception as e:logger.error(f"Error sending dupe check webhook: {e}") # Log errors from the taskasyncio.create_task(send_check_webhook()) # Fire and forgetelse:logger.info("WEBHOOK_URL (for dupe checks) not configured. Skipping notification.")return {"username": data.username, "is_duped": is_duped}1 unmodified line@app.get("/health")def health_check():"""Provides a health status of the API and its cache."""now = datetime.now(timezone.utc)status_detail = {"status": "ok", "last_updated": None, "time_since_update_seconds": None}if cache["last_updated"]:status_detail["last_updated"] = cache["last_updated"].isoformat()time_since_update = (now - cache["last_updated"]).total_seconds()status_detail["time_since_update_seconds"] = round(time_since_update)else:status_detail["last_updated"] = Nonestatus_detail["time_since_update_seconds"] = Noneif not cache["is_ready"]:status_detail["status"] = "initializing"status_detail["reason"] = "Cache has not been populated yet."return status_detailif not cache["service_available"]:status_detail["status"] = "degraded"status_detail["reason"] = "Google Sheets service connection issue detected on last attempt."return status_detail# Check for staleness only if the cache is ready and service *was* available last check# Allow some grace period (e.g., 3 intervals)if cache["last_updated"] and time_since_update > CACHE_UPDATE_INTERVAL_SECONDS * 3:status_detail["status"] = "degraded"status_detail["reason"] = f"Cache potentially stale (last update > {CACHE_UPDATE_INTERVAL_SECONDS * 3} seconds ago)"return status_detail# If we reach here, status is 'ok'return status_detail
main.py+373-164