Example #1
0
def get_sets():
    global all_sets

    sets = Set.all()
    all_sets = []
   
    for set in sets:
        raw_set = str(set).replace('Set', '').replace('=', '').replace('(', '').replace(')', '').replace("'",'').split(',')
        if(raw_set[5] == ' standardLegal'):
            format = 'standard'
        elif(raw_set[4] == ' expandedLegal'):
            format = 'expanded'
        else:
            format = 'unlimited'

        this_set = {
            'id' : raw_set[8].replace('ptcgoCode','').replace(' ', '', 1),
            'name' : raw_set[6].replace('name', '').replace(' ', '', 1),
            'format' : format,
            'size' : int(raw_set[-2].replace('total', '')),
            'req_id' : raw_set[0].replace('id', '').replace(' ', '', 1),
            'cards' : []
        }

        all_sets.append(this_set)
Example #2
0
def show(name, card_set_text):
    card = parse_card(name, card_set_text)

    if type(card) == str:
        return card

    card_set = Set.find(card.set_code)
    return embed_create(card, card_set)
Example #3
0
def cmprice(name, card_set_text):
    card = parse_card(name, card_set_text)

    if type(card) == str:
        return card

    card_set = Set.find(card.set.id)
    return cmprice_embed(card, card_set)
Example #4
0
def search(name):
    if name == "":
        return ("", 0)

    # Users will often enter 'hydreigon ex' when they really mean
    # 'hydreigon-ex'. This annoying, but simply inserting the dash does not
    # work as it makes Ruby/Sapphire era ex cards unaccessible. Instead,
    # search for both
    cards = []
    if name.lower().endswith(" ex"):
        cards.extend(Card.where(name=name.lower()))
        cards.extend(Card.where(name=name.lower().replace(" ex", "-ex")))
    # GX cards do not have the same issue, so we can simply insert the dash
    # as expected
    elif name.lower().endswith(" gx"):
        cards.extend(Card.where(name=name.lower().replace(" gx", "-gx")))
    # Delta card text replacement
    elif name.lower().endswith(" delta"):
        cards.extend(Card.where(name=name.lower().replace(" delta", " δ")))
    # Otherwise, search for the given text
    else:
        cards = Card.where(name=name)

    # Give an error if there are no matches
    if len(cards) == 0:
        return ("No matches for search '%s'" % name, 0)

    # If there is exactly one match, save time for the user and give the
    # !show output instead
    if len(cards) == 1:
        return (show(cards[0].name, cards[0].set_code), 1)

    # If there are matches, build a string with the name, set and set code
    # of every match
    cards_with_sets = []
    for card in cards:
        card_set = Set.find(card.set_code)

        # Re-arrange the release data so it is ISO
        date_split = card_set.release_date.split("/")
        card_set.release_date = "%s-%s-%s" % (date_split[2], date_split[0],
                                              date_split[1])

        cards_with_sets.append((card, card_set))

    # Sort the list of cards by set release date
    cards_with_sets.sort(key=lambda card: card[1].release_date)

    # Create the returned string
    return_str = "Matches for search '%s'\n" % name
    for card in cards_with_sets:
        return_str += ("%s - %s %s/%s (`%s-%s`)\n" %
                       (card[0].name, card[1].name, card[0].number,
                        card[1].total_cards, card[1].code, card[0].number))

    return (return_str, len(cards_with_sets))
    def test_find_returns_set(self):
        with vcr.use_cassette('fixtures/xy11.yaml'):
            set = Set.find('xy11')

            self.assertEqual('xy11', set.code)
            self.assertEqual('Steam Siege', set.name)
            self.assertEqual('XY', set.series)
            self.assertEqual(114, set.total_cards)
            self.assertEqual(True, set.standard_legal)
            self.assertEqual('08/03/2016', set.release_date)
 def test_find_returns_set(self):
     with vcr.use_cassette('fixtures/xy11.yaml'):
         set = Set.find('xy11')
         self.assertEqual('xy11', set.id)
         self.assertEqual('Steam Siege', set.name)
         self.assertEqual('XY', set.series)
         self.assertEqual(114, set.printedTotal)
         self.assertEqual(116, set.total)
         self.assertEqual('STS', set.ptcgoCode)
         self.assertEqual("2016/08/03", set.releaseDate)
 def test_find_returns_set(self):
     with vcr.use_cassette('fixtures/xy11.yaml'):
         set = Set.find('xy11')
         
         self.assertEqual('xy11', set.code)
         self.assertEqual('Steam Siege', set.name)
         self.assertEqual('XY', set.series)
         self.assertEqual(114, set.total_cards)
         self.assertEqual(True, set.standard_legal)
         self.assertEqual(True, set.expanded_legal)
         self.assertEqual('08/03/2016', set.release_date)
