### Run Example Bot Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md Execute the basic example bot after cloning the repository and installing dependencies. ```python python examples/basic_bot.py ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md Clone the TTWars bot skills repository and install the necessary Python dependencies for running example bots. ```bash git clone https://github.com/adit7494/ttwars-bot-skills.git cd ttwars-bot-skills pip install requests beautifulsoup4 ``` -------------------------------- ### Reference TTWARS Automation Skill in Prompt Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md Provides an example of how to reference the ttwars-automation skill directly within a prompt for an AI agent. This allows for dynamic use of the skill's capabilities. ```bash # Or reference it directly in your prompt: # "Using the ttwars-automation skill, write a bot that..." ``` -------------------------------- ### Example GraphQL Response Format Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This JSON structure represents a typical successful response from a GraphQL query, containing the requested data and an empty errors array. It shows the format for player data including alliance information. ```json { "data": { "player": { "id": 61, "name": "claire", "tribeId": 3, "alliance": { "id": 1, "tag": "Friends" } } }, "errors": [] } ``` -------------------------------- ### Render Player Profile with GraphQL Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This JavaScript snippet shows how a React component initializes by embedding a GraphQL query, view data, and player ID. It's the primary method for integrating GraphQL data into the game's UI. ```javascript window.Travian.React.PlayerProfile.render( { gql: "query($uid: Int!) { player(id: $uid) { ... } }", viewData: { /* pre-fetched response data */ }, playerId: 61 }, ["spieler", "allgemein", "statistiken", "hero"] ); ``` -------------------------------- ### Parse Building Upgrade Costs Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Parses building costs from the build.php page. It looks for upgrade buttons and cost tables to extract resource values. ```python # Parse building page for upgrade/train actions # Look for upgrade buttons and cost tables costs = soup.find('div', class_='showCosts') if costs: for resource in costs.find_all('span'): r_class = resource.get('class', []) value = resource.text.strip() print(f"Cost: {value}") ``` -------------------------------- ### Send Hero on Adventure via POST Request Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Sends a hero on an adventure by making a POST request to the rally point endpoint. Requires the server URL, rally point ID, and the adventure's map ID. ```python # The adventure button has data-mapid attribute # POST to the rally point or use the button's onclick # Endpoint varies by server, typically: session.post(f'https://{server}/build.php?id={rally_point_id}', data={ 'action': 'adventure', 'mapId': adventure_map_id }) ``` -------------------------------- ### Upgrade Cost Formula Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/buildings.md General formula for calculating upgrade costs and times for buildings, which scale with level. ```plaintext Wood = base_wood * 1.2^(level-1) Clay = base_clay * 1.2^(level-1) Iron = base_iron * 1.2^(level-1) Crop = base_crop * 1.2^(level-1) Time = base_time * 1.2^(level-1) ``` -------------------------------- ### Map Tile URL Patterns Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/page-structure.md Patterns for fetching map tiles. Includes terrain imagery, overlay markers with timestamps, and a minimap overview. ```text /map/block/{x1}.{y1}.{x2}.{y2}.png # Terrain imagery ``` ```text /map/mark/{x1}.{y1}.{x2}.{y2}.png?t={timestamp} # Overlay markers ``` ```text /map/minimap.jpg # Minimap overview ``` -------------------------------- ### Send Authenticated GraphQL Request with Python Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md This snippet demonstrates how to send a GraphQL request using the `requests` library in Python. It includes logging in via a POST request to establish a session before sending the GraphQL query. ```python import requests session = requests.Session() # Login first (cookie-based auth) session.post(f'https://{server}/login', data={'name': user, 'password': pw, 's1': 'Login'}) # Send GraphQL response = session.post(f'https://{server}/api/graphql', json={ 'query': query, 'variables': variables }) data = response.json() ``` -------------------------------- ### Passing Variables to GraphQL Query Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md Demonstrates how to define and pass variables as a JSON object to a GraphQL query using the gql library. ```python variables = { 'uid': 61, 'subTabName': 'profileVillages' } result = gql.query(query_string, variables) ``` -------------------------------- ### GraphQL Query for Player Profile Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md Use this query to fetch a player's ID, name, tribe ID, alliance information, and village details. Requires the player's UID as a variable. ```graphql query($uid: Int!) { player(id: $uid) { id, name, tribeId alliance { id, tag } villages { id, name, population, x, y } } } ``` -------------------------------- ### Copy TTWARS Automation Skill to Claude Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md Copies the ttwars-automation skill directory to the user's Claude skills directory. This is the primary method for integrating the skill with Claude Code. ```bash # Copy the skill to your Claude skills directory cp -r skills/ttwars-automation ~/.claude/skills/ ``` -------------------------------- ### Hero Status and Adventures Query Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This GraphQL query fetches the current status of the player's hero, including regeneration details, current location (home village, oasis, or on adventure), and upcoming adventures. It also lists the player's villages. ```APIDOC ## GraphQL Query: Hero Status and Adventures ### Description Retrieves the hero's current status, regeneration information, and details about ongoing or upcoming adventures. Also lists the player's villages and their rally point status. ### Query ```graphql query { ownPlayer { hero { isRegenerating regenerationTimeLeft homeVillage { mapId, id, name } status { status inOasis { belongsTo { mapId, name } } inVillage { id, mapId, name, type } arrivalAt arrivalIn onWayTo { id, x, y, type, village { mapId, name } } } adventures { number mapId x y distance place difficulty travelingDuration } } villages { id mapId name hasRallyPoint x y } } } ``` ``` -------------------------------- ### GraphQL Query for Player Profile Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This query retrieves detailed information about a player, including their ID, name, tribe, alliance, hero details, ranks, villages, and profile information. It also fetches data for the current player's overview page. ```graphql query($uid: Int!, $subTabName: String!) { player(id: $uid) { id name tribeId alliance { id, tag } hero { gender horse imageHash level xp equipment { helmet { ...inventoryItemFields } leftHand { ...inventoryItemFields } rightHand { ...inventoryItemFields } body { ...inventoryItemFields } horse { ...inventoryItemFields } shoes { ...inventoryItemFields } } } ranks { populationRank population attackerRank attackerPoints defenderRank defenderPoints } villages { id name tribeId mapId population victoryPoints victoryPointsPerDay x y occupiedOases { bonus { amount, resourceType { id, code } } } region { id, name } typeText typeTitle } profile { ownProfile isNPC allowEdit gender location personalNote additionalLanguages countryFlag { language, languageName } descriptionPlain { description1, description2 } medalsGameworld { id, name, desc, code, type, rank } medalsLifetime { id, name, desc, code, imgUrl, width } daysPlaying } } ownPlayer { isSitter isLocked accessRights { readWriteMessages, buySpendGold, sendRaids } villages { id, sortIndex } } overviewPageFavouriteSubTabKey: favouriteTab(name: $subTabName) { key } } fragment inventoryItemFields on InventoryItem { typeId name attributes { description, descriptionDetails } tier: quality quality rarity } ``` -------------------------------- ### GraphQL Query for Hero Status and Adventures Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md This query fetches the current status of the player's hero, including regeneration time, home village, current status (in village, arrival time), and active adventures. ```graphql query { ownPlayer { hero { isRegenerating regenerationTimeLeft homeVillage { mapId id name } status { status inVillage { id mapId name type } arrivalAt arrivalIn } adventures { number mapId x y distance place difficulty travelingDuration } } villages { id mapId name hasRallyPoint x y } } } ``` -------------------------------- ### Python Class for GraphQL Queries Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This class simplifies executing GraphQL queries and retrieving specific data like player profiles or hero status. It requires an authenticated session to interact with the server. ```python import requests class TTWarsGraphQL: def __init__(self, server, session): self.server = server self.session = session # Already authenticated session def query(self, query_str, variables=None): """Execute a GraphQL query.""" payload = {'query': query_str} if variables: payload['variables'] = variables resp = self.session.post( f'https://{self.server}/api/graphql', json=payload, headers={'Content-Type': 'application/json'} ) return resp.json() def get_player(self, player_id): """Get player profile data.""" return self.query( 'query($uid: Int!) { player(id: $uid) { id, name, tribeId } }', {'uid': player_id} ) def get_hero(self): """Get hero status.""" return self.query(''' query { ownPlayer { hero { isRegenerating status { status } adventures { number, mapId, distance, travelingDuration } } } } ''') ``` -------------------------------- ### Upgrade Building in TTWars Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Attempts to upgrade a building at a specified slot ID. It finds the upgrade button and submits the upgrade request, including a CSRF token if available. ```python def upgrade_building(session, server, slot_id): """Attempt to upgrade a building at the given slot.""" url = f'https://{server}/build.php?id={slot_id}' html = session.get(url).text soup = BeautifulSoup(html, 'html.parser') # Look for upgrade button upgrade_btn = soup.find('button', class_='green') if upgrade_btn and 'upgrade' in str(upgrade_btn).lower(): # Extract CSRF token if needed token = soup.find('input', {'name': 'token'}) data = {'upgrade': 1} if token: data['token'] = token['value'] return session.post(url, data=data) return None ``` -------------------------------- ### GraphQL Query for Hero Status and Adventures Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This query retrieves the hero's current status, regeneration time, home village, and details about ongoing or upcoming adventures. It also lists the player's villages with rally point information. ```graphql query { ownPlayer { hero { isRegenerating regenerationTimeLeft homeVillage { mapId, id, name } status { status inOasis { belongsTo { mapId, name } } inVillage { id, mapId, name, type } arrivalAt arrivalIn onWayTo { id, x, y, type, village { mapId, name } } } adventures { number mapId x y distance place difficulty travelingDuration } } villages { id mapId name hasRallyPoint x y } } } ``` -------------------------------- ### TTWars Bot Class in Python Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md This class handles authentication and data retrieval from TTWars. It requires server details, username, and password for initialization. Use this to programmatically access game data. ```python import requests from bs4 import BeautifulSoup class TTWarsBot: def __init__(self, server, username, password): self.server = server self.session = requests.Session() self.login(username, password) def login(self, username, password): self.session.post(f'https://{self.server}/login', data={ 'name': username, 'password': password, 's1': 'Login' }) def get_production(self): html = self.session.get(f'https://{self.server}/dorf1.php').text soup = BeautifulSoup(html, 'html.parser') production = {} table = soup.find('table', id='production') for row in table.find('tbody').find_all('tr'): res = row.find('td', class_='res').text.strip().rstrip(':') amt = int(row.find('td', class_='num').text.strip().replace(',', '')) production[res] = amt return production def get_buildings(self): html = self.session.get(f'https://{self.server}/dorf2.php').text soup = BeautifulSoup(html, 'html.parser') buildings = [] for slot in soup.find_all('div', class_='buildingSlot'): buildings.append({ 'slot': slot.get('data-aid'), 'gid': slot.get('data-gid'), 'name': slot.get('data-name'), 'level': slot.find('div', class_='labelLayer').text }) return buildings # Usage bot = TTWarsBot('unl7.ttwars.com', 'your_username', 'your_password') print(bot.get_production()) print(bot.get_buildings()) ``` -------------------------------- ### GraphQL Query for Village Buildings Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This query fetches a list of buildings for each of the player's villages, including the building's ID, name, current level, and maximum possible level. ```graphql query { ownPlayer { villages { id name buildings { id gid name level maxLevel } } } } ``` -------------------------------- ### Player Profile Query Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This GraphQL query retrieves detailed information about a player's profile, including their ID, name, alliance, hero status, ranks, villages, and profile details. It also fetches data about the current player's access rights and favorite sub-tab. ```APIDOC ## GraphQL Query: Player Profile ### Description Retrieves comprehensive player data, including alliance information, hero details, village statistics, and profile settings. Also includes data for the current player's session and preferences. ### Query ```graphql query($uid: Int!, $subTabName: String!) { player(id: $uid) { id name tribeId alliance { id, tag } hero { gender horse imageHash level xp equipment { helmet { ...inventoryItemFields } leftHand { ...inventoryItemFields } rightHand { ...inventoryItemFields } body { ...inventoryItemFields } horse { ...inventoryItemFields } shoes { ...inventoryItemFields } } } ranks { populationRank population attackerRank attackerPoints defenderRank defenderPoints } villages { id name tribeId mapId population victoryPoints victoryPointsPerDay x y occupiedOases { bonus { amount, resourceType { id, code } } } region { id, name } typeText typeTitle } profile { ownProfile isNPC allowEdit gender location personalNote additionalLanguages countryFlag { language, languageName } descriptionPlain { description1, description2 } medalsGameworld { id, name, desc, code, type, rank } medalsLifetime { id, name, desc, code, imgUrl, width } daysPlaying } } ownPlayer { isSitter isLocked accessRights { readWriteMessages, buySpendGold, sendRaids } villages { id, sortIndex } } overviewPageFavouriteSubTabKey: favouriteTab(name: $subTabName) { key } } fragment inventoryItemFields on InventoryItem { typeId name attributes { description, descriptionDetails } tier: quality quality rarity } ``` ``` -------------------------------- ### GraphQL Query for Player Profile Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md This query retrieves detailed information about a player, including their ID, name, tribe, alliance, hero stats, ranks, and villages. ```graphql query($uid: Int!, $subTabName: String!) { player(id: $uid) { id, name, tribeId alliance { id, tag } hero { gender, horse, level, xp } ranks { populationRank, population, attackerRank, attackerPoints } villages { id, name, tribeId, mapId, population, x, y } } } ``` -------------------------------- ### Village Buildings Query Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This GraphQL query retrieves a list of buildings for each of the player's villages, including the building's ID, name, current level, and maximum possible level. ```APIDOC ## GraphQL Query: Village Buildings ### Description Fetches the list of buildings for each of the player's villages, detailing their ID, name, current level, and maximum level. ### Query ```graphql query { ownPlayer { villages { id name buildings { id gid name level maxLevel } } } } ``` ``` -------------------------------- ### Parse Hero Adventures Data Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Parses a list of hero adventures from game data to extract details like adventure number, coordinates, distance, duration, and difficulty. Requires the 'adventures' data structure. ```python # Parse adventures from hero_adventures page adventures = data['data']['ownPlayer']['hero']['adventures'] for adv in adventures: print(f"Adventure #{adv['number']}: " f"({adv['x']},{adv['y']}) " f"Distance: {adv['distance']} " f"Duration: {adv['travelingDuration']}s " f"Difficulty: {'hard' if adv['difficulty'] == 0 else 'normal'}") ``` -------------------------------- ### Building Level Display Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/buildings.md HTML structure for displaying the current level of a building, including state classes. ```html
5
``` -------------------------------- ### Monitor Resources in TTWars Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Polls the dorf1.php page to extract current resource production levels. Requires a BeautifulSoup-enabled session. ```python def monitor_resources(session, server): """Poll dorf1.php to track resource levels.""" html = session.get(f'https://{server}/dorf1.php').text soup = BeautifulSoup(html, 'html.parser') production = {} prod_table = soup.find('table', id='production') for row in prod_table.find('tbody').find_all('tr'): res = row.find('td', class_='res').text.strip().rstrip(':') amt = int(row.find('td', class_='num').text.strip().replace(',', '')) production[res] = amt return production ``` -------------------------------- ### Resource Fields and Production HTML Structure Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/page-structure.md This snippet shows the HTML structure for resource fields and production tables on the dorf1.php page. It includes elements for resource field slots and a table detailing hourly production rates. ```html
20
Produksi per jam:
Kayu: 4,900,000
Pasukan:
1 kesatria
3,024,023,111 Phalanx
``` -------------------------------- ### Parse Village Resource Production Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Parses resource production per hour from the dorf1.php page. It identifies the production table by its ID and extracts resource names and amounts. ```python # Parse resource production from dorf1.php # The production table uses class "villageInfobox production" from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'html.parser') production = soup.find('table', id='production') for row in production.find('tbody').find_all('tr'): resource = row.find('td', class_='res').text.strip().rstrip(':') amount = row.find('td', class_='num').text.strip().replace(',', '') print(f"{resource}: {int(amount)}/hour") ``` -------------------------------- ### Default Map Data Options Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/page-structure.md Initial map data embedded for AJAX loading. Contains elements with positions and symbols like adventures. ```javascript Travian.Game.Map.Options.Default.data = { "elements": [ { "position": {"x": 21, "y": 62}, "symbols": [{ "dataId": "adventure681", "type": "adventure", "parameters": {"difficulty": 1}, "title": "Petualangan" }] } ] }; ``` -------------------------------- ### Parse Village Building Slots Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Parses building slots and their details from the dorf2.php page. It extracts slot ID, building type ID, building name, and current level. ```python # Parse building slots from dorf2.php # Each building has data attributes: data-aid, data-gid, data-name for slot in soup.find_all('div', class_='buildingSlot'): aid = slot.get('data-aid') # Slot ID (19-40) gid = slot.get('data-gid') # Building type ID name = slot.get('data-name') # Building name level_el = slot.find('div', class_='labelLayer') level = level_el.text if level_el else '0' print(f"Slot {aid}: {name} (gid={gid}) Level {level}") ``` -------------------------------- ### GraphQL Query for Hero Status Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/README.md This query retrieves the status of the player's hero, including regeneration status, home village details, and active adventures. ```graphql query { ownPlayer { hero { isRegenerating homeVillage { mapId name } adventures { number mapId x y distance travelingDuration } } } } ``` -------------------------------- ### Map Data Query Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This GraphQL query retrieves data for a specific tile on the map, including its ID, coordinates, type, and information about any village present on that tile, such as the village name, population, and owner's player and alliance details. ```APIDOC ## GraphQL Query: Map Data ### Description Retrieves detailed information about a specific map tile, including its coordinates, type, and any village located on it, along with the village owner's details. ### Query ```graphql query($x: Int!, $y: Int!) { mapTile(x: $x, y: $y) { id x y type village { id name population player { id, name, alliance { id, tag } } } } } ``` ``` -------------------------------- ### GraphQL Query for Map Data Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md This query retrieves information about a specific tile on the map, including its type and any village present on it, along with the village's owner and alliance details. ```graphql query($x: Int!, $y: Int!) { mapTile(x: $x, y: $y) { id x y type village { id name population player { id, name, alliance { id, tag } } } } } ``` -------------------------------- ### Extract GraphQL Query and View Data from HTML Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Use regular expressions to find and extract GraphQL queries and embedded viewData from a page's HTML source. The extracted query string needs to be unescaped. ```python import re, json # Find GraphQL query in page source gql_match = re.search(r'gql:\s*"((?:[^"\\]|\\.)*)"', html) if gql_match: query = gql_match.group(1).replace('\"', '"').replace('\\n', '\n') print(query) # Extract viewData (response data embedded in page) view_match = re.search(r'viewData:\s*(\{.*?\}),\s*activePerspective', html, re.DOTALL) if view_match: data = json.loads(view_match.group(1)) ``` -------------------------------- ### Auto Adventure in TTWars Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Sends the hero on the shortest available adventure by parsing adventure data from the hero adventures page. It sorts adventures by duration and sends the hero to the chosen one. ```python def auto_adventure(session, server, prefer_short=True): """Send hero on the shortest available adventure.""" # Get adventures from page html = session.get(f'https://{server}/hero_adventures').text # Extract GraphQL data match = re.search(r'viewData:\s*(\{.*?\})\s*,\s*activePerspective', html, re.DOTALL) if not match: return data = json.loads(match.group(1)) adventures = data['data']['ownPlayer']['hero']['adventures'] if not adventures: return # Sort by duration (shortest first) adventures.sort(key=lambda a: a['travelingDuration']) # Pick best adventure target = adventures[0] if prefer_short else adventures[-1] # Send hero (endpoint varies, check page for button action) rally_point = None for v in data['data']['ownPlayer']['villages']: if v['hasRallyPoint']: rally_point = v['id'] break if rally_point: session.post(f'https://{server}/build.php?id={rally_point}', data={ 'action': 'adventure', 'mapId': target['mapId'] }) ``` -------------------------------- ### Parse Village Troop Counts Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md Parses troop counts from the village info box on dorf1.php. It extracts the troop name, unit class identifier, and the number of troops. ```python # Parse troops from the village info box troops_table = soup.find('table', id='troops') for row in troops_table.find('tbody').find_all('tr'): unit_img = row.find('img', class_=True) unit_class = [c for c in unit_img['class'] if c.startswith('u')][-1] count = row.find('td', class_='num').text.strip().replace(',', '') name = row.find('td', class_='un').text.strip() print(f"{name} ({unit_class}): {count}") ``` -------------------------------- ### Building Slot Data Attributes Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/buildings.md HTML attributes used to identify building slots and their properties on the village overview page. ```html
``` -------------------------------- ### Embedded Hero Data JSON Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/page-structure.md This JavaScript snippet shows how full JSON data for the hero is embedded within a script tag. It contains configuration for the hero's active tab, favorite tab, and screen properties, useful for initializing the hero interface. ```javascript window.Travian.React.Hero.render( { "activeTabKey": "inventory", "favouriteTabKey": null, "tabBarName": "heroV2", "screenProps": { "inventory": {"knowledgeBaseLink": null}, "attributes": {"knowledgeBaseLink": null}, "appearance": {"knowledgeBaseLink": null} } }, ["allgemein", "hero", "heroAppearance", "items", "build", "plus", "karte", "crafting"] ); ``` -------------------------------- ### Extract View Data from HTML Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md A Python function to extract pre-fetched viewData, which is a JSON object, from the page's initialization script. This data can be used to avoid re-fetching common information. ```python def extract_view_data(html: str) -> dict: """Extract pre-fetched viewData from page source.""" import json match = re.search(r'viewData:\s*(\{.*\})\s*,\s*(?:activePerspective|playerId)', html, re.DOTALL) if match: return json.loads(match.group(1)) return {} ``` -------------------------------- ### Convert Coordinates to Map ID and Vice Versa Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/skills/ttwars-automation/SKILL.md These Python functions convert between (x, y) coordinates and a unique map ID, considering map width. Useful for referencing specific map locations. ```python # Convert coordinates to mapId (approximate) # Map width is typically 201 (-100 to +100) or 401 (-200 to +200) def coords_to_mapid(x, y, map_width=401): return (y + map_width // 2) * map_width + (x + map_width // 2) def mapid_to_coords(map_id, map_width=401): y = map_id // map_width - map_width // 2 x = map_id % map_width - map_width // 2 return x, y ``` -------------------------------- ### Village Building Slot HTML Structure Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/page-structure.md This HTML structure represents a single building slot within the village center. It includes attributes for slot ID, building type, name, and level, useful for identifying and managing buildings. ```html
``` -------------------------------- ### Extract GraphQL Query from HTML Source: https://github.com/adit7494/ttwars-bot-skills/blob/master/reference/graphql-queries.md A Python function to parse HTML content and extract the GraphQL query string. It handles escaped quotes and newlines within the query. ```python import re def extract_graphql(html: str) -> str: """Extract GraphQL query from page source.""" match = re.search(r'gql:\s*"((?:[^"\\]|\\.)*)"', html) if match: query = match.group(1) query = query.replace('\"', '"') query = query.replace('\n', '\n') return query return '' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.