From 07bffd6a960cf0a1afc6623bbbbf33997a2d553a Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:55:49 -0500 Subject: [PATCH 1/3] fix(helpers): accept tier 0 in is_omicron_skill is_omicron_skill treated a tier of 0 as missing and raised, both for a roster_unit_skill and for a skill_tier passed directly. Tier 0 is the value a freshly unlocked skill carries, and a skill whose only tier is its omicron has the omicron at index 0, so only a missing tier is now an error. Co-Authored-By: Claude Opus 5.5 --- src/swgoh_comlink/helpers/_omicron.py | 5 +++-- tests/unit/test_helpers.py | 3 +++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/swgoh_comlink/helpers/_omicron.py b/src/swgoh_comlink/helpers/_omicron.py index 6063e71..d0ace5e 100644 --- a/src/swgoh_comlink/helpers/_omicron.py +++ b/src/swgoh_comlink/helpers/_omicron.py @@ -116,13 +116,14 @@ def is_omicron_skill( if roster_unit_skill is not None: skill_id = roster_unit_skill.get("id") skill_tier = roster_unit_skill.get("tier") - if not skill_id or not skill_tier: + # Tier 0 is a legitimate value for a freshly unlocked skill, so only a missing tier is an error. + if not skill_id or skill_tier is None: raise SwgohComlinkValueError("Invalid 'roster_unit_skill' argument.") else: # Validate that skill_id and skill_tier were provided directly if not isinstance(skill_id, str): raise SwgohComlinkValueError(f"'skill_id' must be a string, not {type(skill_id)}") - if not skill_id or not skill_tier: + if not skill_id or skill_tier is None: raise SwgohComlinkValueError( "'skill_id' and 'skill_tier' are required when 'roster_unit_skill' is not provided." ) diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 065bc53..53533fa 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -333,6 +333,9 @@ def test_get_omicron_skill_tier(skill, expected): pytest.param(_SKILL_LIST, {"roster_unit_skill": {"id": "skill_A", "tier": 1}}, True, id="roster-unit-skill"), pytest.param(_SKILL_LIST, {"skill_id": "nonexistent", "skill_tier": 1}, False, id="not-in-list"), pytest.param([_SKILL_LIST[1]], {"skill_id": "skill_B", "skill_tier": 1}, False, id="skill-without-omicron"), + # Tier 0 is a freshly unlocked skill, not a missing tier; skill_C has its omicron at tier index 0. + pytest.param(_SKILL_LIST, {"skill_id": "skill_A", "skill_tier": 0}, False, id="direct-tier-zero"), + pytest.param(_SKILL_LIST, {"roster_unit_skill": {"id": "skill_C", "tier": 0}}, True, id="roster-tier-zero"), ], ) def test_is_omicron_skill(skills, kwargs, expected): From ff158cd4891acda6823387e4bee925d1c6503c85 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 13:59:20 -0500 Subject: [PATCH 2/3] feat(helpers): add get_omicron_breakdown for guild-wide omicron adoption Summarise omicron adoption across a set of player profiles, grouped by game mode. Every omicron skill in game data becomes a row that splits the players into those who have applied it, those who own the unit but have not, and a count of those who do not own the unit. A skill is an omicron when one of its tiers is flagged isOmicronTier, never because of its omicronMode: mode 1 (ALL_OMICRON) is the value every skill without an omicron carries. The mode is read as a number whether the game data was fetched with enums=False or enums=True, including the type-prefixed spelling, through parse_enum and the OmicronMode members; a mode name the library does not know yet is kept as given. Labels default to OMICRON_MODE and can be overridden. Ownership is a property of the unit, resolved through the unit that can be in a roster. Many omicron skills are referenced by several base IDs, a playable unit plus a non-obtainable PVE_ mirror and sometimes an event variant, so playable units (get_playable_units, which also reads an enums=True rarity) claim their skills first. A skill missing from an owner's roster is star-gated, not evidence of non-ownership, and a listed skill without a tier is at tier 0. An optional ability_list names each omicron from the ability its skill references; a skill's own nameKey is a placeholder shared across unrelated skills, and a unit often has several omicrons in one mode. Unit and omicron names are localized through _localize. Co-Authored-By: Claude Opus 5.5 --- docs/api/helpers.md | 63 ++++++ src/swgoh_comlink/helpers/__init__.py | 10 + src/swgoh_comlink/helpers/_omicron.py | 294 +++++++++++++++++++++++++- tests/unit/test_helpers.py | 266 +++++++++++++++++++++++ 4 files changed, 632 insertions(+), 1 deletion(-) diff --git a/docs/api/helpers.md b/docs/api/helpers.md index e9f9ae0..7b48679 100644 --- a/docs/api/helpers.md +++ b/docs/api/helpers.md @@ -1207,6 +1207,69 @@ Functions for querying omicron skill data from game data collections. show_root_heading: true show_root_full_path: false +### get_omicron_breakdown + +Summarizes omicron adoption across a set of player profiles, grouped by game mode. For every +omicron in game data it lists the players who have applied it, the players who own the unit +but have not, and how many do not own the unit. + +It takes **player profiles**, not guild member entries: a guild's `member` list carries no +roster, so fetch each member's profile first. Pass `ability_list` whenever a person will read +the result. A unit often has several omicrons in one mode, so the unit name alone does not +tell the rows apart, and the omicron's own name comes from the `ability` collection. + +```python +from swgoh_comlink import SwgohComlink +from swgoh_comlink.helpers import DataItems, get_guild_members, get_localization_dictionary, get_omicron_breakdown + +comlink = SwgohComlink() +members = get_guild_members(comlink, allycode=314927874) +profiles = [comlink.get_player(player_id=member["playerId"]) for member in members] +game_data = comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, include_pve_units=False +) + +breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=get_localization_dictionary(comlink), +) +for mode in breakdown["modes"]: + for row in mode["skills"]: + print(mode["mode_name"], row["unit_name"], row["skill_name"], len(row["applied"])) +``` + +See `examples/Sync/guild_omicron_breakdown.py` for a full report, and +`examples/Async/guild_omicron_breakdown.py` for the same report with the profiles fetched +concurrently. + +::: swgoh_comlink.helpers._omicron.get_omicron_breakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronBreakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronModeBreakdown + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronSkillStats + options: + show_root_heading: true + show_root_full_path: false + +::: swgoh_comlink.helpers._omicron.OmicronMember + options: + show_root_heading: true + show_root_full_path: false + --- ## Localization Helpers diff --git a/src/swgoh_comlink/helpers/__init__.py b/src/swgoh_comlink/helpers/__init__.py index ab90e5b..f5d0811 100644 --- a/src/swgoh_comlink/helpers/__init__.py +++ b/src/swgoh_comlink/helpers/__init__.py @@ -61,6 +61,11 @@ parse_swgoh_string, ) from ._omicron import ( + OmicronBreakdown, + OmicronMember, + OmicronModeBreakdown, + OmicronSkillStats, + get_omicron_breakdown, get_omicron_skill_tier, get_omicron_skills, get_tw_omicrons, @@ -217,6 +222,11 @@ "get_named_rewards", "get_player_title_names", # Omicron + "OmicronBreakdown", + "OmicronMember", + "OmicronModeBreakdown", + "OmicronSkillStats", + "get_omicron_breakdown", "get_omicron_skill_tier", "get_omicron_skills", "get_tw_omicrons", diff --git a/src/swgoh_comlink/helpers/_omicron.py b/src/swgoh_comlink/helpers/_omicron.py index d0ace5e..afb24c9 100644 --- a/src/swgoh_comlink/helpers/_omicron.py +++ b/src/swgoh_comlink/helpers/_omicron.py @@ -3,9 +3,38 @@ from __future__ import annotations -from typing import Any, NamedTuple +from collections.abc import Mapping +from typing import Any, NamedTuple, TypedDict from ..exceptions import SwgohComlinkValueError +from ._game_data import get_playable_units +from ._localization import _localize +from ._stat_data import OMICRON_MODE +from ._utils import get_function_name +from ._wire import as_int, as_list, as_scalar, as_str, base_id, parse_enum + +# OmicronMode members. omicronMode arrives as a number (enums=False) or a member name (enums=True), bare +# (TERRITORY_WAR_OMICRON) or type-prefixed (OMICRONMODE_TERRITORYWAROMICRON); parse_enum reads all three. +_OMICRON_MODES: dict[str, int] = { + "OmicronMode_DEFAULT": 0, + "ALL_OMICRON": 1, + "PVE_OMICRON": 2, + "PVP_OMICRON": 3, + "GUILD_RAID_OMICRON": 4, + "TERRITORY_STRIKE_OMICRON": 5, + "TERRITORY_COVERT_OMICRON": 6, + "TERRITORY_BATTLE_BOTH_OMICRON": 7, + "TERRITORY_WAR_OMICRON": 8, + "TERRITORY_TOURNAMENT_OMICRON": 9, + "WAR_OMICRON": 10, + "CONQUEST_OMICRON": 11, + "GALACTIC_CHALLENGE_OMICRON": 12, + "PVE_EVENT_OMICRON": 13, + "TERRITORY_TOURNAMENT_3_OMICRON": 14, + "TERRITORY_TOURNAMENT_5_OMICRON": 15, + "GALACTIC_CHALLENGE_3_OMICRON": 16, + "GALACTIC_CHALLENGE_5_OMICRON": 17, +} class Unit(NamedTuple): @@ -177,3 +206,266 @@ def skill_exists(value: Any, dict_list: list[dict[str, Any]] | None) -> bool: ), None, ) + + +# ── Guild omicron breakdown ───────────────────────────────────────────── + + +class OmicronMember(TypedDict): + """One player's standing on a single omicron, as listed in :class:`OmicronSkillStats`.""" + + player_id: str + player_name: str + tier: int | None + """The tier the player has taken the skill to, or ``None`` when they own the unit but the skill is + absent from their roster: a star-gated skill is left out until the unit reaches the rarity that + unlocks it.""" + + +class OmicronSkillStats(TypedDict): + """Adoption of one omicron skill, as listed in :attr:`OmicronModeBreakdown.skills`. + + ``len(applied) + len(owned_not_applied) + not_owned_count`` always equals + :attr:`OmicronBreakdown.total_members`. + """ + + skill_id: str + """The game data ``skill`` id carrying the omicron tier.""" + skill_name_key: str | None + """Localization key of the omicron's name, read from the ``ability`` the skill references. ``None`` + when no ``ability_list`` was given. The skill's own ``nameKey`` is a placeholder shared across + unrelated skills (``DEFENSE_UP_NAME_KEY``) and is not used.""" + skill_name: str | None + """Localized omicron name, when both ``ability_list`` and ``localization`` were given.""" + unit_base_id: str | None + """The unit the skill belongs to, or ``None`` when no unit in ``unit_list`` references it.""" + unit_name_key: str | None + unit_name: str | None + """Localized unit name, when ``localization`` was given and holds the key.""" + omicron_tier: int + """Index into the game data skill's ``tier`` list at which the omicron applies.""" + applied: list[OmicronMember] + """Players who own the unit and have taken the skill to the omicron tier.""" + owned_not_applied: list[OmicronMember] + """Players who own the unit but have not.""" + not_owned_count: int + """Players who do not own the unit.""" + + +class OmicronModeBreakdown(TypedDict): + """Every omicron of one game mode, as listed in :attr:`OmicronBreakdown.modes`.""" + + mode: int | str + """The skills' ``omicronMode`` as a number (see ``OMICRON_MODE``), whether the game data was fetched + with ``enums=True`` or not. A mode name the library does not know yet is kept as given.""" + mode_name: str + """Label from ``mode_names``, or ``"Mode "`` when it has none.""" + skills: list[OmicronSkillStats] + """Ordered by applied count, highest first, then by skill id.""" + + +class OmicronBreakdown(TypedDict): + """Omicron adoption across player profiles, as returned by :func:`get_omicron_breakdown`.""" + + total_members: int + """Number of player profiles the statistics cover.""" + modes: list[OmicronModeBreakdown] + """Numbered modes in ascending order, then any mode kept as a name.""" + + +def _omicron_mode(value: Any) -> int | str: + """A skill's ``omicronMode`` as its number; a name missing from ``_OMICRON_MODES`` is kept as given.""" + raw = as_scalar(value) + if raw is None: + return 0 # proto3 leaves out a zero enum, so a missing mode is OmicronMode_DEFAULT. + if isinstance(raw, int): + return raw + name = parse_enum(raw, _OMICRON_MODES, enum_name="OmicronMode") + return _OMICRON_MODES[name] if name is not None else raw + + +def _omicron_tier_index(skill: dict[str, Any]) -> int | None: + """The index of a game data skill's omicron tier, or ``None`` when it has none.""" + return next( + ( + index + for index, tier in enumerate(as_list(skill.get("tier"))) + if isinstance(tier, dict) and tier.get("isOmicronTier") is True + ), + None, + ) + + +def _owning_units(units: list[dict[str, Any]]) -> dict[str, tuple[str | None, str | None]]: + """Map each skill id to the ``(baseId, nameKey)`` of the unit a player must own to have it. + + A skill is commonly referenced by several base ids: the playable unit, a non-obtainable ``PVE_`` + mirror the AI uses, and sometimes a raid or event variant. Only the playable unit can be in a + roster, so resolving a skill to any other reports every player as not owning it. Playable units + (:func:`get_playable_units`) are therefore read first; the rest only name skills no playable unit + references. The first unit read wins, and the per-rarity rows of one unit agree. + """ + owners: dict[str, tuple[str | None, str | None]] = {} + for unit in (*get_playable_units(units), *units): + identity = (as_str(unit.get("baseId")) or None, as_str(unit.get("nameKey")) or None) + for reference in as_list(unit.get("skillReference")): + skill_id = reference.get("skillId") if isinstance(reference, dict) else None + if isinstance(skill_id, str): + owners.setdefault(skill_id, identity) + return owners + + +def _read_profile(profile: dict[str, Any]) -> tuple[set[str], dict[str, int]]: + """A player profile's owned base ids and the tier of each skill in its roster.""" + owned: set[str] = set() + tiers: dict[str, int] = {} + for unit in as_list(profile.get("rosterUnit")): + if not isinstance(unit, dict): + continue + if unit_id := base_id(unit.get("definitionId")): + owned.add(unit_id) + for skill in as_list(unit.get("skill")): + if isinstance(skill, dict) and isinstance(skill_id := skill.get("id"), str): + # A listed skill is unlocked; proto3 leaves out tier 0. + tiers[skill_id] = as_int(skill.get("tier")) + return owned, tiers + + +def get_omicron_breakdown( + player_profiles: list[dict[str, Any]], + skill_list: list[dict[str, Any]], + unit_list: list[dict[str, Any]], + *, + ability_list: list[dict[str, Any]] | None = None, + localization: dict[str, str] | None = None, + mode_names: Mapping[int, str] | None = None, +) -> OmicronBreakdown: + """Summarise omicron adoption across a set of player profiles, grouped by game mode. + + Every omicron skill in the game data becomes a row, whether or not anybody owns it, so the result + also answers "which omicrons exist, by mode". Each row splits the players into those who have + applied the omicron, those who own the unit but have not, and a count of those who do not own the + unit. + + A skill is an omicron when one of its tiers is flagged ``isOmicronTier``. Its ``omicronMode`` only + says where the omicron applies: skills without one carry mode 1 (``ALL_OMICRON``) by default. + + A player owns a unit when it is in their roster; whether the skill is listed there does not + decide it, because a star-gated skill is left out until unlocked. Only when no unit in + ``unit_list`` references a skill does a listed skill stand in for ownership. + + Args: + player_profiles: Full player profiles, as returned by ``get_player()``. Guild member entries do + not work: they carry no roster. + skill_list: The game data ``skill`` collection. + unit_list: The game data ``units`` collection, which names the unit owning each skill and so + decides ownership. ``include_pve_units=False`` is enough. + ability_list: Optional game data ``ability`` collection. It names each omicron, which matters + because a unit often has several omicrons in one mode (Doctor Aphra has three in 5v5 Grand + Arena) and the unit name alone does not tell them apart. + localization: Optional localization dictionary, e.g. from :func:`get_localization_dictionary`, + used for the unit and omicron names. + mode_names: Optional labels for the mode numbers. [Default: ``OMICRON_MODE``, which does not + name every mode; an unnamed mode is labelled ``"Mode "``] + + Returns: + An :class:`OmicronBreakdown`. Players within a row are ordered by name, then by player id. + + Raises: + SwgohComlinkValueError: If an argument has the wrong type, a profile has no ``playerId``, or two + profiles share one. + + Examples: + >>> game_data = comlink.get_game_data( + ... items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, include_pve_units=False + ... ) # doctest: +SKIP + >>> profiles = [comlink.get_player(player_id=m["playerId"]) for m in guild["member"]] # doctest: +SKIP + >>> breakdown = get_omicron_breakdown( + ... profiles, game_data["skill"], game_data["units"], ability_list=game_data["ability"] + ... ) # doctest: +SKIP + """ + for arg_name, arg in (("player_profiles", player_profiles), ("skill_list", skill_list), ("unit_list", unit_list)): + if not isinstance(arg, list): + raise SwgohComlinkValueError(f"{get_function_name()}: '{arg_name}' must be a list, not {type(arg)}") + if ability_list is not None and not isinstance(ability_list, list): + raise SwgohComlinkValueError(f"{get_function_name()}: 'ability_list' must be a list, not {type(ability_list)}") + if localization is not None and not isinstance(localization, dict): + raise SwgohComlinkValueError( + f"{get_function_name()}: 'localization' must be a dictionary, not {type(localization)}" + ) + if mode_names is not None and not isinstance(mode_names, Mapping): + raise SwgohComlinkValueError(f"{get_function_name()}: 'mode_names' must be a mapping, not {type(mode_names)}") + + members: list[tuple[str, str, set[str], dict[str, int]]] = [] + seen: set[str] = set() + for profile in player_profiles: + if not isinstance(profile, dict): + raise SwgohComlinkValueError( + f"{get_function_name()}: every player profile must be a dictionary, not {type(profile)}" + ) + player_id = as_str(profile.get("playerId")) + if not player_id: + raise SwgohComlinkValueError(f"{get_function_name()}: every player profile must carry a 'playerId'.") + if player_id in seen: + raise SwgohComlinkValueError( + f"{get_function_name()}: duplicate 'playerId' {player_id!r} in 'player_profiles'." + ) + seen.add(player_id) + members.append((player_id, as_str(profile.get("name")), *_read_profile(profile))) + members.sort(key=lambda member: (member[1], member[0])) + + labels = OMICRON_MODE if mode_names is None else mode_names + owners = _owning_units([unit for unit in unit_list if isinstance(unit, dict)]) + ability_names = { + ability["id"]: ability["nameKey"] + for ability in ability_list or [] + if isinstance(ability, dict) and isinstance(ability.get("id"), str) and isinstance(ability.get("nameKey"), str) + } + + by_mode: dict[int | str, list[OmicronSkillStats]] = {} + for skill in skill_list: + if not isinstance(skill, dict) or not isinstance(skill_id := skill.get("id"), str): + continue + if (omicron_tier := _omicron_tier_index(skill)) is None: + continue + unit_id, unit_name_key = owners.get(skill_id, (None, None)) + skill_name_key = ability_names.get(as_str(skill.get("abilityReference"))) + + applied: list[OmicronMember] = [] + owned_not_applied: list[OmicronMember] = [] + for player_id, player_name, owned, tiers in members: + if not (unit_id in owned if unit_id is not None else skill_id in tiers): + continue + tier = tiers.get(skill_id) + member: OmicronMember = {"player_id": player_id, "player_name": player_name, "tier": tier} + (applied if tier is not None and tier >= omicron_tier else owned_not_applied).append(member) + + by_mode.setdefault(_omicron_mode(skill.get("omicronMode")), []).append( + { + "skill_id": skill_id, + "skill_name_key": skill_name_key, + "skill_name": _localize(localization, skill_name_key, "") or None, + "unit_base_id": unit_id, + "unit_name_key": unit_name_key, + "unit_name": _localize(localization, unit_name_key, "") or None, + "omicron_tier": omicron_tier, + "applied": applied, + "owned_not_applied": owned_not_applied, + "not_owned_count": len(members) - len(applied) - len(owned_not_applied), + } + ) + + def mode_order(mode: int | str) -> tuple[bool, int, str]: + return (True, 0, mode) if isinstance(mode, str) else (False, mode, "") + + return { + "total_members": len(members), + "modes": [ + { + "mode": mode, + "mode_name": (labels.get(mode) if isinstance(mode, int) else None) or f"Mode {mode}", + "skills": sorted(stats, key=lambda s: (-len(s["applied"]), s["skill_id"])), + } + for mode, stats in sorted(by_mode.items(), key=lambda item: mode_order(item[0])) + ], + } diff --git a/tests/unit/test_helpers.py b/tests/unit/test_helpers.py index 53533fa..552e899 100644 --- a/tests/unit/test_helpers.py +++ b/tests/unit/test_helpers.py @@ -92,6 +92,7 @@ parse_swgoh_string, ) from swgoh_comlink.helpers._omicron import ( + get_omicron_breakdown, get_omicron_skill_tier, get_omicron_skills, get_tw_omicrons, @@ -398,6 +399,271 @@ def test_invalid_skill_type_raises(self): get_unit_from_skill([], cast(Any, 123)) +# ── _omicron.get_omicron_breakdown ───────────────────────────────────── + + +def _omi_skill(skill_id: str, mode: Any, *, omicron: int | None, tiers: int = 7, ability: str | None = None): + """A game data 'skill' with *tiers* upgrade tiers; *omicron* is the omicron's tier index.""" + skill: dict[str, Any] = { + "id": skill_id, + "omicronMode": mode, + "tier": [{"isZetaTier": False, "isOmicronTier": i == omicron} for i in range(tiers)], + } + if ability is not None: + skill["abilityReference"] = ability + return skill + + +# Modelled on live JEDIKNIGHTCAL game data. uniqueskill_JEDIKNIGHTCAL01 is a zeta that carries mode 1, the +# value every skill without an omicron has, so it is not an omicron. +_BREAKDOWN_SKILLS = [ + _omi_skill("specialskill_JEDIKNIGHTCAL03", 7, omicron=6, ability="specialability_jediknightcal03"), + _omi_skill("uniqueskill_JEDIKNIGHTCAL01", 1, omicron=None), + # Star-gated: missing from a roster until the unit reaches the rarity that unlocks it. + _omi_skill("uniqueskill_JEDIKNIGHTCAL02", 8, omicron=3, tiers=4), + # A mode OMICRON_MODE has no label for (13 is PVE_EVENT_OMICRON). + _omi_skill("specialskill_OTHERUNIT01", 13, omicron=1, tiers=2), +] +_JKCAL = {"baseId": "JEDIKNIGHTCAL", "nameKey": "UNIT_JEDIKNIGHTCAL_NAME", "obtainable": True, "obtainableTime": "0"} +_JKCAL_SKILLS = [{"skillId": s} for s in ("specialskill_JEDIKNIGHTCAL03", "uniqueskill_JEDIKNIGHTCAL01")] +# The 'units' collection has a row per unit per rarity, so a baseId recurs. +_BREAKDOWN_UNITS: list[dict[str, Any]] = [ + {**_JKCAL, "rarity": 7, "skillReference": [*_JKCAL_SKILLS, {"skillId": "uniqueskill_JEDIKNIGHTCAL02"}]}, + {**_JKCAL, "rarity": 1, "skillReference": _JKCAL_SKILLS}, + { + "baseId": "OTHERUNIT", + "nameKey": "UNIT_OTHERUNIT_NAME", + "skillReference": [{"skillId": "specialskill_OTHERUNIT01"}], + }, +] +_BREAKDOWN_ABILITIES = [ + {"id": "specialability_jediknightcal03", "nameKey": "SPECIALABILITY_JEDIKNIGHTCAL03_NAME"}, + {"id": "unrelated_ability", "nameKey": "UNRELATED_NAME"}, +] + + +def _cal_owner(player_id: str, name: str, *skills: dict[str, Any]) -> dict[str, Any]: + """A player profile owning JEDIKNIGHTCAL with the given roster skills.""" + return { + "playerId": player_id, + "name": name, + "rosterUnit": [{"definitionId": "JEDIKNIGHTCAL:SEVEN_STAR", "skill": list(skills)}], + } + + +_APPLIED = _cal_owner("p1", "Applied", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 6}) +_ONE_SHORT = _cal_owner("p2", "OneShort", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 5}) +# Owns JEDIKNIGHTCAL, but uniqueskill_JEDIKNIGHTCAL02 is not in the roster at all. +_GATED = _cal_owner("p3", "Gated", {"id": "specialskill_JEDIKNIGHTCAL03", "tier": 6}) +_NO_UNIT = {"playerId": "p4", "name": "NoUnit", "rosterUnit": []} + + +def _omi_row(breakdown: Any, skill_id: str) -> Any: + return next(row for mode in breakdown["modes"] for row in mode["skills"] if row["skill_id"] == skill_id) + + +def _with_modes(**modes: Any) -> list[dict[str, Any]]: + """_BREAKDOWN_SKILLS with the omicronMode of the named skills replaced; None removes the field.""" + skills = [dict(skill) for skill in _BREAKDOWN_SKILLS] + for skill in skills: + if skill["id"] in modes: + if (mode := modes[skill["id"]]) is None: + del skill["omicronMode"] + else: + skill["omicronMode"] = mode + return skills + + +def test_omicron_breakdown_lists_every_omicron_and_only_omicrons(): + breakdown = get_omicron_breakdown([], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS) + assert breakdown["total_members"] == 0 + assert {row["skill_id"] for mode in breakdown["modes"] for row in mode["skills"]} == { + "specialskill_JEDIKNIGHTCAL03", + "uniqueskill_JEDIKNIGHTCAL02", + "specialskill_OTHERUNIT01", + } + + +@pytest.mark.parametrize( + ("profiles", "units", "skill_id", "applied", "owned_not_applied", "not_owned"), + [ + pytest.param([_APPLIED], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", ["p1"], [], 0, id="at-omicron-tier"), + pytest.param( + [_ONE_SHORT], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [("p2", 5)], 0, id="one-tier-short" + ), + # Owning the unit decides ownership, not whether the skill is listed. + pytest.param([_GATED], _BREAKDOWN_UNITS, "uniqueskill_JEDIKNIGHTCAL02", [], [("p3", None)], 0, id="star-gated"), + pytest.param([_NO_UNIT], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [], 1, id="unit-not-owned"), + pytest.param( + [{"playerId": "p9", "name": "Fresh"}], _BREAKDOWN_UNITS, "specialskill_JEDIKNIGHTCAL03", [], [], 1, + id="no-roster", + ), + # A listed skill is unlocked, and proto3 leaves out a tier of 0. + pytest.param( + [_cal_owner("p5", "Fresh", {"id": "specialskill_JEDIKNIGHTCAL03"})], _BREAKDOWN_UNITS, + "specialskill_JEDIKNIGHTCAL03", [], [("p5", 0)], 0, id="tier-left-out", + ), + # No unit references the skill, so a listed skill stands in for owning the unit. + pytest.param([_APPLIED, _NO_UNIT], [], "specialskill_JEDIKNIGHTCAL03", ["p1"], [], 1, id="unknown-unit"), + ], +) # fmt: skip +def test_omicron_breakdown_cohorts(profiles, units, skill_id, applied, owned_not_applied, not_owned): + row = _omi_row(get_omicron_breakdown(profiles, _BREAKDOWN_SKILLS, units), skill_id) + assert [m["player_id"] for m in row["applied"]] == applied + assert [(m["player_id"], m["tier"]) for m in row["owned_not_applied"]] == owned_not_applied + assert row["not_owned_count"] == not_owned + + +def test_omicron_breakdown_cohorts_sum_to_total_members(): + breakdown = get_omicron_breakdown([_APPLIED, _ONE_SHORT, _GATED, _NO_UNIT], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS) + assert breakdown["total_members"] == 4 + for mode in breakdown["modes"]: + for row in mode["skills"]: + assert len(row["applied"]) + len(row["owned_not_applied"]) + row["not_owned_count"] == 4, row["skill_id"] + + +_JKCAL03, _JKCAL02, _OTHER01 = "specialskill_JEDIKNIGHTCAL03", "uniqueskill_JEDIKNIGHTCAL02", "specialskill_OTHERUNIT01" + + +@pytest.mark.parametrize( + ("skills", "kwargs", "expected"), + [ + pytest.param(_BREAKDOWN_SKILLS, {}, [(7, "TB"), (8, "TW"), (13, "Mode 13")], id="numbers"), + # enums=True sends the member name. + pytest.param( + _with_modes( + **{ + _JKCAL03: "TERRITORY_BATTLE_BOTH_OMICRON", + _JKCAL02: "TERRITORY_WAR_OMICRON", + _OTHER01: "PVE_EVENT_OMICRON", + } + ), + {}, + [(7, "TB"), (8, "TW"), (13, "Mode 13")], + id="enum-names", + ), + pytest.param( + _with_modes(**{_JKCAL02: "OMICRONMODE_TERRITORYWAROMICRON", _OTHER01: "13"}), + {}, + [(7, "TB"), (8, "TW"), (13, "Mode 13")], + id="type-prefixed-and-numeric-string", + ), + # A mode added by a newer game version keeps its name and sorts after the numbered modes. + pytest.param( + _with_modes(**{_JKCAL03: "NEW_EVENT_OMICRON"}), + {}, + [(8, "TW"), (13, "Mode 13"), ("NEW_EVENT_OMICRON", "Mode NEW_EVENT_OMICRON")], + id="unknown-name", + ), + # proto3 leaves out the zero enum value. + pytest.param(_with_modes(**{_OTHER01: None}), {}, [(0, "Default"), (7, "TB"), (8, "TW")], id="mode-left-out"), + pytest.param( + _BREAKDOWN_SKILLS, + {"mode_names": {13: "PVE Event"}}, + [(7, "Mode 7"), (8, "Mode 8"), (13, "PVE Event")], + id="custom-labels", + ), + ], +) +def test_omicron_breakdown_modes(skills, kwargs, expected): + breakdown = get_omicron_breakdown([_APPLIED], skills, _BREAKDOWN_UNITS, **kwargs) + assert [(mode["mode"], mode["mode_name"]) for mode in breakdown["modes"]] == expected + + +def test_omicron_breakdown_orders_skills_by_applied_count_then_members_by_name(): + # Both omicrons in one mode: the one more players applied comes first, ahead of skill id order. + skills = _with_modes(**{_JKCAL03: 8}) + alice = _cal_owner("pz", "Alice", {"id": _JKCAL02, "tier": 3}) + bob = _cal_owner("pa", "Bob", {"id": _JKCAL02, "tier": 3}) + breakdown = get_omicron_breakdown([bob, _APPLIED, alice], skills, _BREAKDOWN_UNITS) + rows = next(mode for mode in breakdown["modes"] if mode["mode"] == 8)["skills"] + assert [row["skill_id"] for row in rows] == [_JKCAL02, _JKCAL03] + assert [m["player_name"] for m in rows[0]["applied"]] == ["Alice", "Bob"] + + +# A skill referenced by several base ids, as in live game data: a non-obtainable PVE_ mirror listed first, an +# event variant whose obtainableTime is in the future, and the playable unit. +_PVE_MIRROR = {"baseId": "PVE_JEDIKNIGHTCAL", "nameKey": "PVE_NAME", "rarity": 8, "obtainable": False} +_EVENT_VARIANT = {"baseId": "JEDIKNIGHTCAL_EVENT", "rarity": 7, "obtainable": True, "obtainableTime": "2396822400000"} + + +@pytest.mark.parametrize( + ("units", "base_id", "not_owned"), + [ + pytest.param([_PVE_MIRROR, _EVENT_VARIANT, {**_JKCAL, "rarity": 7}], "JEDIKNIGHTCAL", 0, id="playable-wins"), + pytest.param( + [_PVE_MIRROR, {**_JKCAL, "rarity": "SEVEN_STAR"}], "JEDIKNIGHTCAL", 0, id="playable-wins-enum-rarity" + ), + # With no playable unit, the first unit read wins and the owner of JEDIKNIGHTCAL is not counted. + pytest.param([_PVE_MIRROR, _EVENT_VARIANT], "PVE_JEDIKNIGHTCAL", 1, id="none-playable"), + ], +) +def test_omicron_breakdown_resolves_the_playable_unit(units, base_id, not_owned): + units = [{**unit, "skillReference": [{"skillId": _JKCAL03}]} for unit in units] + row = _omi_row(get_omicron_breakdown([_APPLIED], _BREAKDOWN_SKILLS, units), _JKCAL03) + assert row["unit_base_id"] == base_id + assert row["not_owned_count"] == not_owned + + +_CAL_NAMES = { + "UNIT_JEDIKNIGHTCAL_NAME": "[c][ffff33]Cal Kestis[-][/c]", + "SPECIALABILITY_JEDIKNIGHTCAL03_NAME": "Impetuous Assault", +} + + +@pytest.mark.parametrize( + ("skill_id", "kwargs", "expected"), + [ + pytest.param(_JKCAL03, {}, (None, None, "UNIT_JEDIKNIGHTCAL_NAME", None), id="keys-only"), + # The omicron's name comes from the ability, never from the skill's placeholder nameKey. + pytest.param( + _JKCAL03, + {"ability_list": _BREAKDOWN_ABILITIES}, + ("SPECIALABILITY_JEDIKNIGHTCAL03_NAME", None, "UNIT_JEDIKNIGHTCAL_NAME", None), + id="ability-key", + ), + pytest.param( + _JKCAL03, + {"ability_list": _BREAKDOWN_ABILITIES, "localization": _CAL_NAMES}, + ("SPECIALABILITY_JEDIKNIGHTCAL03_NAME", "Impetuous Assault", "UNIT_JEDIKNIGHTCAL_NAME", "Cal Kestis"), + id="localized", + ), + pytest.param( + _JKCAL02, + {"ability_list": _BREAKDOWN_ABILITIES, "localization": _CAL_NAMES}, + (None, None, "UNIT_JEDIKNIGHTCAL_NAME", "Cal Kestis"), + id="no-ability-reference", + ), + ], +) +def test_omicron_breakdown_names(skill_id, kwargs, expected): + row = _omi_row(get_omicron_breakdown([_APPLIED], _BREAKDOWN_SKILLS, _BREAKDOWN_UNITS, **kwargs), skill_id) + assert (row["skill_name_key"], row["skill_name"], row["unit_name_key"], row["unit_name"]) == expected + + +@pytest.mark.parametrize( + ("call", "match"), + [ + pytest.param(lambda: get_omicron_breakdown(cast(Any, "bad"), [], []), "player_profiles", id="profiles"), + pytest.param(lambda: get_omicron_breakdown([], cast(Any, "bad"), []), "skill_list", id="skills"), + pytest.param(lambda: get_omicron_breakdown([], [], cast(Any, "bad")), "unit_list", id="units"), + pytest.param( + lambda: get_omicron_breakdown([], [], [], ability_list=cast(Any, "bad")), "ability_list", id="abilities" + ), + pytest.param( + lambda: get_omicron_breakdown([], [], [], localization=cast(Any, "bad")), "localization", id="localization" + ), + pytest.param(lambda: get_omicron_breakdown([], [], [], mode_names=cast(Any, 8)), "mode_names", id="mode-names"), + pytest.param(lambda: get_omicron_breakdown(cast(Any, ["nope"]), [], []), "dictionary", id="profile-not-dict"), + pytest.param(lambda: get_omicron_breakdown([{"name": "Anon"}], [], []), "playerId", id="no-player-id"), + pytest.param(lambda: get_omicron_breakdown([_APPLIED, _APPLIED], [], []), "duplicate", id="duplicate-player"), + ], +) +def test_omicron_breakdown_rejects_invalid_input(call, match): + with pytest.raises(SwgohComlinkValueError, match=match): + call() + + # ── _game_data ────────────────────────────────────────────────────────── From 0c3bf6ad5dae0b1f58914d136fade3f74627b966 Mon Sep 17 00:00:00 2001 From: MarTrepodi Date: Mon, 9 Nov 2026 14:03:14 -0500 Subject: [PATCH 3/3] docs(examples): add guild omicron breakdown examples Add a Sync and an Async guild_omicron_breakdown.py that report omicron adoption across a guild by game mode. Both list the members with get_guild_members(), fetch every member's profile (concurrently with asyncio.TaskGroup in the Async one), request only the skill, units and ability collections by combining DataItems bits with |, and print the top omicrons per mode followed by the members who own the unit behind the biggest unapplied omicron. List both in the examples READMEs, docs/examples.md and the README. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + docs/examples.md | 2 + examples/Async/README.md | 1 + examples/Async/guild_omicron_breakdown.py | 110 ++++++++++++++++++++++ examples/Sync/README.md | 1 + examples/Sync/guild_omicron_breakdown.py | 100 ++++++++++++++++++++ 6 files changed, 216 insertions(+) create mode 100644 examples/Async/guild_omicron_breakdown.py create mode 100644 examples/Sync/guild_omicron_breakdown.py diff --git a/README.md b/README.md index 651164e..d782d9b 100644 --- a/README.md +++ b/README.md @@ -292,6 +292,7 @@ The [`examples/`](https://github.com/swgoh-utils/comlink-python/tree/main/exampl | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_brackets.py) | Scan GAC brackets and search for a player | | [`calc_stats_local.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/calc_stats_local.py) | Calculate character stats locally with `StatCalc` | | [`search_for_guilds.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/search_for_guilds.py) | Search for guilds by name or criteria | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode | ### Asynchronous ([`examples/Async/`](https://github.com/swgoh-utils/comlink-python/tree/main/examples/Async)) @@ -301,6 +302,7 @@ The [`examples/`](https://github.com/swgoh-utils/comlink-python/tree/main/exampl | [`concurrent_requests.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/concurrent_requests.py) | Fetch multiple players in parallel with `asyncio.gather()` | | [`streaming_guild_roster.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/streaming_guild_roster.py) | Fetch all guild members concurrently with `asyncio.TaskGroup` | | [`streaming_guild_roster_advanced.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/streaming_guild_roster_advanced.py) | Production-quality guild roster fetch with CLI args and retry logic | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/guild_omicron_breakdown.py) | Report omicron adoption across a guild, fetching member profiles concurrently | | [`calc_stats_local.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/calc_stats_local.py) | Calculate character stats locally with `StatCalcAsync` | See the [full examples listing](https://github.com/swgoh-utils/comlink-python/blob/main/examples/README.md) for all available scripts and usage details. diff --git a/docs/examples.md b/docs/examples.md index 3f0c06e..54222b2 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -16,6 +16,7 @@ These examples use `SwgohComlink` — the synchronous client. Simple blocking ca | [`get_gac_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_leaderboard.py) | Get GAC bracket or league/division leaderboards | | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_gac_brackets.py) | Scan GAC brackets for a league and search for a player | | [`get_guild_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_guild_leaderboard.py) | Get guild-level leaderboards (TW, raids, GP, TB) | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode | | [`get_language_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_language_bundle.py) | Retrieve and parse a specific language bundle | | [`get_location_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_location_bundle.py) | Retrieve the full localization bundle (zipped or unzipped) | | [`get_location_bundle_adv.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Sync/get_location_bundle_adv.py) | Advanced localization bundle retrieval | @@ -46,6 +47,7 @@ These examples use `SwgohComlinkAsync` — the asynchronous client. Supports con | [`get_gac_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_gac_leaderboard.py) | Get GAC bracket or league/division leaderboards | | [`get_gac_brackets.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_gac_brackets.py) | Scan GAC brackets for a league and search for a player (parallel batches) | | [`get_guild_leaderboard.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_guild_leaderboard.py) | Get guild-level leaderboards (TW, raids, GP, TB) | +| [`guild_omicron_breakdown.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/guild_omicron_breakdown.py) | Report omicron adoption across a guild by game mode, fetching member profiles concurrently | | [`get_language_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_language_bundle.py) | Retrieve and parse a specific language bundle | | [`get_location_bundle.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_location_bundle.py) | Retrieve the full localization bundle (zipped or unzipped) | | [`get_latest_game_data_version.py`](https://github.com/swgoh-utils/comlink-python/blob/main/examples/Async/get_latest_game_data_version.py) | Get current game data and language version strings | diff --git a/examples/Async/README.md b/examples/Async/README.md index 7a07a92..3cbcd23 100644 --- a/examples/Async/README.md +++ b/examples/Async/README.md @@ -13,6 +13,7 @@ These examples use the `SwgohComlinkAsync` async client. All methods must be `aw | `get_game_data.py` | Retrieve game data collections (all, by segment, or by name) | | `get_guild.py` | Look up guild info from a player's ally code | | `get_guild_leaderboard.py` | Get guild-level leaderboards (TW, raids, GP, TB) | +| `guild_omicron_breakdown.py` | Report omicron adoption across a guild by game mode, fetching member profiles concurrently | | `get_language_bundle.py` | Retrieve and parse a specific language bundle | | `get_latest_game_data_version.py` | Get current game data and language version strings | | `get_location_bundle.py` | Retrieve the full localization bundle (zipped or unzipped) | diff --git a/examples/Async/guild_omicron_breakdown.py b/examples/Async/guild_omicron_breakdown.py new file mode 100644 index 0000000..3806024 --- /dev/null +++ b/examples/Async/guild_omicron_breakdown.py @@ -0,0 +1,110 @@ +""" +guild_omicron_breakdown.py +Report omicron adoption across an entire guild, separated by game mode. + +This example demonstrates how to: + 1. List a guild's members from one player's ally code with async_get_guild_members() + 2. Fetch every member's full profile concurrently using asyncio.TaskGroup + 3. Pull only the 'skill', 'units' and 'ability' game data collections, by combining + individual DataItems bits with | rather than requesting whole segments + 4. Resolve unit and omicron names through a localization dictionary + 5. Summarise adoption with helpers.get_omicron_breakdown() + +Why the profiles have to be fetched: a guild's 'member' list holds identity stubs (player ID, +name, galactic power) and carries no roster. Whether a member has an omicron applied lives in +player['rosterUnit'][n]['skill'], so every member needs a full get_player() call. That fan-out +is the bulk of this program; the breakdown itself is one call. +""" + +import asyncio +import time + +from swgoh_comlink import SwgohComlinkAsync +from swgoh_comlink.helpers import ( + DataItems, + async_get_guild_members, + async_get_localization_dictionary, + get_omicron_breakdown, +) + +# CONFIGURATION +# Change these to any valid values to look up that player's guild +ALLY_CODE = 314927874 +COMLINK_HOST = "localhost" +COMLINK_PORT = 3000 +LANGUAGE = "eng_us" + +# How many omicrons to list per game mode +TOP_N = 5 + + +async def main(): + async with SwgohComlinkAsync(host=COMLINK_HOST, port=COMLINK_PORT) as comlink: + # Step 1: The guild's member list, from any one member's ally code. + members = await async_get_guild_members(comlink, allycode=ALLY_CODE) + print(f"Members: {len(members)}") + + # Step 2: Every member profile, concurrently. + start = time.perf_counter() + async with asyncio.TaskGroup() as tg: + tasks = [tg.create_task(comlink.get_player(player_id=member["playerId"])) for member in members] + profiles = [task.result() for task in tasks] + print(f"Fetched {len(profiles)} profiles in {time.perf_counter() - start:.2f}s") + + # Step 3: Game data. Request exactly the three collections needed by combining the + # individual DataItems bits; whole segments pull far more than this needs. 'ability' + # supplies the omicron names: a unit often has several omicrons in one game mode, so + # the unit name alone does not identify them. PvE units are left out, since only + # playable units can be in a roster. + game_data = await comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, + include_pve_units=False, + ) + print( + f"Game data: {len(game_data['skill'])} skills, {len(game_data['units'])} unit rows, " + f"{len(game_data['ability'])} abilities" + ) + + # Step 4: Localization, so units and omicrons read as names rather than IDs. + localization = await async_get_localization_dictionary(comlink, language=LANGUAGE) + + # Step 5: The breakdown itself. It needs no client, so it runs after the session closes. + breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=localization, + ) + + # Step 6: Report. Counts first, then the detail behind one of them. + total = breakdown["total_members"] + for mode in breakdown["modes"]: + print(f"\n=== {mode['mode_name']} (mode {mode['mode']}): {len(mode['skills'])} omicrons ===") + for row in mode["skills"][:TOP_N]: + applied = len(row["applied"]) + owners = applied + len(row["owned_not_applied"]) + label = f"{row['unit_name'] or row['unit_base_id'] or '?'}: {row['skill_name'] or row['skill_id']}" + print(f" {label:<60} {applied:>3}/{total} guild | {applied:>3}/{owners} owners") + + # The member lists are the point of the helper, so show one in full: the omicron with the + # most owners who have not applied it, the guild's largest single opportunity. + rows = [(mode["mode_name"], row) for mode in breakdown["modes"] for row in mode["skills"]] + if not rows: + return + mode_name, target = max(rows, key=lambda pair: len(pair[1]["owned_not_applied"])) + if not target["owned_not_applied"]: + return + + unit = target["unit_name"] or target["unit_base_id"] or "?" + print(f"\n=== Biggest opportunity: {unit}: {target['skill_name'] or target['skill_id']} ({mode_name}) ===") + print(f" applied by {len(target['applied'])}, missing on {len(target['owned_not_applied'])} rosters") + print(f" {target['not_owned_count']} members do not own the unit\n") + for member in target["owned_not_applied"]: + # tier is None when the skill is not in the roster at all: star-gated and not yet + # unlocked, rather than merely not upgraded. + position = "not unlocked" if member["tier"] is None else f"tier {member['tier']}/{target['omicron_tier']}" + print(f" {member['player_name']:<24} {position}") + + +asyncio.run(main()) diff --git a/examples/Sync/README.md b/examples/Sync/README.md index a5060ed..81abf1a 100644 --- a/examples/Sync/README.md +++ b/examples/Sync/README.md @@ -13,6 +13,7 @@ These examples use the `SwgohComlink` synchronous client. They run in a standard | `get_game_data.py` | Retrieve game data collections (all, by segment, or by name) | | `get_guild.py` | Look up guild info from a player's ally code | | `get_guild_leaderboard.py` | Get guild-level leaderboards (TW, raids, GP, TB) | +| `guild_omicron_breakdown.py` | Report omicron adoption across a guild by game mode | | `get_language_bundle.py` | Retrieve and parse a specific language bundle | | `get_latest_game_data_version.py` | Get current game data and language version strings | | `get_location_bundle.py` | Retrieve the full localization bundle (zipped or unzipped) | diff --git a/examples/Sync/guild_omicron_breakdown.py b/examples/Sync/guild_omicron_breakdown.py new file mode 100644 index 0000000..d033c1a --- /dev/null +++ b/examples/Sync/guild_omicron_breakdown.py @@ -0,0 +1,100 @@ +""" +guild_omicron_breakdown.py +Report omicron adoption across an entire guild, separated by game mode. + +This example demonstrates how to: + 1. List a guild's members from one player's ally code with get_guild_members() + 2. Fetch every member's full profile + 3. Pull only the 'skill', 'units' and 'ability' game data collections, by combining + individual DataItems bits with | rather than requesting whole segments + 4. Resolve unit and omicron names through a localization dictionary + 5. Summarise adoption with helpers.get_omicron_breakdown() + +Why the profiles have to be fetched: a guild's 'member' list holds identity stubs (player ID, +name, galactic power) and carries no roster. Whether a member has an omicron applied lives in +player['rosterUnit'][n]['skill'], so every member needs a full get_player() call. Here they are +fetched one after another; see examples/Async/guild_omicron_breakdown.py to fetch them +concurrently. +""" + +import time + +from swgoh_comlink import SwgohComlink +from swgoh_comlink.helpers import ( + DataItems, + get_guild_members, + get_localization_dictionary, + get_omicron_breakdown, +) + +# CONFIGURATION +# Change these to any valid values to look up that player's guild +ALLY_CODE = 314927874 +COMLINK_HOST = "localhost" +COMLINK_PORT = 3000 +LANGUAGE = "eng_us" + +# How many omicrons to list per game mode +TOP_N = 5 + +comlink = SwgohComlink(host=COMLINK_HOST, port=COMLINK_PORT) + +# Step 1: The guild's member list, from any one member's ally code. +members = get_guild_members(comlink, allycode=ALLY_CODE) +print(f"Members: {len(members)}") + +# Step 2: Every member profile. +start = time.perf_counter() +profiles = [comlink.get_player(player_id=member["playerId"]) for member in members] +print(f"Fetched {len(profiles)} profiles in {time.perf_counter() - start:.2f}s") + +# Step 3: Game data. Request exactly the three collections needed by combining the individual +# DataItems bits; whole segments pull far more than this needs. 'ability' supplies the omicron +# names: a unit often has several omicrons in one game mode, so the unit name alone does not +# identify them. PvE units are left out, since only playable units can be in a roster. +game_data = comlink.get_game_data( + items=DataItems.SKILL | DataItems.UNITS | DataItems.ABILITY, + include_pve_units=False, +) +print( + f"Game data: {len(game_data['skill'])} skills, {len(game_data['units'])} unit rows, " + f"{len(game_data['ability'])} abilities" +) + +# Step 4: Localization, so units and omicrons read as names rather than IDs. +localization = get_localization_dictionary(comlink, language=LANGUAGE) + +# Step 5: The breakdown itself. +breakdown = get_omicron_breakdown( + profiles, + game_data["skill"], + game_data["units"], + ability_list=game_data["ability"], + localization=localization, +) + +# Step 6: Report. Counts first, then the detail behind one of them. +total = breakdown["total_members"] +for mode in breakdown["modes"]: + print(f"\n=== {mode['mode_name']} (mode {mode['mode']}): {len(mode['skills'])} omicrons ===") + for row in mode["skills"][:TOP_N]: + applied = len(row["applied"]) + owners = applied + len(row["owned_not_applied"]) + label = f"{row['unit_name'] or row['unit_base_id'] or '?'}: {row['skill_name'] or row['skill_id']}" + print(f" {label:<60} {applied:>3}/{total} guild | {applied:>3}/{owners} owners") + +# The member lists are the point of the helper, so show one in full: the omicron with the most +# owners who have not applied it, the guild's largest single opportunity. +rows = [(mode["mode_name"], row) for mode in breakdown["modes"] for row in mode["skills"]] +if rows: + mode_name, target = max(rows, key=lambda pair: len(pair[1]["owned_not_applied"])) + if target["owned_not_applied"]: + unit = target["unit_name"] or target["unit_base_id"] or "?" + print(f"\n=== Biggest opportunity: {unit}: {target['skill_name'] or target['skill_id']} ({mode_name}) ===") + print(f" applied by {len(target['applied'])}, missing on {len(target['owned_not_applied'])} rosters") + print(f" {target['not_owned_count']} members do not own the unit\n") + for member in target["owned_not_applied"]: + # tier is None when the skill is not in the roster at all: star-gated and not yet + # unlocked, rather than merely not upgraded. + position = "not unlocked" if member["tier"] is None else f"tier {member['tier']}/{target['omicron_tier']}" + print(f" {member['player_name']:<24} {position}")