"""Reference client for the MinecraftCombatAI streaming API. Python 3.9+, standard library only. from mca_client import Client, Frame with Client("mca_live_...", model="v32") as bot: # waits for the GPU if needed; # then streams to it directly while fighting: action = bot.step(Frame(...)) # one call per game tick # (CrystalFrame for "crystal") apply(action.yaw_delta, action.pitch_delta, action.keys) bot.new_fight() # opponent changed Wire format: one little-endian frame of raw game state per tick in (221 bytes for the sword models, Frame; 2592 for crystal, CrystalFrame), one 16-byte applied input out. Field meanings are on https://minecraftcombatai.com/docs.html. Apply the returned yaw/pitch deltas verbatim: sessions whose rotation does not follow the model are ended (the API drives a player; it does not label states you choose). """ from __future__ import annotations import base64 import hashlib import hmac import json import urllib.error import urllib.request import os import socket import ssl import struct import time from dataclasses import dataclass, field from urllib.parse import urlparse DEFAULT_API = "https://minecraftcombatai.com" FRAME_FMT = "<9d5f4i4B9d3fi5B2ifB3B" ACTION_FMT = " bytes: return struct.pack( FRAME_FMT, *self.pos, *self.prev_pos, *self.motion, self.yaw, self.pitch, self.health, self.fall_distance, self.saturation, self.hurt_time, self.jump_ticks, self.food_level, self.attack_strength_ticker, self.on_ground, self.sprinting, self.sneaking, self.collided_horizontally, *self.opp_pos, *self.opp_prev_pos, *self.opp_motion, self.opp_yaw, self.opp_pitch, self.opp_health, self.opp_hurt_time, self.opp_on_ground, self.opp_sprinting, self.opp_sneaking, self.opp_swinging, self.opp_crouch_pose, self.tick, self.ping_ms, self.sensitivity, self.last_attack, 0, 0, 0) @dataclass class Action: tick: int yaw_delta: float pitch_delta: float keys: int raw: bytes = field(repr=False, default=b"") @classmethod def unpack(cls, b: bytes) -> "Action": tick, yaw, pitch, keys, *_ = struct.unpack(ACTION_FMT, b) return cls(tick, yaw, pitch, keys, b) def down(self, bit: int) -> bool: return bool(self.keys & bit) # Crystal models only (zero for sword). @property def use(self) -> bool: """Right-click this tick (place / charge / detonate / throw / fire).""" return bool(self.raw and self.raw[13] & USE_CLICK) @property def use_held(self) -> bool: """Keep the use key held (eating, shield, crossbow charge).""" return bool(self.raw and self.raw[13] & USE_HELD) @property def slot(self): """Hotbar slot 0..8 to select, or None to leave the selection as it is.""" return None if not self.raw or self.raw[14] == 0xFF else self.raw[14] @property def inventory_op(self) -> int: """INV_NONE, INV_SWAP_OFFHAND (the F key), INV_SWAP_CHEST, INV_REFILL.""" return self.raw[15] if self.raw else 0 # ---------------------------------------------------------------- crystal ------------- # Crystal models take a different frame (2592 bytes) and fill the reply's spare bytes. # Block ids: what each world block becomes. Anything else solid is BLOCK_STONE; anything # else non-solid (flowers, slabs' air, water...) is BLOCK_AIR. BLOCK_AIR, BLOCK_BEDROCK, BLOCK_STONE, BLOCK_DIRT, BLOCK_OBSIDIAN = 0, 1, 2, 3, 4 BLOCK_ANCHOR_0, BLOCK_FIRE = 5, 10 # respawn anchor with charge c is 5 + c (0..4) # Item ids, the platform's 32-entry item table (see docs.html for the full mapping). (ITEM_EMPTY, ITEM_SWORD, ITEM_MACE, ITEM_OBSIDIAN, ITEM_END_CRYSTAL, ITEM_RESPAWN_ANCHOR, ITEM_GLOWSTONE, ITEM_TOTEM, ITEM_GOLDEN_APPLE, ITEM_FIREWORK, ITEM_ELYTRA, ITEM_CHESTPLATE, ITEM_ENDER_PEARL, ITEM_AXE, ITEM_SHIELD, ITEM_WIND_CHARGE, ITEM_CROSSBOW, ITEM_ARROW, ITEM_PICKAXE, ITEM_XP_BOTTLE, ITEM_SPLASH_POTION, ITEM_HELMET, ITEM_LEGGINGS, ITEM_BOOTS, ITEM_BUILDING_BLOCK, ITEM_CONTAINER, ITEM_GLOWSTONE_DUST, ITEM_SPEAR, ITEM_BOW, ITEM_COBWEB, ITEM_UTILITY, ITEM_UNKNOWN) = range(32) _ITEM_EXACT = { "air": 0, "mace": 2, "obsidian": 3, "crying_obsidian": 3, "end_crystal": 4, "respawn_anchor": 5, "glowstone": 6, "totem_of_undying": 7, "golden_apple": 8, "enchanted_golden_apple": 8, "firework_rocket": 9, "elytra": 10, "ender_pearl": 12, "shield": 14, "wind_charge": 15, "crossbow": 16, "arrow": 17, "tipped_arrow": 17, "spectral_arrow": 17, "experience_bottle": 19, "potion": 20, "splash_potion": 20, "lingering_potion": 20, "cobblestone": 24, "stone": 24, "dirt": 24, "netherrack": 24, "end_stone": 24, "deepslate": 24, "cobbled_deepslate": 24, "gravel": 24, "shulker_box": 25, "ender_chest": 25, "chest": 25, "barrel": 25, "glowstone_dust": 26, "netherite_spear": 27, "bow": 28, "cobweb": 29, "nether_star": 30, "player_head": 30, "book": 30, "grindstone": 30, "water_bucket": 30, "bucket": 30, "chorus_fruit": 30, "enchanted_book": 30} _ITEM_SUFFIX = [("_sword", 1), ("_axe", 13), ("_chestplate", 11), ("_helmet", 21), ("_leggings", 22), ("_boots", 23), ("_pickaxe", 18), ("_shovel", 18), ("_hoe", 18), ("_spear", 27), ("_shulker_box", 25), ("_bed", 30), ("_potion", 20)] def item_id(name: str) -> int: """'minecraft:end_crystal' -> ITEM_END_CRYSTAL. Unknown items are ITEM_UNKNOWN, never ITEM_EMPTY: holding something unmodelled is not holding nothing.""" path = name.lower().removeprefix("minecraft:") if path in ("cave_air", "void_air"): return ITEM_EMPTY if path in _ITEM_EXACT: return _ITEM_EXACT[path] for suffix, it in _ITEM_SUFFIX: if path.endswith(suffix): return it return ITEM_UNKNOWN CRYSTAL_FRAME_BYTES = 2592 CRYSTAL_MAGIC = 0x3158434D CUBE_SIDE, CUBE_HALF, COL_SIDE, COL_HALF, FOE_SIDE, FOE_HALF = 13, 6, 13, 6, 5, 2 TOP_SCAN_UP, TOP_SCAN_DOWN = 4, 40 USE_CLICK, USE_HELD = 1, 2 INV_NONE, INV_SWAP_OFFHAND, INV_SWAP_CHEST, INV_REFILL = 0, 1, 2, 3 def _solid(block: int) -> bool: return block not in (BLOCK_AIR, BLOCK_FIRE) def _floor(v: float) -> int: import math return math.floor(v) @dataclass class Crystal: pos: tuple own: bool = False # you placed it (match the entity to your own placement) @dataclass class Blast: pos: tuple radius: float = 6.0 # 6 crystal, 5 anchor damage: float = 0.0 # health + absorption it took from you age: int = 0 # ticks since it went off; send the last 4, newest first @dataclass class Projectile: pos: tuple kind: int = 1 # 1 ender pearl, 2 arrow; only ones someone else threw @dataclass class CrystalFrame: """One crystal tick. Everything is what a vanilla client already has; see docs.html.""" tick: int = 0 ping_ms: int = 0 sensitivity: float = 0.5 pos: tuple = (0.0, 0.0, 0.0) prev_pos: tuple = (0.0, 0.0, 0.0) motion: tuple = (0.0, 0.0, 0.0) # getDeltaMovement() fall_distance: float = 0.0 yaw: float = 0.0 pitch: float = 0.0 eye_height: float = 1.62 # getEyeHeight() for the current pose health: float = 20.0 absorption: float = 0.0 attack_strength: float = 1.0 # getAttackStrengthScale(0.5f) fire_ticks: int = 0 use_ticks: int = 0 since_totem_pop: int = 1000 # ticks since your totem popped (cap 1000) since_elytra_drop: int = 1000 # ticks since you stopped wearing/flying an elytra hurt_time: int = 0 food_level: int = 20 right_click_delay: int = 0 inv_lock: int = 0 # ticks your inventory screen still owns the client using_item: int = ITEM_EMPTY on_ground: bool = True fall_flying: bool = False sneaking: bool = False # isCrouching() sprinting: bool = False last_use: bool = False # the use click you actually applied last tick slow_falling: bool = False weakness: bool = False selected: int = 0 chest_worn: int = ITEM_CHESTPLATE chest_stowed: int = ITEM_EMPTY # chestplate if one is carried, else elytra, else 0 offhand: tuple = (ITEM_TOTEM, 1) hotbar: list = field(default_factory=lambda: [(ITEM_EMPTY, 0)] * 9) backpack: list = field(default_factory=lambda: [(ITEM_EMPTY, 0)] * 27) opp_pos: tuple = (0.0, 0.0, 0.0) opp_prev_pos: tuple = (0.0, 0.0, 0.0) opp_motion: tuple = (0.0, 0.0, 0.0) opp_yaw: float = 0.0 opp_pitch: float = 0.0 opp_health: float = 20.0 opp_hurt_time: int = 0 opp_on_ground: bool = True opp_sprinting: bool = False opp_sneaking: bool = False opp_swinging: bool = False opp_fall_flying: bool = False opp_chest_elytra: bool = False opp_shield_raised: bool = False # using a shield for >= 5 ticks opp_slow_falling: bool = False opp_weakness: bool = False opp_main_item: int = ITEM_EMPTY opp_offhand_item: int = ITEM_EMPTY crystals: list = field(default_factory=list) # up to 12, nearest first blasts: list = field(default_factory=list) # up to 4, newest first projectiles: list = field(default_factory=list) # up to 4 cube_origin: tuple = (0, 0, 0) cube: bytes = bytes(CUBE_SIDE ** 3) # one block id per cell col_top: list = field(default_factory=lambda: [0] * COL_SIDE ** 2) col_id: list = field(default_factory=lambda: [0] * COL_SIDE ** 2) foe_top: list = field(default_factory=lambda: [0] * FOE_SIDE ** 2) foe_id: list = field(default_factory=lambda: [0] * FOE_SIDE ** 2) def fill_terrain(self, block_at, min_y: int = -64, max_y: int = 319) -> None: """block_at(x, y, z) -> BLOCK_* id. Builds the eye cube and both column grids exactly as the API reads them. Call after pos, eye_height and opp_pos are set.""" fx, fy, fz = _floor(self.pos[0]), _floor(self.pos[1]), _floor(self.pos[2]) ey = _floor(self.pos[1] + self.eye_height) ox, oy = fx - CUBE_HALF, ey - CUBE_HALF oz = fz - CUBE_HALF self.cube_origin = (ox, oy, oz) cells = bytearray(CUBE_SIDE ** 3) for y in range(CUBE_SIDE): for z in range(CUBE_SIDE): for x in range(CUBE_SIDE): cells[(y * CUBE_SIDE + z) * CUBE_SIDE + x] = block_at(ox + x, oy + y, oz + z) self.cube = bytes(cells) def top(x, z): # Highest SOLID block at or below feet+4, at most 40 below the feet. start, stop = min(fy + TOP_SCAN_UP, max_y), max(fy - TOP_SCAN_DOWN, min_y) for y in range(start, stop - 1, -1): if _solid(block_at(x, y, z)): return y return stop - 1 for dz in range(-COL_HALF, COL_HALF + 1): for dx in range(-COL_HALF, COL_HALF + 1): i = (dz + COL_HALF) * COL_SIDE + dx + COL_HALF t = top(fx + dx, fz + dz) self.col_top[i], self.col_id[i] = t - fy, block_at(fx + dx, t, fz + dz) px, pz = _floor(self.opp_pos[0]), _floor(self.opp_pos[2]) for dz in range(-FOE_HALF, FOE_HALF + 1): for dx in range(-FOE_HALF, FOE_HALF + 1): i = (dz + FOE_HALF) * FOE_SIDE + dx + FOE_HALF t = top(px + dx, pz + dz) self.foe_top[i], self.foe_id[i] = t - fy, block_at(px + dx, t, pz + dz) @classmethod def unpack(cls, b: bytes) -> "CrystalFrame": """Inverse of pack() (logging, replays, tests).""" if len(b) != CRYSTAL_FRAME_BYTES: raise ValueError("not a crystal frame") o = 0 def take(fmt): nonlocal o v = struct.unpack_from(fmt, b, o) o += struct.calcsize(fmt) return v magic, tick, ping, sens = take("> 1] >> (4 if i & 1 else 0)) & 15 for i in range(CUBE_SIDE ** 3)) return cls( tick=tick, ping_ms=ping, sensitivity=sens, pos=d[0:3], prev_pos=d[3:6], motion=d[6:9], fall_distance=d[9], yaw=yaw, pitch=pitch, eye_height=eye, health=hp, absorption=absorb, attack_strength=atk, fire_ticks=fire, use_ticks=use_t, since_totem_pop=stp, since_elytra_drop=sed, hurt_time=hurt, food_level=food, right_click_delay=rcd, inv_lock=lock, using_item=using, on_ground=bool(flags & 1), fall_flying=bool(flags & 2), sneaking=bool(flags & 4), sprinting=bool(flags & 8), last_use=bool(flags & 16), slow_falling=bool(eff & 1), weakness=bool(eff & 2), selected=sel, chest_worn=worn, chest_stowed=stowed, offhand=(oh_i, oh_c), hotbar=list(zip(hb_i, hb_c)), backpack=list(zip(bp_i, bp_c)), opp_pos=od[0:3], opp_prev_pos=od[3:6], opp_motion=od[6:9], opp_yaw=oyaw, opp_pitch=opitch, opp_health=ohp, opp_hurt_time=ohurt, opp_on_ground=bool(oflags & 1), opp_sprinting=bool(oflags & 2), opp_sneaking=bool(oflags & 4), opp_swinging=bool(oflags & 8), opp_fall_flying=bool(oflags & 16), opp_chest_elytra=bool(oflags & 32), opp_shield_raised=bool(oflags & 64), opp_slow_falling=bool(oeff & 1), opp_weakness=bool(oeff & 2), opp_main_item=omain, opp_offhand_item=ooff, crystals=[Crystal(c[0:3], bool(c[3])) for c in crystals], blasts=[Blast(x[0:3], x[3], x[4], x[5]) for x in blasts], projectiles=[Projectile(x[0:3], x[3]) for x in projs], cube_origin=origin, cube=cube, col_top=col_top, col_id=list(col_id), foe_top=foe_top, foe_id=list(foe_id)) def pack(self) -> bytes: if len(self.crystals) > 12 or len(self.blasts) > 4 or len(self.projectiles) > 4: raise ValueError("at most 12 crystals, 4 blasts and 4 projectiles") flags = (self.on_ground | self.fall_flying << 1 | self.sneaking << 2 | self.sprinting << 3 | self.last_use << 4) effects = self.slow_falling | self.weakness << 1 oflags = (self.opp_on_ground | self.opp_sprinting << 1 | self.opp_sneaking << 2 | self.opp_swinging << 3 | self.opp_fall_flying << 4 | self.opp_chest_elytra << 5 | self.opp_shield_raised << 6) oeffects = self.opp_slow_falling | self.opp_weakness << 1 out = [struct.pack("> 1] |= (v & 15) << (4 if i & 1 else 0) out += [struct.pack("<3i", *self.cube_origin), bytes(nib), struct.pack(f"<{COL_SIDE ** 2}h", *self.col_top), bytes(self.col_id), struct.pack(f"<{FOE_SIDE ** 2}h", *self.foe_top), bytes(self.foe_id), bytes(3)] blob = b"".join(out) assert len(blob) == CRYSTAL_FRAME_BYTES, len(blob) return blob class APIError(Exception): def __init__(self, code: str, message: str): super().__init__(f"{code}: {message}") self.code = code # ---------------------------------------------------------------- minimal websocket ---- class WebSocket: def __init__(self, url: str, timeout: float = 30.0, pin_sha256: str | None = None): u = urlparse(url) port = u.port or (443 if u.scheme == "wss" else 80) sock = socket.create_connection((u.hostname, port), timeout=timeout) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) if u.scheme == "wss" and pin_sha256: # The GPU's certificate is self-signed per rental and PINNED: its SHA-256 came # from the API over normal HTTPS. Nothing is sent until it matches. ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE ctx.minimum_version = ssl.TLSVersion.TLSv1_3 sock = ctx.wrap_socket(sock) der = sock.getpeercert(binary_form=True) or b"" if not hmac.compare_digest(hashlib.sha256(der).hexdigest(), pin_sha256.lower()): sock.close() raise ConnectionError("GPU certificate does not match the pin; refusing") elif u.scheme == "wss": ctx = ssl.create_default_context() ctx.minimum_version = ssl.TLSVersion.TLSv1_2 sock = ctx.wrap_socket(sock, server_hostname=u.hostname) self.sock = sock key = base64.b64encode(os.urandom(16)).decode() path = u.path or "/" host = u.hostname if u.port is None else f"{u.hostname}:{u.port}" req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUpgrade: websocket\r\n" f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n" f"Sec-WebSocket-Version: 13\r\nUser-Agent: mca-client/1\r\n\r\n") sock.sendall(req.encode()) head = b"" while b"\r\n\r\n" not in head: chunk = sock.recv(4096) if not chunk: raise ConnectionError("handshake failed") head += chunk status, _, rest = head.partition(b"\r\n\r\n") if b" 101 " not in status.split(b"\r\n")[0]: raise ConnectionError("upgrade refused: " + status.split(b"\r\n")[0].decode(errors="replace")) self.buf = rest def send(self, data: bytes | str) -> None: opcode = 1 if isinstance(data, str) else 2 payload = data.encode() if isinstance(data, str) else data mask = os.urandom(4) n = len(payload) if n < 126: head = struct.pack("!BB", 0x80 | opcode, 0x80 | n) elif n < 65536: head = struct.pack("!BBH", 0x80 | opcode, 0x80 | 126, n) else: head = struct.pack("!BBQ", 0x80 | opcode, 0x80 | 127, n) masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) self.sock.sendall(head + mask + masked) def _parse(self): """One complete message from the buffer, consuming it only when whole: a timeout can never leave a half-read frame behind. Returns (kind, payload) or None.""" i, message, kind = 0, b"", None while True: buf = self.buf if len(buf) - i < 2: return None start = i b0, b1 = buf[i], buf[i + 1] fin, opcode, n, j = b0 & 0x80, b0 & 0x0F, b1 & 0x7F, i + 2 if b1 & 0x80: raise ConnectionError("server frames must not be masked") if n == 126: if len(buf) - j < 2: return None n, j = struct.unpack_from("!H", buf, j)[0], j + 2 elif n == 127: if len(buf) - j < 8: return None n, j = struct.unpack_from("!Q", buf, j)[0], j + 8 if len(buf) - j < n: return None payload, end = buf[j:j + n], j + n if opcode >= 8: # Control frame (possibly between fragments): splice it out and handle it. self.buf = buf[:start] + buf[end:] if opcode == 8: return ("close", b"") if opcode == 9: self._control(10, payload) i = start continue if opcode in (1, 2): kind = opcode message += payload i = end if fin: self.buf = buf[end:] return ("text" if kind == 1 else "binary", message) def _fill(self, timeout): """Read whatever arrives within `timeout` seconds (None = block). False on timeout.""" if isinstance(self.sock, ssl.SSLSocket) and self.sock.pending(): timeout = 0 self.sock.settimeout(timeout) try: chunk = self.sock.recv(65536) except (socket.timeout, ssl.SSLWantReadError, BlockingIOError): return False if not chunk: raise ConnectionError("connection closed") self.buf += chunk return True def recv(self, timeout: float | None = None): """Returns str (text), bytes (binary), None (closed), or TimeoutError after `timeout` seconds with nothing complete. Single-threaded: TLS sockets must not be read and written from two threads at once.""" deadline = None if timeout is None else time.monotonic() + timeout while True: got = self._parse() if got is not None: kind, payload = got if kind == "close": return None return payload.decode() if kind == "text" else payload left = None if deadline is None else max(0.0, deadline - time.monotonic()) if not self._fill(left) and deadline is not None and time.monotonic() >= deadline: raise TimeoutError() def _control(self, opcode: int, payload: bytes) -> None: mask = os.urandom(4) masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) self.sock.sendall(struct.pack("!BB", 0x80 | opcode, 0x80 | len(payload)) + mask + masked) def close(self) -> None: try: self._control(8, struct.pack("!H", 1000)) except OSError: pass self.sock.close() # ---------------------------------------------------------------- the API ------------- class Client: def __init__(self, key: str, model: str = "v32", api: str = DEFAULT_API, wait: float = 600.0, on_status=None, client_name: str = "mca-client/1"): self.key, self.model, self.api, self.wait = key, model, api.rstrip("/"), wait self.on_status = on_status or (lambda m: None) self.client_name = client_name self.ws = None self.info: dict = {} self.events: list = [] def __enter__(self): self.connect() return self def __exit__(self, *exc): self.close() def _session(self) -> dict: """Ask the API for a session; waits (polling) while a GPU starts.""" deadline = time.time() + self.wait while True: req = urllib.request.Request( self.api + "/api/v1/session", method="POST", data=json.dumps({"model": self.model}).encode(), headers={"Authorization": "Bearer " + self.key, "Content-Type": "application/json", "User-Agent": self.client_name}) try: with urllib.request.urlopen(req, timeout=30) as r: body, status = json.loads(r.read() or b"{}"), r.status except urllib.error.HTTPError as e: try: body = json.loads(e.read() or b"{}") except ValueError: body = {} raise APIError(body.get("error", f"http_{e.code}"), body.get("message", "")) from None if status == 200: return body self.on_status(body) if time.time() > deadline: raise TimeoutError("the GPU did not answer the hello") time.sleep(float(body.get("retry_after", 3))) def connect(self) -> dict: session = self._session() self.ws = WebSocket(session["url"], pin_sha256=session["cert_sha256"]) self.ws.send(json.dumps({"type": "hello", "ticket": session["ticket"], "client": self.client_name})) deadline = time.time() + 30 while time.time() < deadline: try: msg = self.ws.recv(10) except TimeoutError: continue if msg is None: raise ConnectionError("closed during hello") m = json.loads(msg) if m["type"] == "ready": self.info = dict(m, url=session["url"]) return self.info if m["type"] == "error": raise APIError(m.get("code", "error"), m.get("message", "")) raise TimeoutError("GPU did not become ready") def step(self, frame: "Frame | CrystalFrame | bytes") -> Action: """Send one frame, return the action for it. Control messages that arrive in between are collected in self.events.""" self.ws.send(frame if isinstance(frame, (bytes, bytearray)) else frame.pack()) while True: msg = self.ws.recv() if msg is None: raise ConnectionError("server closed the session") if isinstance(msg, bytes): return Action.unpack(msg) m = json.loads(msg) if m.get("type") == "error": raise APIError(m.get("code", "error"), m.get("message", "")) self.events.append(m) def poll(self, until: float) -> list: """Everything that arrives before time.monotonic() reaches `until`: the pipelined loop is send(frame) then poll(next_tick). Actions come back in order; match by tick.""" out = [] while True: left = until - time.monotonic() try: out.append(self.recv(max(0.0, left))) except TimeoutError: return out if left <= 0: return out def send(self, frame: "Frame | bytes") -> None: """Pipelined use: send a frame every tick without waiting for its reply, and collect replies with poll(). Keep both on one thread.""" self.ws.send(frame if isinstance(frame, (bytes, bytearray)) else frame.pack()) def recv(self, timeout: float | None = None): """The next action, or a dict for a control message. Raises APIError on an error, TimeoutError if nothing arrives within `timeout`.""" msg = self.ws.recv(timeout) if msg is None: raise ConnectionError("server closed the session") if isinstance(msg, bytes): return Action.unpack(msg) m = json.loads(msg) if m.get("type") == "error": raise APIError(m.get("code", "error"), m.get("message", "")) return m def new_fight(self) -> None: self.ws.send(json.dumps({"type": "new_fight"})) def close(self) -> None: if self.ws: try: self.ws.send(json.dumps({"type": "bye"})) except OSError: pass self.ws.close() self.ws = None