Example #8
0
 def getAllSetIds(self):
     """
     Gets all card set names and corresponding codes
     :return: Prints list of sets to console
     """
     allCardSets = Set.all()
     cardSetName = [sets.name for sets in allCardSets]
     cardSetCode = [sets.code for sets in allCardSets]
     self.setDict = {
         cardSetName[i].lower(): cardSetCode[i]
         for i in range(len(cardSetName))
     }
    def _card_to_searchresult(card: Card) -> SearchResult:
        """
        Convert a pokemontcgsdk Card object to a SearchResult.

        :param card: The card to make a SearchResult from
        :returns: A SearchResult object for the passed Card.
        """
        card_set = Set.find(card.set_code)
        return SearchResult(name=card.name,
                            set_name=card_set.name,
                            set_no=card.number,
                            set_max=card_set.total_cards,
                            release=PokemonTCGIOV1Provider._set_date_to_date(
                                card_set.release_date),
                            card_id=f"{card_set.code}-{card.number}")
    def _newest_legal_format(card: Card) -> str:
        """
        Get the most restrictive format the given card is legal in.

        :param card: The card to get the format of
        :returns: The name of the most restrictive format the card is legal in
        """
        card_set = Set.find(card.set_code)
        if card_set.standard_legal:
            legal_format = "Standard"
        elif card_set.expanded_legal:
            legal_format = "Expanded"
        else:
            legal_format = "Legacy"

        return legal_format
Example #11
0
def main():
    print("Downloading all cards... Please be patient")

    fields_remain_same = [
        'id', 'name', 'national_pokedex_number', 'image_url',
        'image_url_hi_res', 'subtype', 'supertype', 'hp', 'number', 'artist',
        'rarity', 'series', 'set', 'set_code', 'converted_retreat_cost',
        'evolves_from'
    ]

    set_fields = [
        'total_cards', 'standard_legal', 'expanded_legal', 'release_date'
    ]

    cards = Card.all()
    sets = Set.all()

    create_workbook(cards, fields_remain_same, sets, set_fields)
Example #12
0
def insert_cards(set_name):
    cards = Card.where(q='set.name:{}'.format(set_name))
    sets = Set.all()

    sets_to_save = []
    for set in sets:
        sets_to_save.append(PokemonCardSet(id=set.id, name=set.name))

    overlap, inserted = _dedupe_and_insert(PokemonCardSet, sets_to_save)

    cards_to_save = []
    for card in cards:
        cards_to_save.append(
            PokemonCard(id=card.id,
                        name=card.name,
                        set=PokemonCardSet.objects.get(id=card.set.id)))

    overlap, inserted = _dedupe_and_insert(PokemonCard, cards_to_save)

    return overlap, inserted
def search(name):
	# Search for the given text
	cards = Card.where(name = name).all()

	if name == "":
		return

	# Give an error if there are no matches
	if len(cards) == 0:
		return "No matches for search '%s'" % name

	# If there is exactly one match, save time for the user and give the
	# !show output instead
	if len(cards) == 1:
		return show(cards[0].name, cards[0].set_code)

	# If there are matches, build a string with the name, set and set code
	# of every match
	cards_with_sets = []
	for card in cards:
		card_set = Set.find(card.set_code)

		# Re-arrange the release data so it is ISO
		date_split = card_set.release_date.split("/")
		card_set.release_date = ("%s-%s-%s" %
			(date_split[2], date_split[0], date_split[1]))

		cards_with_sets.append((card, card_set))

	# Sort the list of cards by set release date
	cards_with_sets.sort(key = lambda card : card[1].release_date)

	# Create the returned string
	return_str = "Matches for search '%s'\n" % name
	for card in cards_with_sets:
		return_str += ("%s - %s %s/%s (`%s-%s`)\n" %
			(card[0].name, card[1].name, card[0].number,
			 card[1].total_cards, card[1].code, card[0].number))
	return return_str
