Files
myrzx_bot/ranch_assistant/policy_io.py
T

43 lines
2.0 KiB
Python

"""Portable rule sets; credentials, sessions and local paths never enter files."""
from dataclasses import asdict
from .model import Policy
FORMAT = "ranch-helper-policies"
VERSION = 1
def portable_policy(policy, snapshot=None):
value = asdict(policy)
value["enabled"] = False
for field in ("buy", "collect", "dispatch", "feed", "fill", "gift_enabled"):
value[field] = False
targets = {}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
targets[kind] = []
for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]):
mon = snapshot.monsters.get(int(key)) if snapshot else None
targets[kind].append({"typeId": str(mon.get("typeId")) if mon else "", "priority": priority})
return {"format": FORMAT, "schema": VERSION, "assistantVersion": "1.1.0", "gameVersion": "1.9.68",
"policy": value, "targetSpecies": targets}
def import_policy(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT or value.get("schema") != VERSION or not isinstance(value.get("policy"), dict):
raise ValueError("不是受支持的辅助策略文件")
policy = Policy(**value["policy"])
if snapshot:
used = {"feed": set(), "gift": set()}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
result = {}
for rule in value.get("targetSpecies", {}).get(kind, []):
key = str(rule.get("typeId", ""))
for mon in sorted(snapshot.raw["monsters"], key=lambda m: int(m["id"])):
if str(mon.get("typeId")) == key and mon.get("process") == 3 and int(mon["id"]) not in used[kind]:
result[str(mon["id"])] = int(rule["priority"])
used[kind].add(int(mon["id"]))
break
setattr(policy, field, result)
else:
policy.feed_targets, policy.gift_targets = {}, {}
return policy