# services/torn_api.py import aiohttp import json from pathlib import Path from config import TORN_API_KEY, ENEMY_FACTION_ID, YOUR_FACTION_ID from .ffscouter import fetch_batch_stats ENEMY_FILE = Path("data/enemy_faction.json") FRIENDLY_FILE = Path("data/friendly_faction.json") async def fetch_and_save_faction(faction_id: int, file_path: Path) -> bool: """ Fetches faction members from Torn, fetches their estimated BS from FFScouter, and saves everything to a JSON file. """ url = f"https://api.torn.com/v2/faction/{faction_id}?selections=members&key={TORN_API_KEY}" async with aiohttp.ClientSession() as session: async with session.get(url) as resp: if resp.status != 200: print(f"Torn faction fetch error: {resp.status}") return False data = await resp.json() members_list = data.get("members", []) if not members_list: return False # Build list of IDs (Torn uses 'id', not 'player_id') member_ids = [info.get("id") for info in members_list if "id" in info] if not member_ids: return False # Fetch batch FFScouter stats ff_data = await fetch_batch_stats(member_ids) # returns dict keyed by player_id # Build final faction data faction_data = [] for info in members_list: pid = info.get("id") if pid is None: continue est = ff_data.get(str(pid), {}).get("bs_estimate_human", "?") member = { "id": pid, "name": info.get("name", "Unknown"), "level": info.get("level", 0), "estimate": est } faction_data.append(member) # Save to file file_path.parent.mkdir(exist_ok=True, parents=True) # ensure folder exists with open(file_path, "w", encoding="utf-8") as f: json.dump(faction_data, f, indent=2) return True # Wrappers for clarity async def update_enemy_faction() -> bool: return await fetch_and_save_faction(ENEMY_FACTION_ID, ENEMY_FILE) async def update_friendly_faction() -> bool: return await fetch_and_save_faction(YOUR_FACTION_ID, FRIENDLY_FILE)