Spaces:
Sleeping
Sleeping
Update main.py
Browse files68 unmodified lines697071727374753 unmodified lines79808182838485292 unmodified lines378379380381382383384385386387388389390391392393394395396397398399400401402403404405406125 unmodified lines5325335345355365375385393 unmodified lines54354454554654754854955055155255355455555655755855956056195 unmodified lines6576586596606616626636646656661 unmodified line668669670671672673674217 unmodified lines89289389489589689789889990090190290390490590690790890991091191291391491591691791893 unmodified lines1012101310141015101610171018101943 unmodified lines106310641065106610671068106910701071107210731074107568 unmodified lines# Webhook URLsSCAMMER_WEBHOOK_URL = os.getenv("SCAMMER_WEBHOOK_URL")VALUE_WEBHOOK_URL = os.getenv("VALUE_WEBHOOK_URL")DUPE_CHECK_WEBHOOK_URL = os.getenv("DUPE_CHECK_WEBHOOK_URL")# --- Global Cache ---3 unmodified lines"user_scammers": [],"server_scammers": [],"dwc": [],"trusted": [], # List of trusted users/servers"dupes": [], # List of duped usernames"last_updated": None, # Timestamp of the last successful/partial update"is_ready": False, # Is the cache populated at least once?292 unmodified linesprocessed_data.append(processed_item)return processed_datadef process_trusted_data(values): # For Trusted Users/Servers Sheetif not values: return []processed_data = []for row in values: # Expected range like B6:Eif not row or len(row) < 2: continue# Indices based on B6:E (0-indexed from B)discord_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col Bdiscord_username = clean_string_optional(row[1]) if len(row) > 1 else None # Col Cdiscord_server_id = clean_string_optional(row[2]) if len(row) > 2 else None # Col Droblox_username = clean_string_optional(row[3]) if len(row) > 3 else None # Col E# Skip if all identifiers are missingif not discord_id and not discord_username and not discord_server_id and not roblox_username: continue# Skip if it looks like a header rowif str(discord_id).lower() == 'discord id' or str(discord_username).lower() == 'discord username':continueprocessed_item = {'discord_id': discord_id,'discord_username': discord_username,'discord_server_id': discord_server_id,'roblox_username': roblox_username,'roblox_avatar_url': None # Will be filled later}processed_data.append(processed_item)return processed_data125 unmodified lines"user_scammers": [],"server_scammers": [],"dwc": [],"dupes": [],"trusted": [], # List of trusted users/servers}current_errors = {} # Track errors for specific fetches/sheets3 unmodified linesf"{quote_sheet_name(USER_SCAMMER_SHEET)}!{USER_SCAMMER_RANGE}",f"{quote_sheet_name(SERVER_SCAMMER_SHEET)}!{SERVER_SCAMMER_RANGE}",f"{quote_sheet_name(DWC_SHEET)}!{DWC_RANGE}",f"{quote_sheet_name(TRUSTED_SHEET)}!{TRUSTED_RANGE}",]scammer_dwc_processor_map = {USER_SCAMMER_SHEET: process_user_scammer_data,SERVER_SCAMMER_SHEET: process_server_scammer_data,DWC_SHEET: process_dwc_data,TRUSTED_SHEET: process_trusted_data,}scammer_dwc_target_key_map = {USER_SCAMMER_SHEET: "user_scammers",SERVER_SCAMMER_SHEET: "server_scammers",DWC_SHEET: "dwc",TRUSTED_SHEET: "trusted",}values_dupes_ranges = [f"{quote_sheet_name(DUPE_LIST_SHEET)}!{DUPE_LIST_RANGE}"]95 unmodified lines# --- Fetch Roblox Avatars (for new data before comparison/webhook) ---if not current_errors.get("scammer_dwc_batch") and \not current_errors.get("process_user_scammers") and \not current_errors.get("process_dwc"):logger.info("Fetching Roblox avatars for newly processed data...")avatar_tasks = []entries_needing_avatars = new_cache_data.get("user_scammers", []) + new_cache_data.get("dwc", []) + new_cache_data.get("trusted", [])for entry in entries_needing_avatars:if entry.get('roblox_username'):avatar_tasks.append(fetch_avatar_for_entry_update(session, entry))1 unmodified lineawait asyncio.gather(*avatar_tasks) # Exceptions logged within helperlogger.info(f"Finished fetching avatars for {len(avatar_tasks)} potential new entries.")else:logger.warning("Skipping avatar fetching due to errors in fetching/processing scammer/dwc data.")# --- Change Detection & Webhook Preparation (ONLY if cache is ready) ---217 unmodified lines# 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", "trusted"]:process_error_key = f"process_{key}"logger.info(f"Partial update check for key: '{key}'")if process_error_key not in current_errors:logger.info(f"--> No processing error found for '{key}'.")# Log the comparison detailsold_data = cache.get(key)new_data = new_cache_data.get(key) # Use .get for safetylogger.info(f"--> Comparing for '{key}': cache has {len(old_data) if old_data is not None else 'None'} items, new data has {len(new_data) if new_data is not None else 'None'} items.")if old_data != new_data:logger.info(f"--> Data differs for '{key}'. UPDATING CACHE.")cache[key] = new_datapartial_update_details.append(key)update_occurred = Trueelse:logger.info(f"--> Data is identical for '{key}'. Skipping update.")else:logger.warning(f"--> Skipping update for '{key}' due to processing error: {current_errors.get(process_error_key)}")else:logger.warning("Skipping update for 'user_scammers', 'server_scammers', 'dwc', 'trusted' due to batch fetch error.")if update_occurred:cache["last_updated"] = current_time # Mark partial update time93 unmodified lines"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", [])),"trusted_entries": len(cache.get("trusted", [])),},"value_change_categories_in_last_cycle": len(cache.get("value_changes", {}))}43 unmodified lines@app.get("/api/scammers")async def get_scammers():"""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", []),"trusted": cache.get("trusted", [])}@app.get("/api/dupes")68 unmodified lines69707172737475763 unmodified lines80818283848586292 unmodified lines379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411125 unmodified lines5375385395405415425435443 unmodified lines54854955055155255355455555655755855956056156256356456556695 unmodified lines6626636646656666676686696706716721 unmodified line674675676677678679680217 unmodified lines89889990090190290390490590690790890991091191291391493 unmodified lines1008100910101011101210131014101543 unmodified lines105910601061106210631064106510661067106810691070107168 unmodified lines# Webhook URLsSCAMMER_WEBHOOK_URL = os.getenv("SCAMMER_WEBHOOK_URL")VALUE_WEBHOOK_URL = os.getenv("VALUE_WEBHOOK_URL")# Optional: Separate webhook for dupe checks? Keep using the general one for now.DUPE_CHECK_WEBHOOK_URL = os.getenv("WEBHOOK_URL")# --- Global Cache ---3 unmodified lines"user_scammers": [],"server_scammers": [],"dwc": [],"trusted": [], # New cache key for trusted entries"dupes": [], # List of duped usernames"last_updated": None, # Timestamp of the last successful/partial update"is_ready": False, # Is the cache populated at least once?292 unmodified linesprocessed_data.append(processed_item)return processed_datadef process_trusted_data(values): # New function for Trusted Sheetif not values: return []processed_data = []for row in values: # Expected range like B6:Eif not row or len(row) < 1: continue # Need at least one identifier# Indices based on B6:E (0-indexed from B)discord_user_id = clean_string_optional(row[0]) if len(row) > 0 else None # Col B# discord_username = clean_string_optional(row[1]) if len(row) > 1 else None # Col C - Not currently used for matching, but keep for potential future usediscord_server_id = clean_string_optional(row[2]) if len(row) > 2 else None # Col Droblox_username = clean_string_optional(row[3]) if len(row) > 3 else None # Col E# Skip if all relevant identifiers are missingif not discord_user_id and not discord_server_id and not roblox_username: continue# Skip if it looks like a header row (check common header names)if (str(discord_user_id).lower() == 'discord user id' orstr(discord_server_id).lower() == 'discord server id' orstr(roblox_username).lower() == 'roblox username'):continueprocessed_item = {'status': 'Trusted', # Add a status field'discord_user_id': discord_user_id,'discord_server_id': discord_server_id,'roblox_username': roblox_username,'roblox_avatar_url': None # Will be filled later if roblox_username exists# Note: No explanation or evidence expected for trusted entries based on B6:E}processed_data.append(processed_item)return processed_data125 unmodified lines"user_scammers": [],"server_scammers": [],"dwc": [],"trusted": [], # Add trusted key"dupes": [],}current_errors = {} # Track errors for specific fetches/sheets3 unmodified linesf"{quote_sheet_name(USER_SCAMMER_SHEET)}!{USER_SCAMMER_RANGE}",f"{quote_sheet_name(SERVER_SCAMMER_SHEET)}!{SERVER_SCAMMER_RANGE}",f"{quote_sheet_name(DWC_SHEET)}!{DWC_RANGE}",f"{quote_sheet_name(TRUSTED_SHEET)}!{TRUSTED_RANGE}", # Add trusted range]scammer_dwc_processor_map = {USER_SCAMMER_SHEET: process_user_scammer_data,SERVER_SCAMMER_SHEET: process_server_scammer_data,DWC_SHEET: process_dwc_data,TRUSTED_SHEET: process_trusted_data, # Add trusted processor}scammer_dwc_target_key_map = {USER_SCAMMER_SHEET: "user_scammers",SERVER_SCAMMER_SHEET: "server_scammers",DWC_SHEET: "dwc",TRUSTED_SHEET: "trusted", # Add trusted target key}values_dupes_ranges = [f"{quote_sheet_name(DUPE_LIST_SHEET)}!{DUPE_LIST_RANGE}"]95 unmodified lines# --- Fetch Roblox Avatars (for new data before comparison/webhook) ---if not current_errors.get("scammer_dwc_batch") and \not current_errors.get("process_user_scammers") and \not current_errors.get("process_dwc") and \not current_errors.get("process_trusted"): # Check trusted processing toologger.info("Fetching Roblox avatars for newly processed data...")avatar_tasks = []entries_needing_avatars = new_cache_data.get("user_scammers", []) + new_cache_data.get("dwc", []) + new_cache_data.get("trusted", []) # Include trusted listfor entry in entries_needing_avatars:if entry.get('roblox_username'):avatar_tasks.append(fetch_avatar_for_entry_update(session, entry))1 unmodified lineawait asyncio.gather(*avatar_tasks) # Exceptions logged within helperlogger.info(f"Finished fetching avatars for {len(avatar_tasks)} potential new entries.")else:logger.warning("Skipping avatar fetching due to errors in fetching/processing scammer/dwc/trusted data.")# --- Change Detection & Webhook Preparation (ONLY if cache is ready) ---217 unmodified lines# 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 time93 unmodified lines"user_scammers": len(cache.get("user_scammers", [])),"server_scammers": len(cache.get("server_scammers", [])),"dwc_entries": len(cache.get("dwc", [])),"trusted_entries": len(cache.get("trusted", [])), # Add trusted count"duped_usernames": len(cache.get("dupes", [])),},"value_change_categories_in_last_cycle": len(cache.get("value_changes", {}))}43 unmodified lines@app.get("/api/scammers")async def get_scammers():"""Get all scammer, DWC, and trusted data (users, servers, dwc, trusted) from cache"""check_cache_readiness()return {"users": cache.get("user_scammers", []),"servers": cache.get("server_scammers", []),"dwc": cache.get("dwc", []),"trusted": cache.get("trusted", []) # Include trusted list}@app.get("/api/dupes")
main.py+36-40