Spaces:
Sleeping
Sleeping
Update main.py
Browse files63 unmodified lines646566676869105 unmodified lines17517617717817918018118218318418518618718818919019119212 unmodified lines2052062072082092102112122132142152162172182192202212222239 unmodified lines23323423523623723823913 unmodified lines25325425525625725825926026126226326426526626726826927027127227327427527627727827928028116 unmodified lines29829930030130230330414 unmodified lines3193203213223233243258 unmodified lines33433533633733833934034134234334434510 unmodified lines35635735835936036136236336436536636736836918 unmodified lines3883893903913923933943953963973983994004014024034044054064074084094104114124134141 unmodified line4164174184194204214224234244254261 unmodified line4284294304314324334344354364374384395 unmodified lines44544644744844945045155 unmodified lines50750850951051151224 unmodified lines53753853954054154222 unmodified lines5655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026038 unmodified lines6126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237241 unmodified line7267277287297307317327337347357363 unmodified lines7407417427437447457463 unmodified lines7507517527537547557562 unmodified lines75976076176276376476517 unmodified lines78378478578678778878979079179279379479579679720 unmodified lines8188198208218228231 unmodified line8258268278288298308319 unmodified lines8418428438448458467 unmodified lines85485585685785885986086186231 unmodified lines8948958968978988999009017 unmodified lines90991091191291391491527 unmodified lines9439449459469479489491 unmodified line95195295395495595695795895996096196296396496596696796896997097197297397497563 unmodified lines# Webhook URLsSCAMMER_WEBHOOK_URL = os.getenv("SCAMMER_WEBHOOK_URL")VALUE_WEBHOOK_URL = os.getenv("VALUE_WEBHOOK_URL")# --- Global Cache ---105 unmodified linesnum = float(num_str)return f"${num:,.0f}"except (ValueError, TypeError):if isinstance(value, str) and not re.match(r'^-?[\d,.$]+\$?$', value.strip()):return value.strip() # Return original text if non-numeric-likereturn 'N/A'def parse_cached_currency(value_str: Optional[str]) -> Optional[float]:if value_str is None or value_str is None or str(value_str).strip().lower() == 'n/a':return Nonetry:num_str = str(value_str).replace('$', '').replace(',', '').strip()return float(num_str)except (ValueError, TypeError):return Nonedef clean_string(value, default='N/A'):if value is None: return default12 unmodified linesreturn [acc.strip() for acc in raw_string.split(',') if acc.strip()]# --- Roblox API Helpers (Unchanged) ---async def get_roblox_user_id(session: aiohttp.ClientSession, username: str):if not username: return Noneurl = "https://users.roblox.com/v1/usernames/users"payload = {"usernames": [username], "excludeBannedUsers": False}try:async with session.post(url, json=payload) as response:if response.status == 200:data = 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}")9 unmodified linesif not user_id: return Noneurl = f"https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds={user_id}&size=150x150&format=Png&isCircular=false"try:async with session.get(url) as response:if response.status == 200:data = await response.json()if data and data.get("data") and len(data["data"]) > 0:13 unmodified lines# --- 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'duped_value_raw = row[6] if len(row) > 6 else 'N/A'market_value_raw = row[8] if len(row) > 8 else 'N/A'demand = row[10] if len(row) > 10 else 'N/A'notes = 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 = {16 unmodified lines# 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: continueprocessed_item = {'discord_id': discord_id,'roblox_username': roblox_username,14 unmodified lines# 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: continueprocessed_item = {'server_id': server_id,'server_name': server_name,8 unmodified linesif not values: return []processed_data = []for 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 Dif not user_id and not server_id and not roblox_user: continueprocessed_item = {'status': 'DWC','discord_user_id': user_id,10 unmodified linesdef process_dupe_list_data(values): # For Dupe List Sheetif not values: return []# Expected range like B2:Breturn [row[0].strip().lower() for row in values if row and len(row)>0 and row[0] and isinstance(row[0], str) and row[0].strip()]# --- Async Fetching Functions ---async def fetch_batch_ranges_async(spreadsheet_id: str, ranges: List[str], value_render_option: str = 'FORMATTED_VALUE') -> List[Dict]:"""Async wrapper to fetch multiple ranges using batchGet and return raw valueRanges."""global sheets_serviceif not sheets_service:logger.warning(f"Attempted batch fetch from {spreadsheet_id} but Sheets service is unavailable.")raise Exception("Google Sheets service not initialized")18 unmodified linesreturn value_ranges # Return the raw list of valueRange objectsexcept HttpError as e:error_details = json.loads(e.content).get('error', {})status = 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.")1 unmodified linewebhook_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:1 unmodified lineexcept 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...")5 unmodified lineselse: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 tasks55 unmodified linesif isinstance(result, Exception):logger.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 = result24 unmodified linescurrent_errors[f"process_{target_key}"] = str(e)else:logger.warning(f"No processor found for sheet name '{sheet_name}' derived from range '{range_str}' in Scammer/DWC sheet.")# --- Process Values/Dupes Results ---if raw_values_dupes_results is not None:22 unmodified linestarget_key = "dupes" if sheet_name == DUPE_LIST_SHEET else f"values_{sheet_name}"logger.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'):# Pass the specific entry dict to the update functionavatar_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')8 unmodified lines"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:1 unmodified lineawait asyncio.gather(*webhook_tasks)logger.info("Finished sending webhook notifications.")else:logger.info("No webhooks to send for this cycle.")# --- Final Cache Update ---update_occurred = Falseif not current_errors: # Perfect cyclelogger.info("Updating full cache (no errors during fetch or processing).")cache["values"] = fetched_values_categories3 unmodified linescache["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.")3 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 values2 unmodified lineselse: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"]:17 unmodified lineselse: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}")20 unmodified linesuser_id = await get_roblox_user_id(session, roblox_username)if user_id:new_avatar = await get_roblox_avatar_url(session, user_id)except Exception as e:# Log errors but don't stop the main update loop1 unmodified line# 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_avatar9 unmodified lineslogger.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())7 unmodified linesraise 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():31 unmodified linesmatched_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, [])}7 unmodified linesmatched_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.")27 unmodified lines@app.post("/api/check")async def check_username(data: UsernameCheck):"""Check if a username is duped using cached data and send webhook"""check_cache_readiness() # Use the standard readiness checkusername_to_check = data.username.strip().lower()1 unmodified linedupes_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:63 unmodified lines6465666768697071105 unmodified lines17717817918018118218318418518618718818919019119219319419512 unmodified lines2082092102112122132142152162172182192202212222232242252262279 unmodified lines23723823924024124224324413 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828916 unmodified lines30630730830931031131231331431531614 unmodified lines3313323333343353363373383393403418 unmodified lines35035135235335435535635735835936036136236336436510 unmodified lines37637737837938038138238338438538638738838939039139239339439539618 unmodified lines4154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544551 unmodified line4574584594604614624634644654664674684694701 unmodified line4724734744754764774784794804814824834845 unmodified lines49049149249349449549655 unmodified lines55255355455555655755855924 unmodified lines58458558658758858959059159222 unmodified lines6156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646658 unmodified lines6746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058061 unmodified line8088098108118128138148158168178188198208213 unmodified lines8258268278288298308318328333 unmodified lines8378388398408418422 unmodified lines84584684784884985017 unmodified lines86886987087187287387487587687787887988088188288388488588620 unmodified lines9079089099109119129139141 unmodified line9169179189199209219229 unmodified lines9329339349359369379389397 unmodified lines94794894995095195295331 unmodified lines9859869879889899909919929937 unmodified lines1001100210031004100510061007100827 unmodified lines10361037103810391040104110421 unmodified line104410451046104710481049105010511052105310541055105610571058105910601061106210631064106563 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 ---105 unmodified linesnum = float(num_str)return f"${num:,.0f}"except (ValueError, TypeError):# Allow text like "Event", "Unobtainable" etc. to pass throughif isinstance(value, str) and value.strip() and not re.match(r'^-?[\d,.$]+\$?$', value.strip()):return value.strip() # Return original text if non-numeric-likereturn 'N/A' # Return N/A for things that look like bad numbersdef parse_cached_currency(value_str: Optional[str]) -> Optional[float]:if value_str is None or str(value_str).strip().lower() == 'n/a':return Nonetry:num_str = str(value_str).replace('$', '').replace(',', '').strip()return float(num_str)except (ValueError, TypeError):return None # Return None if it's not a parsable number (e.g., "Event")def clean_string(value, default='N/A'):if value is None: return default12 unmodified linesreturn [acc.strip() for acc in raw_string.split(',') if acc.strip()]# --- Roblox API Helpers ---async def get_roblox_user_id(session: aiohttp.ClientSession, username: str):if not username: return Noneurl = "https://users.roblox.com/v1/usernames/users"payload = {"usernames": [username], "excludeBannedUsers": False}try:# Increased timeout specifically for Roblox API calls which can be slowasync with session.post(url, json=payload, timeout=aiohttp.ClientTimeout(total=10)) as response:if response.status == 200:data = 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 User API returned status {response.status} for username '{username}'")return Noneexcept asyncio.TimeoutError:logger.warning(f"Timeout fetching Roblox User ID for {username}")9 unmodified linesif not user_id: return Noneurl = f"https://thumbnails.roblox.com/v1/users/avatar-headshot?userIds={user_id}&size=150x150&format=Png&isCircular=false"try:# Increased timeout specifically for Roblox API callsasync with session.get(url, timeout=aiohttp.ClientTimeout(total=10)) as response:if response.status == 200:data = await response.json()if data and data.get("data") and len(data["data"]) > 0:13 unmodified lines# --- Data Processing Functions ---def process_sheet_data(values): # For Value Categoriesif not values: return []processed_data = []for row_idx, row in enumerate(values): # Start counting from sheet row 6 (index 0 here)if 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)# Use index 4 for Value column (F)if len(row) > 4 and isinstance(row[4], str) and re.search(r'(LEVEL \d+ \|)|(VALUE)', row[4], re.IGNORECASE):#logger.debug(f"Skipping potential header row {row_idx+6}: {row}")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' # Column Dvalue_raw = row[4] if len(row) > 4 else 'N/A' # Column Fduped_value_raw = row[6] if len(row) > 6 else 'N/A' # Column Hmarket_value_raw = row[8] if len(row) > 8 else 'N/A' # Column Jdemand = row[10] if len(row) > 10 else 'N/A' # Column Lnotes = row[12] if len(row) > 12 else '' # Column Ndrive_url = row[14] if len(row) > 14 else None # Column Pcleaned_name = clean_string(name)# Also skip if name is clearly a header like "Name"if cleaned_name == 'N/A' or cleaned_name.lower() == 'name':#logger.debug(f"Skipping row {row_idx+6} due to missing/header name: {row}")continueprocessed_item = {16 unmodified lines# 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 C# Skip if both identifiers are missingif not discord_id and not roblox_username: continue# Skip if it looks like a header rowif str(discord_id).lower() == 'discord id' or str(roblox_username).lower() == 'roblox username':continueprocessed_item = {'discord_id': discord_id,'roblox_username': roblox_username,14 unmodified lines# 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 C# Skip if both identifiers are missingif not server_id and not server_name: continue# Skip if it looks like a header rowif str(server_id).lower() == 'server id' or str(server_name).lower() == 'server name':continueprocessed_item = {'server_id': server_id,'server_name': server_name,8 unmodified linesif not values: return []processed_data = []for row in values: # Expected range like B6:Gif not row or len(row) < 1: continue # Need at least one ID# 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 D# Skip if all identifiers are missingif not user_id and not server_id and not roblox_user: continue# Skip if it looks like a header rowif str(user_id).lower() == 'user id' or str(server_id).lower() == 'server id' or str(roblox_user).lower() == 'roblox user':continueprocessed_item = {'status': 'DWC','discord_user_id': user_id,10 unmodified linesdef process_dupe_list_data(values): # For Dupe List Sheetif not values: return []# Expected range like B2:Bprocessed_dupes = []for row in values:if row and len(row)>0 and row[0] and isinstance(row[0], str):username = row[0].strip().lower()# Skip header or empty stringsif username and username not in ('username', 'usernames'):processed_dupes.append(username)return processed_dupes# --- Async Fetching Functions ---async def fetch_batch_ranges_async(spreadsheet_id: str, ranges: List[str], value_render_option: str = 'FORMATTED_VALUE') -> List[Dict]:"""Async wrapper to fetch multiple ranges using batchGet and return raw valueRanges."""global sheets_service, cacheif not sheets_service:logger.warning(f"Attempted batch fetch from {spreadsheet_id} but Sheets service is unavailable.")raise Exception("Google Sheets service not initialized")18 unmodified linesreturn value_ranges # Return the raw list of valueRange objectsexcept HttpError as e:status_code = e.resp.statuserror_details = {}try:error_details = json.loads(e.content).get('error', {})except json.JSONDecodeError:logger.error(f"Failed to parse JSON error content from Google API: {e.content}")status = error_details.get('status', f'HTTP_{status_code}') # Use HTTP status if details missingmessage = error_details.get('message', e._get_reason()) # Fallback messagelogger.error(f"Google API HTTP Error during batch fetch for {spreadsheet_id}: Status={status}, Message={message}")if status in ('PERMISSION_DENIED', 'UNAUTHENTICATED') or status_code == 403 or status_code == 401:logger.critical(f"Authentication/Permission Error accessing {spreadsheet_id}. Disabling service checks.")cache["service_available"] = False # Mark service as downsheets_service = None # Reset service to force re-init attemptelif status == 'NOT_FOUND' or status_code == 404:logger.error(f"Spreadsheet or Range not found error for {spreadsheet_id}. Ranges: {ranges}. Check IDs and Sheet Names.")elif status_code >= 500: # Server-side errors on Google's endlogger.warning(f"Google API server error ({status_code}) for {spreadsheet_id}. May be temporary.")# Keep service_available as True, retry might work# else: # Other client errors (e.g., 400 Bad Request for invalid range format)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)# Could be network issues, timeouts handled by aiohttp session typically# Consider marking service unavailable for persistent non-HTTP errors too?# cache["service_available"] = False # Optional: Be more aggressiveraise 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.")returnif not embed:logger.warning("Attempted to send webhook with empty embed.")1 unmodified linewebhook_data = {"embeds": [embed]}try:# Use a reasonable timeout for webhook postsasync with session.post(webhook_url, json=webhook_data, timeout=aiohttp.ClientTimeout(total=10)) as response:if response.status not in [200, 204]:# Log more details on failureresponse_text = await response.text()logger.warning(f"Failed to send webhook to {webhook_url[:30]}... (Status: {response.status}): {response_text[:500]}") # Limit response text length# else:# logger.debug(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:1 unmodified lineexcept Exception as e:logger.error(f"Unexpected error sending webhook: {e}", exc_info=True)# --- Background Cache Update Task ---async def update_cache_periodically():"""Fetches data, processes, detects changes/new entries (if not first run), sends webhooks, and updates cache."""global cache# Increase overall session timeout slightly for robustnessasync with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=45)) as session:while True:if not cache["service_available"]:logger.info("Attempting to re-initialize Google Sheets service...")5 unmodified lineselse:logger.info("Google Sheets service re-initialized. Proceeding with cache update.")logger.info(f"Starting cache update cycle... (Cache Ready: {cache['is_ready']})")start_time = datetime.now(timezone.utc)webhook_tasks = [] # Store webhook sending tasks55 unmodified linesif isinstance(result, Exception):logger.error(f"Failed to fetch batch data for {key}: {result}")current_errors[key] = str(result)# If fetch failed, likely service unavailable (handled by fetch_batch_ranges_async)# No need to explicitly set cache["service_available"] = False here againelse:if key == "scammer_dwc_batch":raw_scammer_dwc_results = result24 unmodified linescurrent_errors[f"process_{target_key}"] = str(e)else:logger.warning(f"No processor found for sheet name '{sheet_name}' derived from range '{range_str}' in Scammer/DWC sheet.")else:logger.warning("Skipping Scammer/DWC processing due to fetch error.")# --- Process Values/Dupes Results ---if raw_values_dupes_results is not None:22 unmodified linestarget_key = "dupes" if sheet_name == DUPE_LIST_SHEET else f"values_{sheet_name}"logger.error(f"Error processing data for {sheet_name}: {e}", exc_info=True)current_errors[f"process_{target_key}"] = str(e)else:logger.warning("Skipping Values/Dupes processing due to fetch error.")# --- 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", [])for entry in entries_needing_avatars:if entry.get('roblox_username'):avatar_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.")else:logger.warning("Skipping avatar fetching due to errors in fetching/processing scammer/dwc data.")# --- Change Detection & Webhook Preparation (ONLY if cache is ready) ---current_time = datetime.now(timezone.utc)timestamp_iso = current_time.isoformat()detected_value_changes_for_api = {} # Always calculate for API, but only send webhooks if ready# Perform comparisons regardless of cache readiness to populate detected_value_changes_for_api# But only queue webhooks if cache["is_ready"] is True# 1. Value Changes Calculationif "values" not in cache: cache["values"] = {} # Ensure exists for comparison logicif "values_dupes_batch" not in current_errors and not any(k.startswith("process_values_") for k in current_errors):fields_to_compare = ['value', 'dupedValue', 'marketValue']for category, new_items in fetched_values_categories.items():old_items_dict = {item['name'].lower(): item for item in cache["values"].get(category, [])} # Use lower case for comparison robustnesscategory_changes_for_api = []for new_item in new_items:item_name = new_item.get('name')if not item_name or item_name == 'N/A': continueitem_name_lower = item_name.lower()old_item = old_items_dict.get(item_name_lower)change_detected_for_webhook = Falsechange_info_webhook = {}if old_item: # Check existing item for changesfor field in fields_to_compare:old_val_str = old_item.get(field, 'N/A')8 unmodified lines"timestamp": timestamp_iso}category_changes_for_api.append(change_info)change_detected_for_webhook = Truechange_info_webhook = change_info # Store last change for potential webhook# Prepare webhook only if a change was found AND cache was readyif change_detected_for_webhook and cache["is_ready"] and VALUE_WEBHOOK_URL:embed = {"title": f"Value Update: {item_name} ({category})","color": 3447003, # Blue"fields": [{"name": "Field Changed", "value": change_info_webhook['field'], "inline": True},{"name": "Old Value", "value": f"`{change_info_webhook['old_value']}`", "inline": True},{"name": "New Value", "value": f"`{change_info_webhook['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_apiif cache["is_ready"] and VALUE_WEBHOOK_URL:logger.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 sending.")elif not cache["is_ready"]:logger.info("Skipping value change webhook sending during initial cache population.")else:logger.warning("Skipping value change detection and webhooks due to fetch/processing errors.")# 2. New Scammers / DWC (Only if cache is ready)if cache["is_ready"] and 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 (cache is ready)...")initial_webhook_task_count = len(webhook_tasks)added_new_scammer_webhook = False# --- User Scammers ---# Create keys robust to None valuesdef get_user_scammer_key(item):return (item.get('discord_id') or 'none', item.get('roblox_username') or 'none')old_user_keys = set(get_user_scammer_key(item) for item in cache.get("user_scammers", []))for item in new_cache_data.get("user_scammers", []):key = get_user_scammer_key(item)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')[:1020] or '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']])[:1020] or 'N/A', "inline": False}) # Limit lengthif item.get('roblox_avatar_url'): embed["thumbnail"] = {"url": item['roblox_avatar_url']}webhook_tasks.append(send_webhook_notification(session, SCAMMER_WEBHOOK_URL, embed))added_new_scammer_webhook = True# --- Server Scammers ---def get_server_scammer_key(item):return (item.get('server_id') or 'none', item.get('server_name') or 'none')old_server_keys = set(get_server_scammer_key(item) for item in cache.get("server_scammers", []))for item in new_cache_data.get("server_scammers", []):key = get_server_scammer_key(item)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')[:1020] or '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))added_new_scammer_webhook = True# --- DWC Entries ---def get_dwc_key(item):# Use a combination of available identifiers as the keyreturn (item.get('discord_user_id') or 'none',item.get('discord_server_id') or 'none',item.get('roblox_username') or 'none')old_dwc_keys = set(get_dwc_key(item) for item in cache.get("dwc", []))for item in new_cache_data.get("dwc", []):key = get_dwc_key(item)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']])[:1020] or 'N/A', "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))added_new_scammer_webhook = Trueif added_new_scammer_webhook:logger.info(f"Prepared {len(webhook_tasks) - initial_webhook_task_count} new scammer/DWC webhooks.")elif not cache["is_ready"]:logger.info("Skipping new scammer webhook detection during initial cache population.")elif not SCAMMER_WEBHOOK_URL:logger.info("SCAMMER_WEBHOOK_URL not set, skipping new scammer webhook detection.")else: # Errors occurredlogger.warning("Skipping new scammer webhook detection due to fetch/processing errors.")# --- Send Webhooks Concurrently ---if webhook_tasks:1 unmodified lineawait asyncio.gather(*webhook_tasks)logger.info("Finished sending webhook notifications.")else:logger.info("No webhooks prepared to send for this cycle.")# --- Final Cache Update ---update_occurred = False# Determine if this cycle *should* mark the cache as readycan_set_ready = not cache["is_ready"] and not current_errors # Only set ready on first *fully successful* runif not current_errors: # Perfect cyclelogger.info("Updating full cache (no errors during fetch or processing).")cache["values"] = fetched_values_categories3 unmodified linescache["dupes"] = new_cache_data["dupes"]cache["value_changes"] = detected_value_changes_for_api # Store the detected changescache["last_updated"] = current_timeif can_set_ready:logger.info("Marking cache as ready after initial successful population.")cache["is_ready"] = Truecache["service_available"] = True # Mark as available on successupdate_occurred = Truelogger.info(f"Cache update cycle completed successfully.")3 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.get("values") != fetched_values_categories:cache["values"] = fetched_values_categoriescache["value_changes"] = detected_value_changes_for_api # Update changes along with values2 unmodified lineselse: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"]:17 unmodified lineselse: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 time# Mark cache ready only if it was *already* ready and we managed a partial update# Or if this was the first run AND it was partially successful (maybe relax this?)# Let's stick to: only mark ready on first FULL success.if cache["is_ready"]: # If it was already ready, keep it readylogger.info(f"Partially updated cache sections: {', '.join(partial_update_details)}. Cache remains ready.")else:logger.info(f"Partially updated cache sections: {', '.join(partial_update_details)}. Cache remains NOT ready (requires full success on first run).")# Keep service_available based on whether fetch errors occurredelse:logger.error(f"Cache update cycle failed, and no parts could be updated based on errors. Errors: {current_errors}")# Cache readiness and service availability remain unchangedexcept Exception as e:logger.exception(f"Critical error during cache update cycle: {e}")20 unmodified linesuser_id = await get_roblox_user_id(session, roblox_username)if user_id:new_avatar = await get_roblox_avatar_url(session, user_id)# else: # User ID not found, keep avatar as None# logger.debug(f"Roblox user ID not found for username: {roblox_username}")except Exception as e:# Log errors but don't stop the main update loop1 unmodified line# Keep new_avatar as None on errorfinally:# Update the entry dict directlyentry['roblox_avatar_url'] = new_avatar9 unmodified lineslogger.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.")if not DUPE_CHECK_WEBHOOK_URL:logger.warning("WEBHOOK_URL (for dupe checks) environment variable not set. Dupe check notifications disabled.")asyncio.create_task(update_cache_periodically())7 unmodified linesraise 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.")@app.get("/")async def root():31 unmodified linesmatched_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 emptyvalid_categories_lower = [c.lower() for c in CATEGORIES]if category.lower() in valid_categories_lower:return {category: []} # Return empty list if category is valid but has no items yetelse:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")return {matched_category: cache.get("values", {}).get(matched_category, [])}7 unmodified linesmatched_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 emptyvalid_categories_lower = [c.lower() for c in CATEGORIES]if category.lower() in valid_categories_lower:return {category: []} # Return empty list if category is valid but had no changeselse:raise HTTPException(status_code=404, detail=f"Category '{category}' not found.")27 unmodified lines@app.post("/api/check")async def check_username(data: UsernameCheck):"""Check if a username is duped using cached data and optionally send webhook"""check_cache_readiness() # Use the standard readiness checkusername_to_check = data.username.strip().lower()1 unmodified linedupes_list = cache.get("dupes", [])is_duped = username_to_check in dupes_list# Webhook notification for checks resulting in "Not Found"if not is_duped:if DUPE_CHECK_WEBHOOK_URL:async def send_check_webhook():try:# Use a short-lived session for this potentially frequent taskasync with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10)) as session:embed = {"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, DUPE_CHECK_WEBHOOK_URL, embed)except Exception as e:logger.error(f"Error sending dupe check webhook: {e}")asyncio.create_task(send_check_webhook()) # Fire and forgetelse:
main.py+237-147