# mtg2gmi.py -rw-r--r-- 1.9 KiB View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import sys
import requests
import collections


# pipe into this script a list of quantities & cards (lines with no quantity are ignored)

def main():
    data = collections.defaultdict(list)
    cards = []
    for line in sys.stdin.read().split("\n"):
        if line != "" and line[0].isdigit():
            cards.append(line)
    # split in half. this should work for any deck with <100 unique cards
    # can't find the maximum input length documented anywhere
    length = len(cards)
    cards.sort(key=lambda x: x.partition(" ")[2])
    middle_index = length//2
    query1 =" OR ".join("!\"" + c.partition(" ")[2] + "\"" for c in cards[:middle_index])
    query2 =" OR ".join("!\"" + c.partition(" ")[2] + "\"" for c in cards[middle_index:])
    items = []
    for query in [query1, query2]:
        res = requests.get(
            "https://api.scryfall.com/cards/search",
            params={"q": query},
        )
        items += res.json()["data"]
    items.sort(key=lambda x: x["name"])
    if len(items) != length:
        print("input and output lengths don't match:", length, len(items))
        return 1
    for n, j in enumerate(items):
        try:
            type_line = j["type_line"]
            if "—" in type_line:
                basic_type = type_line.partition(" — ")[0].split(" ")[-1]  # eg sorcery, creature
            else:
                basic_type = type_line.split(" ")[-1]
            j["line"] = cards[n]
            data[basic_type].append(j)
        except Exception as e:
            print(j)
            print(e)
    # arbitrary order 
    for cardtype in ["Planeswalker", "Creature", "Sorcery", "Instant", "Artifact", "Enchantment", "Land"]:
        if len(data[cardtype]) > 0:
            if cardtype == "Sorcery":
                print("### Sorceries")
            else:
                print("###", cardtype + "s")
            for i in data[cardtype]:
                print("=>", i["scryfall_uri"], i["line"])


main()