cockatrice-custom-tokens/scripts/spellbook.py

121 lines
5.4 KiB
Python

"""Opt-in Commander Spellbook API integration (standard library only)."""
import json
import re
from pathlib import Path
import time
import urllib.error
import urllib.request
BASE = 'https://backend.commanderspellbook.com/'
BRACKETS = {'R': 'Ruthless', 'S': 'Spicy', 'P': 'Powerful', 'O': 'Oddball',
'C': 'Core', 'E': 'Exhibition', 'B': 'Banned'}
_last_request = 0.0
def is_command_zone(name):
"""Recognize legacy and individually named Command Zone reminder tokens."""
name = ' '.join(name.casefold().replace('_', ' ').split())
return name in ('command zone', 'command-zone') or bool(
re.fullmatch(r'command[ -]zone\s*-\s*\S.*', name))
def request(endpoint, payload):
global _last_request
time.sleep(max(0, 1.0 - (time.monotonic() - _last_request)))
_last_request = time.monotonic()
req = urllib.request.Request(BASE + endpoint, data=json.dumps(payload).encode(),
headers={'Content-Type': 'application/json', 'Accept': 'application/json',
'User-Agent': 'cockatrice-custom-tokens-deck-checker/1.0'})
try:
with urllib.request.urlopen(req, timeout=30) as response:
data = response.read(8 * 1024 * 1024 + 1)
if len(data) > 8 * 1024 * 1024:
raise ValueError('Spellbook response exceeds 8 MiB')
result = json.loads(data)
if not isinstance(result, dict):
raise ValueError('Unexpected Spellbook response')
return result
except urllib.error.HTTPError as error:
if error.code == 429:
raise ValueError('Spellbook rate limit reached; retry later (Retry-After: '
+ str(error.headers.get('Retry-After', 'unspecified')) + ')') from None
raise ValueError(f'Spellbook HTTP {error.code}; no analysis available') from None
except (urllib.error.URLError, TimeoutError, OSError, UnicodeError, json.JSONDecodeError) as error:
raise ValueError(f'Spellbook request failed: {error}') from None
def deck_payload(root, find_commanders):
zones = find_commanders(root)
if not zones:
raise ValueError('No Commander/Command Zone custom zone; designate the commander before analysis')
commanders, main = {}, {}
def add(card, target):
name = card.get('name', '').strip()
if is_command_zone(name):
return
try:
count = int(card.get('number', '0'))
except ValueError:
count = 0
if not name or len(name) > 256 or count <= 0:
raise ValueError('Invalid card name or quantity; analysis aborted')
target[name] = target.get(name, 0) + count
def walk(zone):
if zone in zones:
return
for card in zone.findall('./card'):
add(card, main)
for child in zone.findall('./zone'):
walk(child)
for zone in zones:
for card in zone.findall('./card'):
add(card, commanders)
for board in root.findall('./zone'):
if board.get('name', '').strip().casefold() == 'main':
walk(board)
if not commanders or not main:
raise ValueError('Empty commander or main deck; analysis aborted')
if len(main) > 600 or len(commanders) > 12:
raise ValueError('Deck exceeds Spellbook API limits')
return {key: [{'card': name, 'quantity': count} for name, count in cards.items()]
for key, cards in [('main', main), ('commanders', commanders)]}
def analyze(root, find_commanders, fetch=request):
payload = deck_payload(root, find_commanders)
combos = fetch('find-my-combos?limit=100', payload)
bracket = fetch('estimate-bracket', payload)
results = combos.get('results')
if not isinstance(results, dict) or not isinstance(results.get('included'), list):
raise ValueError('Unexpected Spellbook combo response')
if bracket.get('bracketTag') not in BRACKETS:
raise ValueError('Unrecognized Spellbook bracket response')
return {'source': 'https://commanderspellbook.com/',
'bracket': BRACKETS[bracket['bracketTag']],
'partial': bool(combos.get('next')), 'combos': results,
'bracket_details': bracket}
def display_analysis(analyses, no_color=False):
from rich.console import Console
from rich.text import Text
console = Console(no_color=no_color)
console.print(Text('\nCommander Spellbook · https://commanderspellbook.com/', style='bold cyan'))
for path, result in analyses.items():
console.print(Text(Path(path).name, style='bold'))
if 'error' in result:
console.print(Text(result['error'], style='red'))
continue
included = result['combos']['included']
console.print(Text(f"Estimated bracket: {result['bracket']} · {len(included)} included combo variants"
+ (' (partial results)' if result['partial'] else ''), style='cyan'))
for combo in included[:10]:
names = [item.get('card', {}).get('name', '?') for item in combo.get('uses', [])]
console.print(Text(' + '.join(names) + ' — https://commanderspellbook.com/combo/' + str(combo.get('id', ''))))
if len(included) > 10:
console.print(Text('Showing first 10; use --json for returned combo details.'))
console.print(Text('Estimates, not legality certification. No automatic strategy tags or deck edits.', style='dim'))