Example #14
0
def initial_sets_input():  # add sets info on db
    sets = Set.all()
    db = conn.cursor()
    for pc_set in sets:
        name = pc_set.name
        code = pc_set.code
        ptcgo_code = pc_set.ptcgo_code
        series = pc_set.series
        total_cards = pc_set.total_cards  # already in int
        standard_legal = str(pc_set.standard_legal)
        expanded_legal = str(pc_set.expanded_legal)
        release_date = parser.parse(
            pc_set.release_date).date()  # only want date, not time
        updated_at = parser.parse(pc_set.updated_at)
        logo_url = pc_set.logo_url
        symbol_url = pc_set.symbol_url
        db.execute(
            '''insert into pokemon_cards_set(    name, code, ptcgo_code, series, total_cards, standard_legal, expanded_legal,
                                                            release_date, updated_at, logo_url, symbol_url)
                                values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''', [
                name, code, ptcgo_code, series, total_cards, standard_legal,
                expanded_legal, release_date, updated_at, logo_url, symbol_url
            ])
        conn.commit()
Example #15
0
def new_set(set_):
    new_set_ = Set.where(name=set_)
    cards = Card.where(set=set_)
    for card in cards:
        input_card(card)
    def show(self, card_id: str) -> Optional[ShowResult]:
        """
        Get details on a specific card.

        :param card_id: The unique ID on the card
        :returns: The result of the card lookup, or None if no card matches
        """
        card = Card.find(card_id)
        card_set = Set.find(card.set_code)
        if not card:
            return None

        if card.supertype == "Pokémon":
            fields = []

            # If the Pokemon has an ability, it goes in its own field
            if card.ability:
                fields.append(
                    (f"{card.ability['type']}: {card.ability['name']}",
                     card.ability["text"] or "\u200b"))

            # Each attack is its own field
            if card.attacks:
                for attack in card.attacks:
                    name = ""
                    text = ""
                    for cost in attack["cost"]:
                        name += emoji[cost]
                    name += f" {attack['name']}"
                    if "damage" in attack and attack["damage"] != "":
                        name += f" - {attack['damage']}"
                    if "text" in attack and attack["text"] != "":
                        text = attack["text"]
                    else:
                        text = "\u200b"
                    fields.append((name, text))

            # Weakness, resistances and retreat all go on the same line
            bottom_line = ""
            if card.weaknesses:
                bottom_line += "Weakness: "
                bottom_line += ", ".join([
                    f"{emoji[w['type']]} ({w['value']})"
                    for w in card.weaknesses
                ])
            if card.resistances:
                bottom_line += " - Resistance: "
                bottom_line += ", ".join([
                    f"{emoji[r['type']]} ({r['value']})"
                    for r in card.resistances
                ])
            if card.retreat_cost:
                bottom_line += f" - Retreat: {emoji['Colorless'] * len(card.retreat_cost)}"
            if bottom_line != "":
                fields.append(("\u200b", bottom_line))

            return ShowResult(
                name=card.name,
                supertype=card.supertype,
                subtype=card.subtype,
                legality=PokemonTCGIOV1Provider._newest_legal_format(card),
                set_name=card_set.name,
                set_no=card.number,
                set_max=card_set.total_cards,
                image=card.image_url,
                set_icon=card_set.symbol_url,
                fields=fields,
                hp=card.hp,
                evolves_from=card.evolves_from,
                types=card.types)
        else:
            return ShowResult(
                name=card.name,
                supertype=card.supertype,
                subtype=card.subtype,
                legality=PokemonTCGIOV1Provider._newest_legal_format(card),
                set_name=card_set.name,
                set_no=card.number,
                set_max=card_set.total_cards,
                image=card.image_url,
                set_icon=card_set.symbol_url,
                fields=[("\u200b", text) for text in card.text])
    def test_all_returns_all_sets(self):
        with vcr.use_cassette('fixtures/all_sets.yaml'):
            sets = Set.all()

            self.assertGreater(len(sets), 70)
