def search(self, search_term: str) -> List[SearchResult]: """ Search the pokemontcg.io API for cards with the given search term. :param search_term: The search to give to the API :returns: A list of search results given from the search """ # 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 search_term.lower().endswith(' ex'): cards.extend(Card.where(name=search_term.lower())) cards.extend( Card.where(name=search_term.lower().replace(' ex', '-ex'))) # GX cards do not have the same issue, so we can simply insert the dash # as expected elif search_term.lower().endswith(' gx'): cards.extend( Card.where(name=search_term.lower().replace(' gx', '-gx'))) # Hardcode the card 'N' to search for the specific card, not all cards # with the letter n within their name elif search_term.lower() == "n": cards = Card.where(name="\"N\"") # Otherwise, search for the given text else: cards = Card.where(name=search_term) return sorted([ PokemonTCGIOV1Provider._card_to_searchresult(card) for card in cards ], key=lambda result: result.release)
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 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(q=f'name:"{name.lower()}"')) cards.extend( Card.where(q=f'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(q=f'name:"{name.lower().replace(" gx", "-gx")}"')) # Delta card text replacement elif name.lower().endswith(" delta"): cards.extend( Card.where(q=f'name:"{name.lower().replace(" delta", " δ")}"')) # Handling "N" elif name.lower() == "n": return_str = "Matches for search 'N'\n" return_str += "N - Noble Victories 92/101 (`bw3-92`)\n" return_str += "N - Noble Victories 101/101 (`bw3-101`)\n" return_str += "N - Dark Explorers 96/108 (`bw5-96`)\n" return_str += "N - BW Black Star Promos BW100 (`bwp-BW100`)\n" return_str += "N - Fates Collide 105/124 (`xy10-105`)\n" return_str += "N - Fates Collide 105a/124 (`xy10-105a`)\n" return (return_str, 6) # Otherwise, search for the given text else: cards = Card.where(q=f'name:"{name}"', orderBy="set.releaseDate") # 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].id), 1) # Create the returned string return_str = "Matches for search '%s'\n" % name for card in cards: return_str += ("%s - %s %s/%s (`%s-%s`)\n" % (card.name, card.set.name, card.number, card.set.printedTotal, card.set.id, card.number)) return (return_str, len(cards))
def parse_card(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, setCode=card_set) 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] return card
def parse_card(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_part = card_set.split("-") for set_code, setid in sets.items(): if set_code in card_set: card_set = card_set.replace(card_part[0], setid.lower()) card = Card.find(card_set) if card is None: return "No results for card `%s`" % card_set else: # Check if a Set Abbreviation was used instead nums = set('0123456789') for set_code, setid in sets.items(): card_set = card_set.replace(set_code, setid) # Verify Set Abbreviation was replaced if any((n in nums) for n in card_set): # Search for the given card cards = Card.where(q=f'name:{name} set.id:{card_set}') 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 `[p]show %s %s-%s`" % (name, card_set, cards[0].number)) card = cards[0] else: return ("Set Abbreviation wasn't found. Double check and try again.") return card
def test_all_with_params_return_cards(self): with vcr.use_cassette('fixtures/mega_pokemon.yaml'): cards = Card.where(supertype='pokemon') \ .where(subtype='mega') \ .all() self.assertTrue(len(cards) >= 70)
def get_cards_from_sets(sets): cards = [] for set in sets: print(set.name) set_cards = Card.where(set=set.name) for card in set_cards: cards.append(card) return remove_duplicate_card_names(cards)
def showPokemonData(): #get the number typed into the entry box pokemonNumber = randint(0, 99) #use the function above to get the pokemon data pokemon = Card.where(page=1).array()[pokemonNumber] #get the data from the dictionary and add it to the labels lblNameValue.configure(text=pokemon.get('name')) lblHPValue.configure(text=pokemon.get('hp')) lblAttackValue.configure(text=pokemon.get('attacks')[0]['damage'] if pokemon.get('attacks') else '?') lblDefenceValue.configure(text=pokemon.get("resistances")[0]['type'])
def getOptions(): global options global chosenSets global probs recalc=0 while(recalc<20): cset = np.random.choice(chosenSets,1) ctype = np.random.choice([p[0] for p in probs],p=[p[1] for p in probs]) try: options = np.random.choice(Card.where(set=cset[0], supertype=ctype),NOPTIONS,replace=False) recalc+=100 except ValueError: recalc+=1 return [card.image_url_hi_res for card in options]
def getCardByName(cardName, cardSet, cardID, literal, superType): if not cardSet: card = Card.where(name=cardName).all() else: card = Card.where(name=cardName).where(set=cardSet).all() if literal: result = [] for i in card: if re.findall('^' + cardName + '$', i.name): result.append(i) card = result if superType: result = [] for i in card: if i.supertype[0] == superType[0]: result.append(i) card = result if cardID: result = [] for i in card: if re.findall(str(cardID) + '$', i.id): result.append(i) card = result return card
def getCard(): name = request.args.get('name') cards = [] try: cards = Card.where(name=name) except: return pokelista = [] for card in cards: pokelista.append({ 'name': card.name, 'imageUrl': card.image_url, 'id': card.id }) return (jsonify(pokelista), 200)
def fetch_alternate_version_of_card(card): # Subtype filter needed for cases like special darkness energy versions_of_card = Card.where(name=card.name, subtype=card.subtype) for version in versions_of_card: try: print(version.id) version_photo = getphoto(version.image_url, version.id) break except AttributeError: # Happens due to a bug in pillow 5.4.1 where some cards with EXIF data cause pillow to barf # In that case, try and find an alternate card image # This mostly occurs on certain secret rares, esp from Ultra Prism pass if (version_photo): return version_photo return get_back_photo()
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
#!/usr/bin/env python3 import requests import traceback from pokemontcgsdk import Card # from pokemontcgsdk import Set # from pokemontcgsdk import Type # from pokemontcgsdk import Supertype # from pokemontcgsdk import Subtype # requests.packages.urllib3.disable_warnings() log = open("log.txt", "w") session = requests.Session() session.verify = False try: cards = Card.where(page=5, pageSize=100) print(card) except Exception: traceback.print_exc(file=log)
def new_set(set_): new_set_ = Set.where(name=set_) cards = Card.where(set=set_) for card in cards: input_card(card)
from pokemontcgsdk import Card #Getting pokes from specific set cards = Card.where(set="FireRed & LeafGreen") #Array to handle pokes objects pokemons_list = [] #Class to get each pokemon from api class Pokemon(): def __init__(self, name, number, image_url, supertype, subtype, rarity): self.name = name self.number = number self.image_url = image_url self.supertype = supertype self.subtype = subtype self.rarity = rarity def return_by_name(self, name): if self.name == name: return self #Creating json for card in cards: poke = Pokemon(card.name, card.number, card.image_url, card.supertype, card.subtype, card.rarity) pokemons_list.append(poke)
fire_energy, grass_energy, lightning_energy, metal_energy, psychic_energy, water_energy, ) c = conn.cursor() if energy_cost_attackID: c.execute( "DELETE FROM EnergyCost WHERE cardID=? AND costType=? AND attackID=?", (card_id, energy_cost_type, energy_cost_attackID)) else: c.execute( "DELETE FROM EnergyCost WHERE cardID=? AND costType=? AND attackID IS NULL", (card_id, energy_cost_type)) c.execute("INSERT INTO EnergyCost VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", energy_index) print("Inserted EnergyCost: {} {} {} {}".format(card_id, energy_cost_type, energy_cost_attackID, energy_cost_converted)) cards = Card.where(set='generations').where(supertype='pokemon').all() conn = create_connection("ptcg.db") for card in cards: insert_card(card) conn.commit() conn.close()
def test_all_with_params_return_cards(self): with vcr.use_cassette('fixtures/mega_pokemon.yaml'): cards = Card.where(supertype='pokemon', subtype='mega') self.assertTrue(len(cards) >= 70)
def test_all_with_page_returns_cards(self): with vcr.use_cassette('fixtures/all_first_page.yaml'): cards = Card.where(page=1) self.assertEqual(100, len(cards))
def test_all_with_page_and_page_size_returns_card(self): with vcr.use_cassette('fixtures/all_first_page_one_card.yaml'): cards = Card.where(page=1, pageSize=1) self.assertEqual(1, len(cards))
def test_all_with_page_returns_cards(self): with vcr.use_cassette('fixtures/all_first_page.yaml'): cards = Card.where(page=1) self.assertEqual(250, len(cards))
def initial_cards_input_using_sets(sets): # add cards using sets db = conn.cursor() #sets = Set.all() #sets = [x.name for x in sets] for pc_set in sets: cards = Card.where(set=pc_set) for card in cards: try: pc_id = card.id name = card.name national_pokedex_number = card.national_pokedex_number if card.types: # can be none, error when trying to join types = ','.join(card.types) else: types = card.types sub_type = card.subtype super_type = card.supertype if card.hp and card.hp != 'None': hp = int(card.hp) else: hp = None if card.number: pc_number = card.number else: pc_number = None artist = card.artist rarity = card.rarity series = card.series pc_set = card.set set_code = card.set_code if card.retreat_cost: # can be none retreat_cost = ','.join(card.retreat_cost) else: retreat_cost = card.retreat_cost converted_retreat_cost = card.converted_retreat_cost if card.text: pc_text = '\n'.join(card.text) else: pc_text = card.text if card.attacks: # doesnt necessarily have to have dmg if 'damage' in card.attacks: if 'text' in card.attacks: attacks = '\n'.join([ '{}-{}-{}\n{}'.format(','.join(attack['cost']), attack['name'], attack['damage'], attack['text']) for attack in card.attacks ]) else: attacks = '\n'.join([ '{}-{}-{}'.format(','.join(attack['cost']), attack['name'], attack['damage']) for attack in card.attacks ]) else: if 'text' in card.attacks: attacks = '\n'.join([ '{}-{}\n{}'.format(','.join(attack['cost']), attack['name'], attack['text']) for attack in card.attacks ]) else: attacks = '\n'.join([ '{}-{}'.format(','.join(attack['cost']), attack['name']) for attack in card.attacks ]) else: attacks = card.attacks if card.weaknesses: weakness = ','.join([ '{} {}'.format(weak['type'], weak['value']) for weak in card.weaknesses ]) else: weakness = card.weaknesses if card.resistances: resistances = ','.join([ '{} {}'.format(resist['type'], resist['value']) for resist in card.resistances ]) else: resistances = card.resistances if card.ability: # doesnt necessarily have a type.. how about texT? if 'type' in card.ability: ability = '{} {}\n{}'.format( card.ability['type'], card.ability['name'], card.ability['text'] ) # only one ability so no need for new line at end else: ability = '{}\n{}'.format(card.ability['name'], card.ability['text']) else: ability = card.ability if card.ancient_trait: ancient_trait = '{}\n{}'.format( card.ancient_trait['name'], card.ancient_trait['text'] ) # only one trait so no need for new line at end else: ancient_trait = card.ancient_trait evolves_from = card.evolves_from image_url = card.image_url image_url_hi_res = card.image_url_hi_res db.execute( '''insert into pokemon_cards( id, name, national_pokedex_number, types, sub_type, super_type, hp, pc_number, artist, rarity, series, pc_set, set_code, retreat_cost, converted_retreat_cost, pc_text, attacks, weakness, resistances, ability, ancient_trait, evolves_from, image_url, image_url_hi_res) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''', [ pc_id, name, national_pokedex_number, types, sub_type, super_type, hp, pc_number, artist, rarity, series, pc_set, set_code, retreat_cost, converted_retreat_cost, pc_text, attacks, weakness, resistances, ability, ancient_trait, evolves_from, image_url, image_url_hi_res ]) conn.commit() # download image, check if hi res or not, time.sleep(0.5) if image_url_hi_res: response = requests.get(image_url_hi_res, stream=True) with open(r'img\{}.png'.format(pc_id), 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response elif image_url: response = requests.get(image_url, stream=True) with open(r'img\{}.png'.format(pc_id), 'wb') as out_file: shutil.copyfileobj(response.raw, out_file) del response else: print('error - {}'.format(pc_id)) except Exception as e: print(e) print('ERROR - {}'.format(card.id)) file1 = open('error.txt', 'a') file1.write('{}\n'.format(card.id)) file1.close() except: print('error - {}'.format(card.id))
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