comlink-python
Description
A python wrapper for the swgoh-comlink tool, plus an in-package local stat calculator (StatCalc).
Supports both synchronous and asynchronous usage via SwgohComlink and SwgohComlinkAsync.
Requires Python 3.11 or higher. Free-threaded CPython builds are supported as beta: the test suite runs on 3.14t, and Threads and Event Loops lists what you can share between threads.
Installation
Install from PyPI:
# Add to a uv-managed project
uv add swgoh_comlink
# Or install with pip
pip install swgoh_comlink
Full documentation, including the API reference, is at swgoh-utils.github.io/comlink-python.
Synchronous Usage
Basic default usage:
from swgoh_comlink import SwgohComlink
comlink = SwgohComlink()
player_data = comlink.get_player(allycode=245866537)
player_name = player_data['name']
guild_id = player_data['guildId']
guild = comlink.get_guild(guild_id=guild_id)
guild_name = guild['profile']['name']
With a custom comlink URL:
from swgoh_comlink import SwgohComlink
comlink = SwgohComlink(url='http://localhost:3500')
player_data = comlink.get_player(allycode=245866537)
With an external swgoh-stats service:
from swgoh_comlink import SwgohComlink
comlink = SwgohComlink(url='http://localhost:3500', stats_url='http://localhost:3550')
player_data = comlink.get_player(allycode=245866537)
player_roster = player_data['rosterUnit']
roster_with_stats = comlink.get_unit_stats(player_roster)
With HMAC authentication:
from swgoh_comlink import SwgohComlink
comlink = SwgohComlink(
url='http://localhost:3000',
access_key='public_key',
secret_key='this_string_should_be_secret'
)
player_data = comlink.get_player(allycode=245866537)
As a context manager (auto-closes connections):
from swgoh_comlink import SwgohComlink
with SwgohComlink() as comlink:
player_data = comlink.get_player(allycode=245866537)
Async Usage
The SwgohComlinkAsync class provides the same API with async/await support. All public methods have identical signatures to the sync client.
from swgoh_comlink import SwgohComlinkAsync
async with SwgohComlinkAsync() as comlink:
player_data = await comlink.get_player(allycode=245866537)
player_name = player_data['name']
guild_id = player_data['guildId']
guild = await comlink.get_guild(guild_id=guild_id)
guild_name = guild['profile']['name']
Without a context manager, call aclose() when done:
comlink = SwgohComlinkAsync()
try:
player_data = await comlink.get_player(allycode=245866537)
finally:
await comlink.aclose()
Both clients accept the same constructor parameters and support connection pooling via persistent httpx2 clients.
StatCalc / StatCalcAsync (Local Stat Calculator)
StatCalc and StatCalcAsync calculate unit stats and Galactic Power locally without requiring an external swgoh-stats service. StatCalc fetches game data synchronously on initialization; StatCalcAsync provides an async factory method (await StatCalcAsync.create()) for non-blocking initialization. Both accept pre-loaded data for offline use.
Building game data from Comlink
Instead of fetching a static gameData.json from GitHub, you can build game data
dynamically from a running Comlink service using GameDataBuilder / GameDataBuilderAsync:
from swgoh_comlink import SwgohComlink, StatCalc, GameDataBuilder
comlink = SwgohComlink()
game_data = GameDataBuilder(comlink).build()
calc = StatCalc(game_data=game_data)
Async:
from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync, GameDataBuilderAsync
async with SwgohComlinkAsync() as comlink:
game_data = await GameDataBuilderAsync(comlink).build()
calc = StatCalcAsync(game_data=game_data)
The builder fetches only the required game data collections in a single API call
and transforms them into the format StatCalc expects.
Basic usage
from swgoh_comlink import SwgohComlink, StatCalc
comlink = SwgohComlink()
calc = StatCalc() # fetches latest game data from GitHub on init
# Calculate stats for a full player roster
player = comlink.get_player(allycode=245866537)
calc.calc_roster_stats(player['rosterUnit'])
# Or calculate stats for a single character
unit = {
"defId": "BOSSK",
"rarity": 7,
"level": 85,
"gear": 13,
"equipped": [],
"skills": [],
}
calc.calc_char_stats(unit)
print(unit["stats"]) # final stats, mods, and GP added in-place
print(unit["gp"]) # galactic power
Offline / pre-loaded game data
calc = StatCalc(game_data=my_game_data_dict)
Async usage (StatCalcAsync)
StatCalcAsync provides an async factory method for fetching game data without blocking the event loop. Its acalc_char_stats, acalc_ship_stats, acalc_roster_stats and acalc_player_stats methods run the matching calc_* method on the calculator's own worker threads, so a large roster does not stall the event loop. With the GIL there is one worker, so concurrent calls on one calculator queue (see max_workers, aclose() and aset_game_data() in the StatCalc API). The inherited synchronous calc_* methods still work but block the loop while they run.
from swgoh_comlink import SwgohComlinkAsync, StatCalcAsync
async with SwgohComlinkAsync() as comlink:
calc = await StatCalcAsync.create() # fetches game data from GitHub async
player = await comlink.get_player(allycode=245866537)
await calc.acalc_roster_stats(player['rosterUnit'])
With pre-loaded game data (no async fetch needed):
calc = StatCalcAsync(game_data=my_game_data_dict)
StatCalc / StatCalcAsync Methods
| Method | Description |
|---|---|
calc_char_stats(unit) |
Calculate stats and GP for a single character (modifies in-place) |
calc_ship_stats(unit, crew) |
Calculate stats and GP for a ship with its crew |
calc_roster_stats(units) |
Calculate stats for all units in a roster (list or dict) |
calc_player_stats(players) |
Calculate stats for one or more full player payloads |
calc_char_gp(char) |
Calculate GP for a character |
calc_ship_gp(ship, crew) |
Calculate GP for a ship |
set_game_data(game_data) |
Replace the game data used by the calculator |
Parameters
Constructor parameters for SwgohComlink and SwgohComlinkAsync:
| Parameter | Type | Default | Description |
|---|---|---|---|
url |
str |
http://localhost:3000 |
URL where swgoh-comlink is running |
stats_url |
str |
http://localhost:3223 |
URL where swgoh-stats service is running |
access_key |
str |
None |
HMAC public key. Also reads from COMLINK_ACCESS_KEY env var (ACCESS_KEY is deprecated) |
secret_key |
str |
None |
HMAC private key. Also reads from COMLINK_SECRET_KEY env var (SECRET_KEY is deprecated) |
host |
str |
None |
Server hostname (overrides url and stats_url) |
port |
int |
None |
Comlink TCP port. With host it defaults to 3000; without host it replaces the port in url |
stats_port |
int |
None |
Stats service TCP port. With host it defaults to 3223; without host it replaces the port in stats_url |
verify_ssl |
bool |
True |
Enable TLS certificate verification |
version_cache_ttl |
float |
3600 |
Seconds to cache game/localization versions from /metadata (see below) |
retry |
RetryPolicy |
None |
Keyword-only. Retry rate refusals and HTTP 503, and optionally pace calls. None makes one attempt per call (see Retries and Rate Limits) |
max_response_bytes |
int |
None |
Keyword-only. Largest decoded response body accepted from any endpoint except /data. None means no limit |
max_game_data_bytes |
int |
None |
Keyword-only. The same limit for /data (get_game_data()) |
timeout |
float or httpx2.Timeout |
None |
Keyword-only. Timeout for every endpoint except /data. None means 120 s. A number applies to each phase (connect, send, read) on its own |
game_data_timeout |
float or httpx2.Timeout |
None |
Keyword-only. The same for /data. None means 300 s |
limits |
httpx2.Limits |
None |
Keyword-only. Connection pool limits for both underlying clients. None keeps the httpx2 defaults: 100 connections, 20 kept alive, idle ones closed after 5 s |
url must be an http or https URL with a host; anything else raises SwgohComlinkValueError when the client is built.
The Configuration guide covers how
url, host and the ports combine, the environment variables, timeouts and the pool limits.
Version caching
Calls to /data and /localization require the current latestGamedataVersion /
latestLocalizationBundleVersion values from the /metadata endpoint. When you call
get_game_data(), get_localization(), or get_latest_game_data_version() without an explicit
version, the client fetches these values once and caches them on the instance for
version_cache_ttl seconds (default: 1 hour), instead of making a fresh /metadata request every
time.
- Pass
version_cache_ttl=0to disable caching (the pre-v2.3 behavior), ormath.infto cache for the client's lifetime. - Explicit
version=/localization_id=arguments always bypass the cache. - Call
invalidate_version_cache()orget_latest_game_data_version(refresh=True)to force a re-fetch, e.g. right after a game update lands. - A successful
get_game_metadata()call also refreshes the cache opportunistically.
Enums caching
get_enums() caches its response on the instance as enums, together with the game data version
it was fetched under as enums_version. Later calls return the cached response while that version
is unchanged, and fetch the enums again once it changes. The version check goes through the version
cache above, so it usually makes no request.
get_enums(refresh=True)fetches the version and the enums again.enums_cachereturns both as oneCachedEnumsrecord (.enums,.version). Read it instead of the two attributes when they must match while another thread may be refreshing them.- When the version cannot be determined (for example
/metadatafails), the enums are fetched and returned without being cached. - The cached response is shared: copy it before changing it.
Available Methods
Methods available on both SwgohComlink and SwgohComlinkAsync (async methods use await):
| Method | Description |
|---|---|
get_player(allycode, player_id, enums) |
Get player data by allycode or player ID |
get_player_arena(allycode, player_id, player_details_only, enums) |
Get player arena profile |
get_guild(guild_id, include_recent_guild_activity_info, enums) |
Get guild data by guild ID |
get_guilds_by_name(name, start_index, count, enums) |
Search guilds by name |
get_guilds_by_criteria(search_criteria, start_index, count, enums) |
Search guilds by criteria |
get_game_data(version, include_pve_units, request_segment, enums, items, device_platform, *, strip_empty) |
Get game data collections (select them with items=DataItems...; strip_empty=True drops the empty ones) |
get_game_metadata(client_specs, enums) |
Get current game and localization versions |
get_localization(localization_id, locale, unzip, enums) |
Get localization bundles |
get_enums(refresh) |
Get game data enums (cached per game data version) |
get_events(enums) |
Get current game events |
get_leaderboard(leaderboard_type, league, division, ...) |
Get GAC leaderboard data |
get_guild_leaderboard(leaderboard_id, count, enums) |
Get guild leaderboard data |
get_unit_stats(request_payload, flags, language) |
Calculate unit stats via swgoh-stats |
get_latest_game_data_version(refresh) |
Get latest game data and language versions (cached) |
invalidate_version_cache() |
Discard cached versions so the next lookup re-fetches /metadata |
get_name_spaces(only_compatible, enums) |
Deprecated. Comlink no longer has this route, so it answers HTTP 404. Warns, and is removed in v3 |
get_segmented_content(content_name_space, accept_language, enums) |
Retrieve segmented content |
get_livez() |
Check that Comlink is alive ({"status": "ok"}). One attempt, never retried |
get_readyz() |
Check that Comlink is ready to answer game requests. One attempt, never retried |
swgoh_comlink.__version__ holds the installed version (swgoh_comlink.version is the same value).
Retries and Rate Limits
By default a client makes one attempt per call. Pass retry=RetryPolicy(...) to retry rate refusals and
HTTP 503, optionally retry failures to connect, and space calls to one endpoint so a burst stays under the game's
limit. See Retries and Rate Limits.
from swgoh_comlink import RetryPolicy, SwgohComlink
comlink = SwgohComlink(retry=RetryPolicy(attempts=5, min_interval=0.4))
Error Handling
Every error the clients raise is a SwgohComlinkException. Network failures raise SwgohComlinkTransportError or one
of its subclasses, which tell a request that was never sent (SwgohComlinkConnectionError) from one that may have
reached Comlink (SwgohComlinkTimeoutError); HTTP errors raise SwgohComlinkHTTPError or a subclass. All of them can
be imported from swgoh_comlink. See Errors.
Examples
The examples/ directory contains runnable scripts for common tasks using both the sync and async clients.
Synchronous (examples/Sync/)
| Script | Description |
|---|---|
get_player.py |
Get a player's full profile including roster |
get_guild.py |
Look up guild info from a player's ally code |
get_events.py |
Retrieve current game events with timestamps |
get_game_data.py |
Retrieve game data collections |
get_gac_leaderboard.py |
Get GAC leaderboard data |
get_gac_brackets.py |
Scan GAC brackets and search for a player |
calc_stats_local.py |
Calculate character stats locally with StatCalc |
search_for_guilds.py |
Search for guilds by name or criteria |
guild_omicron_breakdown.py |
Report omicron adoption across a guild by game mode |
Asynchronous (examples/Async/)
| Script | Description |
|---|---|
get_player.py |
Get a player's full profile using await |
concurrent_requests.py |
Fetch multiple players in parallel with asyncio.gather() |
streaming_guild_roster.py |
Fetch all guild members concurrently with asyncio.TaskGroup |
streaming_guild_roster_advanced.py |
Production-quality guild roster fetch with CLI args and retry logic |
guild_omicron_breakdown.py |
Report omicron adoption across a guild, fetching member profiles concurrently |
calc_stats_local.py |
Calculate character stats locally with StatCalcAsync |
See the full examples listing for all available scripts and usage details.
Logging
Logging is handled by the python logging module. The library follows Python best practice by attaching only a NullHandler — no output is produced unless your application configures logging.
For details on enabling and customizing log output, see docs/logging.md.
Upgrading to v2.10
v2.10 runs on httpx2, Pydantic's maintained fork of httpx, instead of httpx. Most code needs no changes. If you pass limits=, use the HTTP objects directly, configure the httpx loggers, or run without OS CA certificates, see v2.10: httpx2 replaces httpx. The legacy httpx package still works until v3 through the deprecated swgoh_comlink[httpx] extra.
Migrating from v1.x
v2 replaced requests with httpx (httpx2 since v2.10) and changed how logging is configured. If you are upgrading from a previous version, see the Migration Guide for a walkthrough of required changes:
- Replace
requestswithhttpx2in your dependencies - Update
except requests.RequestExceptiontoexcept SwgohComlinkException(network errors are wrapped in it) - Update any
get_logger(log_level=...)calls — configure logging via the standardloggingmodule instead - Use a context manager (
with SwgohComlink() ...) or callclose()to release connections
Test Configuration
Integration tests are opt-in and require a running comlink service:
# Run integration tests (requires comlink on localhost:3000)
RUN_INTEGRATION_TESTS=1 uv run pytest tests/integration/ -v
# Run with HMAC tests (requires comlink-hmac on localhost:3001)
HMAC_ACCESS_KEY=your_key HMAC_SECRET_KEY=your_secret \
RUN_INTEGRATION_TESTS=1 uv run pytest tests/integration/ -v
HMAC tests are automatically skipped when HMAC_ACCESS_KEY and HMAC_SECRET_KEY environment variables are not set.
See the online wiki for more information.
Support
Usage questions are best asked in the Discord server. Bugs and feature requests go in GitHub issues. See SUPPORT.md for where to report what.
Contributing
Contributions are welcome! See CONTRIBUTING.md for the development setup, workflow, and conventions. This project follows a Code of Conduct.
Security
Please report security vulnerabilities privately as described in SECURITY.md, not in public issues.
License
Released under the MIT License.
Metadata
Release files for swgoh-comlink 2.10.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| swgoh_comlink-2.10.0.tar.gz | 251.6 kB | With provenance | Details for swgoh_comlink-2.10.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| swgoh_comlink-2.10.0-py3-none-any.whl | Python 3 | none | any | Details for swgoh_comlink-2.10.0-py3-none-any.whl |
Total release size: 441.9 kB
Release files / swgoh_comlink-2.10.0.tar.gz
| Download URL | swgoh_comlink-2.10.0.tar.gz |
|---|---|
| Size | 251.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
da50717d2ad9a698c1b7378f85b95b0f4faf1cacc9e1c7682ac42cfb36749919
|
|
BLAKE2b-256 checksum How to use checksums |
b9846fa09d2bac60ec636e34e55c4a90520e28edcbcdcfd182b8762fbb0d37c5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / swgoh_comlink-2.10.0-py3-none-any.whl
| Download URL | swgoh_comlink-2.10.0-py3-none-any.whl |
|---|---|
| Size | 190.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
978c0ba836670e31e66c7fc00404311e9f1d00370c5c95ebf4df3d359d51e45d
|
|
BLAKE2b-256 checksum How to use checksums |
709214c146f4499b7d622e0c9bd0d6f375d0167b07d2e133747ca0d5ba529bca
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logSecurity for swgoh-comlink 2.10.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for swgoh_comlink-2.10.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.