Example #18
0
#! /usr/bin/env python

from pokemontcgsdk import Card
from pokemontcgsdk import Set
from pokemontcgsdk import Type
from pokemontcgsdk import Supertype
from pokemontcgsdk import Subtype
import json

#Gets all info needed
cards = Card.all()
sets = Set.all()
types = Type.all()
subtypes = Subtype.all()
supertypes = Supertype.all()

print('Resources gathered, converting to json...')

#Loops through all cards an eliminates all NoneTypes to eliminate excess null values in json
cards_list = []
for c in cards:
    card_dict = {}

    if c.id is not None:
        card_dict["id"] = c.id

    if c.name is not None:
        card_dict["name"] = c.name

    if c.national_pokedex_number is not None:
        card_dict["national_pokedex_number"] = c.national_pokedex_number
Example #19
0
def getSets():
    sets= [(s.name,s.symbol_url) for s in Set.all()]
    return sets
    def test_where_filters_on_name(self):
        with vcr.use_cassette('fixtures/filtered_sets.yaml'):
            sets = Set.where(q='name:steam')

            self.assertEqual(1, len(sets))
            self.assertEqual('xy11', sets[0].id)
 def test_where_filters_on_name(self):
     with vcr.use_cassette('fixtures/filtered_sets.yaml'):
         sets = Set.where(name='steam')
         
         self.assertEqual(1, len(sets))
         self.assertEqual('xy11', sets[0].code)
    def test_all_returns_all_sets(self):
        with vcr.use_cassette('fixtures/all_sets.yaml'):
            sets = Set.all()

            self.assertGreater(len(sets), 70)
Example #23
0
def fetch_standard():
    sets = Set.where(standardLegal=True)
    return get_cards_from_sets(sets)
def show(name, card_set):
	# If the card set includes a specific number, we can just use that to
	# get the card
	card = None
	if "-" in card_set:
		card = Card.find(card_set)
		if card == None:
			return "No results for card `%s`" % card_set
	else:
		# Search for the given card
		cards = Card.where(name = name).where(setCode=card_set).all()

		if len(cards) == 0:
			return ("No results found for '%s' in set `%s`" %
				(name, card_set))

		if len(cards) > 1:
			return (
"""
Too many results. Try specifying the card number too. For example
`!show %s %s-%s`
""" % (name, card_set, cards[0].number)
			)

		card = cards[0]

	# Create a string for the card text
	return_str = "%s\n" % card.image_url
	return_str += "```\n"

	# Pokemon are the most involved as they have a lot going on
	if card.supertype == "Pokémon":
		# Start with the Pokemon's name and type(s)
		return_str += "%s - %s" % (card.name, "/".join(card.types))

		# Some Pokemon have no HP (e.g. the second half of LEGEND cards),
		# so do only add it if it exists
		if card.hp != None:
			return_str += " - HP%s\n" % (card.hp)
		else:
			return_str += "\n"

		return_str += "%s Pokemon\n\n" % card.subtype

		# Add the ability if present
		if card.ability != None:
			return_str += "%s: %s\n" % (card.ability['type'], card.ability['name'])
			return_str += "%s\n" % card.ability['text']
			return_str += "\n"

		# Add any attacks, including shorthand cost, text and damage
		if card.attacks != None:
			for attack in card.attacks:
				for cost in attack['cost']:
					return_str += "%s" % short_energy[cost]
				return_str += " %s" % attack['name']
				if attack['damage'] != '':
					return_str += ": %s damage\n" % attack['damage']
				else:
					return_str += "\n"
				if attack['text'] != None:
					return_str += "%s\n" % attack['text']
				return_str += "\n"

		# Add weakness, resistances and retreat if they exist
		if card.weaknesses != None:
			for weakness in card.weaknesses:
				return_str += ("Weakness: %s (%s)\n" %
					(weakness['type'], weakness['value']))
		if card.resistances != None:
			for resistance in card.resistances:
				return_str += ("Resistance: %s (%s)\n" %
					(resistance['type'], resistance['value']))
		if card.retreat_cost != None:
			return_str += "Retreat: %s" % len(card.retreat_cost)

	# Trainers and Energy are a lot easier
	elif card.supertype == "Trainer" or card.supertype == "Energy":
		return_str += "%s\n" % card.name
		return_str += "%s\n\n" % card.subtype
		return_str += "%s\n" % "\n\n".join(card.text)

	# Finally, get the set and legality info
	card_set = Set.find(card.set_code)
	return_str += "\n\n%s - %s/%s" % (card_set.name, card.number, card_set.total_cards)
	if card_set.standard_legal == True:
		return_str += " (Standard)"
	elif card_set.expanded_legal == True:
		return_str += " (Expanded)"
	else:
		return_str += " (Legacy)"

	return_str += "```\n"
	return return_str
Example #25
0
 def getSet(self, setName):
     return Set.find(id=f"{self.setDict[setName].lower()}")
Example #26
0
def fetch_expanded():
    sets = Set.where(expandedLegal=True)
    return get_cards_from_sets(sets)
Example #27
0
def text(name, card_set_text):
	card = parse_card(name, card_set_text)
	card_set = Set.find(card.set_code)

	# Create a string for the card text
	return_str = "```\n"

	# Pokemon are the most involved as they have a lot going on
	if card.supertype == "Pokémon":
		# Start with the Pokemon's name and type(s)
		return_str += "%s - %s" % (card.name, "/".join(card.types))

		# Some Pokemon have no HP (e.g. the second half of LEGEND cards),
		# so do only add it if it exists
		if card.hp != None:
			return_str += " - HP%s\n" % (card.hp)
		else:
			return_str += "\n"

		return_str += "%s Pokemon" % card.subtype
		if card.evolves_from != None and card.evolves_from != "":
			return_str += " (Evolves from %s)" % card.evolves_from
		return_str += "\n\n"

		# Add the ability if present
		if card.ability != None:
			return_str += "%s: %s\n" % (card.ability['type'], card.ability['name'])
			return_str += "%s\n" % card.ability['text']
			return_str += "\n"

		# Add any attacks, including shorthand cost, text and damage
		if card.attacks != None:
			for attack in card.attacks:
				for cost in attack['cost']:
					return_str += "%s" % short_energy[cost]
				return_str += " %s" % attack['name']
				if attack['damage'] != '':
					return_str += ": %s damage\n" % attack['damage']
				else:
					return_str += "\n"
				if attack['text'] != None:
					return_str += "%s\n" % attack['text']
				return_str += "\n"

		# Add weakness, resistances and retreat if they exist
		if card.weaknesses != None:
			for weakness in card.weaknesses:
				return_str += ("Weakness: %s (%s)\n" %
					(weakness['type'], weakness['value']))
		if card.resistances != None:
			for resistance in card.resistances:
				return_str += ("Resistance: %s (%s)\n" %
					(resistance['type'], resistance['value']))
		if card.retreat_cost != None:
			return_str += "Retreat: %s" % len(card.retreat_cost)

	# Trainers and Energy are a lot easier
	elif card.supertype == "Trainer" or card.supertype == "Energy":
		return_str += "%s\n" % card.name
		return_str += "%s\n\n" % card.subtype
		return_str += "%s\n" % "\n\n".join(card.text)

	# Finally, get the set and legality info
	return_str += "\n\n%s - %s/%s" % (card_set.name, card.number, card_set.total_cards)
	if card_set.standard_legal == True:
		return_str += " (Standard)"
	elif card_set.expanded_legal == True:
		return_str += " (Expanded)"
	else:
		return_str += " (Legacy)"

	return_str += "```\n"
	return return_str
Example #28
0
from pokemontcgsdk import Set, Card
from lxml import etree as et

root = et.Element('cockatrice_carddatabase')
root.attrib["version"] = "3"
xmlsets = et.SubElement(root, "sets")
xmlcards = et.SubElement(root, "cards")
#Save sets
for s in Set.all():
    nset = et.SubElement(xmlsets, "set")

    name = et.SubElement(nset, "name")
    longname = et.SubElement(nset, "longname")
    setType = et.SubElement(nset, "setType")
    releasedate = et.SubElement(nset, "releasedate")

    name.text = s.code
    longname.text = s.name
    setType.text = s.series
    releasedate.text = s.release_date

names = []
n = 0
for c in Card.all():
    n += 1
    ncard = et.SubElement(xmlcards, "card")

    name = et.SubElement(ncard, "name")
    cset = et.SubElement(ncard, "set")
    color = et.SubElement(ncard, "color")
    mana = et.SubElement(ncard, "manacost")
Example #29
0
def text(name, card_set_text):
    card = parse_card(name, card_set_text)
    card_set = Set.find(card.set.id)

    # Create a string for the card text
    return_str = "```\n"

    # Pokemon are the most involved as they have a lot going on
    if card.supertype == "Pokémon":
        # Start with the Pokemon's name and type(s)
        return_str += "%s - %s" % (card.name, "/".join(card.types))

        # Some Pokemon have no HP (e.g. the second half of LEGEND cards),
        # so do only add it if it exists
        if card.hp is not None:
            return_str += " - HP%s\n" % (card.hp)
        else:
            return_str += "\n"

        return_str += "%s Pokemon" % card.subtypes
        if card.evolvesFrom is not None and card.evolvesFrom != "":
            return_str += " (Evolves from %s)" % card.evolvesFrom
        if len(card.subtypes) > 1:
            return_str += "%s" % card.subtypes[1]

        return_str += "\n\n"

        # Ancient Traits
        if card.ancientTrait is not None:
            return_str += "Ancient Trait: %s\n" % card.ancientTrait.name
            return_str += "%s\n" % card.ancientTrait.text
            return_str += "\n"

        # Add the ability if present
        if card.abilities is not None:
            for ability in card.abilities:
                return_str += "%s: %s\n" % (ability.type, ability.name)
                return_str += "%s\n" % ability.text
                return_str += "\n"

        # Add any attacks, including shorthand cost, text and damage
        if card.attacks is not None:
            for attack in card.attacks:
                for cost in attack.cost:
                    return_str += "%s" % short_energy[cost]

                return_str += " %s" % attack.name

                if attack.damage != '':
                    return_str += ": %s damage\n" % attack.damage
                else:
                    return_str += "\n"

                if attack.text is not None:
                    return_str += "%s\n" % attack.text

                return_str += "\n"

        # Add weakness, resistances and retreat if they exist
        if card.weaknesses is not None:
            for weakness in card.weaknesses:
                return_str += ("Weakness: %s (%s)\n" %
                               (weakness.type, weakness.value))

        if card.resistances is not None:
            for resistance in card.resistances:
                return_str += ("Resistance: %s (%s)\n" %
                               (resistance.type, resistance.value))

        if card.retreatCost is not None:
            return_str += "Retreat: %s" % len(card.retreatCost)

        # Ruleboxes
        if card.rules is not None:
            return_str += "\n\n"
            for rule in card.rules:
                return_str += "%s" % rule

    # Trainers and Energy are a lot easier
    elif card.supertype == "Trainer" or card.supertype == "Energy":
        return_str += "%s\n" % card.name
        return_str += "%s\n\n" % card.subtypes
        return_str += "%s\n" % "\n\n".join(card.rules)

    # Finally, get the set and legality info
    return_str += "\n\n%s - %s/%s" % (card_set.name, card.number,
                                      card_set.printedTotal)
    if card.legalities.standard == 'Legal':
        return_str += " \u2705 (Standard)"
    elif card.legalities.standard == 'Banned':
        return_str += " \u274C (Standard)"
    if card.legalities.expanded == 'Legal':
        return_str += " \u2705 (Expanded)"
    elif card.legalities.expanded == 'Banned':
        return_str += " \u274C (Expanded)"
    if card.legalities.unlimited == 'Legal':
        return_str += " \u2705 (Unlimited)"
    elif card.legalities.unlimited == 'Banned':
        return_str += " \u274C (Unlimited)"

    return_str += "```\n"
    return return_str