Example #1
0
def getCardByName(cardName, cardSet=None, literal=False, superType=None):
    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 = []
        Type = ''
        for i in card:
            Type = i.type
            if re.findall('^Legendary', Type):
                Type = Type[10:]
            if re.findall('^Basic', Type):
                Type = Type[6:]
            if re.findall('^Tribal', Type):
                Type = Type[7:]
            if Type[0] == superType[0]:
                result.append(i)
        card = result
    return card
Example #2
0
    def db_insert_data_card(self, cards_json):
        """Insert download from mtgjson"""
        c_rows = []
        s_rows = []
        for data in cards_json.values():
            cards = []
            for raw in data["cards"]:
                c = Card(raw)
                c.image_url = util.CARD_IMAGE_URL.format(c.multiverse_id)
                c.set = data["code"]
                c.set_name = data["name"]
                cards.append(c)

            for c in cards:
                c_rows.append(self.card_to_table_mapping(c))
            set = Set(data)
            s_rows.append(self.set_to_table_mapping(set))

        # Use separate connection to commit changes immediately
        con = sqlite3.connect(self.db_file)
        try:
            with con:
                sql_string = "INSERT INTO `cards` VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?," \
                             "?,?,?,?,?,?,?,?,?,?,?)"
                con.executemany(sql_string, c_rows)
                sql_string = "INSERT INTO `sets` VALUES (?,?,?,?,?,?,?,?,?,?,?)"
                con.executemany(sql_string, s_rows)

        except sqlite3.OperationalError as err:
            util.log("Database Error", util.LogLevel.Error)
            util.log(str(err), util.LogLevel.Error)
        except sqlite3.IntegrityError as err:
            util.log("Database Error", util.LogLevel.Error)
            util.log(str(err), util.LogLevel.Error)
Example #3
0
async def on_message(message):
        # we do not want the bot to reply to itself
        if message.author == client.user:
                return
        if message.content.startswith('!magic'):
                msg_com = message.content.split('-')
                msg_com.pop(0)
                for msg in msg_com:
                        if '-help' in msg.lower():
                                print('help')
                                await client.send_message(message.channel,'Magic Card Bot \n --help : This message displaying \n -s_reg : Followed by a string will search that string \n -m_uid : Searchs cards by multivesrse id \n -s_adv : Not currently finished')
                        elif 'm_uid' in  msg.lower():
                                print(msg[6:])
                                card_m = Card.find(msg[6:])
                                print(http_address(card_m.set_name,card_m.name))
                                await client.send_message(message.channel,http_address(card_m.set_name,card_m.name))
                                print(http_image(card_m.multiverse_id))
                                await client.send_message(message.channel,http_image(card_m.multiverse_id))
                        elif 's_reg' in msg.lower():
                                print(http_parse(msg[6:]))
                                card_s = Card.where(name=msg[6:]).all()
                                for s_card in card_s:
                                        print(http_address(s_card.set_name,s_card.name))
                                        await client.send_message(message.channel,http_address(s_card.set_name,s_card.name))
                                        print(http_image(s_card.multiverse_id))
                                        await client.send_message(message.channel,http_image(s_card.multiverse_id))
                        elif 's_adv' in msg.lower():
                                await client.send_message(message.channel,'This command is disabled')
                        else:
                                print('RIP something went wrong')
                                await client.send_message(message.channel, 'RIP something went wrong')
Example #4
0
def scanImage(chat_id, file_path):
    im = Image.open(
        file_path)  #NOTE: WITH 500X500 IMG NO PROBLEM TO READ THE TEXT
    text = ''
    enchanceIndex = 1  #per fare una prova ho visto che da 12 in poi legge bene
    w, h = im.size
    im.crop((0, 0, w, h - 250)).save("temp.jpg")
    im2 = Image.open("temp.jpg")  #.convert('L')
    #im2.show()
    ReadedText = []
    enhancer = ImageEnhance.Contrast(im2)
    im2 = im2.filter(ImageFilter.MinFilter(3))
    d = enchant.DictWithPWL("en_US", "MagicCardName.txt")
    while enchanceIndex <= 15:  #Testing
        im2 = enhancer.enhance(enchanceIndex)
        im2 = im2.convert('1')
        #im2.show()
        text = (pytesseract.image_to_string(im2, lang='ita'))
        #print (text)
        print('\nValore contrasto= ', enchanceIndex)
        enchanceIndex += 1
        if text != '':
            #ReadedText.append(text)
            print('\n---------Name of Cards---------\n')
            print('Testo rilevato ', text)
            print('Testi suggeriti ', d.suggest(text))
            suggerimenti = d.suggest(text)
            if (len(suggerimenti) > 0):
                print('Ricerca...')
                for s in suggerimenti:
                    if s == text:
                        cardToSearch = s
                    else:
                        cardToSearch = suggerimenti[
                            0]  #quella con maggior probabilità di essere esatta

                print('Cerca -> ', cardToSearch)
                cards = Card.where(name=cardToSearch).all()
                if (len(cards) > 0):
                    #for c in cards:
                    print(cards[0].name, ' ', cards[0].cmc, cards[0].colors)
                    send_message(
                        str(cards[0].name) + " " + str(cards[0].cmc) + " " +
                        str(cards[0].colors), chat_id)
                    break
                else:
                    cardsITA = Card.where(language="Italian").where(
                        name=cardToSearch).all()
                    if (len(cardsITA) > 0):
                        #for c in cardsITA:
                        print(cardsITA[0].name, ' ', ' costo= ',
                              cardsITA[0].cmc, ' colore= ', cardsITA[0].colors)
                        send_message(
                            str(cardsITA[0].name) + " " +
                            str(cardsITA[0].cmc) + " " +
                            str(cardsITA[0].colors), chat_id)
                        break
    send_message("Mi dispiace ma non sono riuscito a decifrare la foto",
                 chat_id)
def Index():
  # Get all cards
  cards = Card.all()
  
  # Filter Cards
  # You can chain 'where' clauses together. The key of the hash
  # should be the URL parameter you are trying to filter on
  cards = Card.where(supertypes='legendary') \
              .where(types='creature') \
              .where(colors='red,white') \
              .all()
 def card_get_image(self, card, set, all_sets):
     iterator = Card.where(name=card.name, set=set).iter()
     for i in iterator:
         if i.name == card.name and i.image_url:
             return i
     all_sets.reverse()
     for cur_printing in all_sets[1:]:
         iterator = Card.where(card=card.name, set=cur_printing).iter()
         for i in iterator:
             if i.name == card.name and i.image_url:
                 return i
Example #7
0
def get_cards():

    try:
        cards = Card.where(supertypes='legendary').where(
            subtypes='vampire').all()
        #return cards

        res = []
        index = 0
        insert_card({"name": "test"})
        for card in cards:

            js = MyEncoder().encode(card)

            index += 1
            colors = ', '.join(card.colors)
            types = ', '.join(card.types)
            subtypes = ', '.join(card.subtypes)

            res.append(
                "%3d. Name: %-30s csc: %2d =>%15s colors: %-20s [p/t]: %2s/%-2s rarity: %13s types: %10s subTypes: %20s"
                % (index, card.name, card.cmc, card.mana_cost, colors,
                   card.power, card.toughness, card.rarity, types, subtypes))

        return res

    except Exception as ex:
        print('Exception occured {0}'.format(ex))
Example #8
0
def get_card_oracle_text_by_name(name):
    if name in cache:
        return cache[name].text
    cards = Card.where(name=f'"{name}"').all()
    c = cards[0]
    cache[name] = c
    return c.text
Example #9
0
 def sync_all_cards():
     start_time = time.time()
     count = 0
     cards = api_cards.all()
     for card in cards:
         set = Set.objects.get(abbreviation=card.set)
         body = {
             'name': card.name,
             'mana_cost': card.mana_cost,
             'converted_mana_cost': card.cmc,
             'abilities': card.text,
             'power': card.power,
             'toughness': card.toughness,
             'loyalty': None if card.loyalty == 0 else card.loyalty,
             'rarity': card.rarity,
             'number': card.number,
             'img_url': card.image_url,
             'type': card.type,
             'flavor_text': card.flavor,
             'set': set
         }
         Card.objects.update_or_create(defaults=body,
                                       set_id=set.id,
                                       number=card.number)
         count += 1
     end_time = time.time()
     print('{0} seconds to sync {1} cards.'.format(end_time - start_time,
                                                   count))
Example #10
0
def search():
    sets = 'KLD,AER,AKH,HOU,XLN,RIX,DOM'

    searchTerm = request.form['search']
    if not os.path.isdir('cache'):
        os.makedirs('cache')

    cacheFile = 'cache/%s.json' % searchTerm
    if not os.path.isfile(cacheFile):
        cards = Card.where(set=sets).where(name=searchTerm).all()
        with open(cacheFile, 'w') as f:
            data = '['
            for card in cards:
                data += json.dumps(card.__dict__)
                data += ','
            data = data[:-1] + ']'
            f.write(data)

    cards = []
    with open(cacheFile, 'r') as f:
        cards = json.loads(f.read())

    names = []
    for card in cards:
        names.append({'name': card['name'], 'image': card['image_url']})

    return jsonify(names)
def retrieveRelatedCardInfo(cardName):
    # for now we will just print the info to the console, but this really should be more of a getter function (with a return statement as opposed to a print statement)
    cards = Card.where(name=cardName).all()
    print('\n----------RESULTS----------\n')
    i=0
    uniqueCardResults = []
    for card in cards:
        if card.name in uniqueCardResults:
            continue
        else:
            uniqueCardResults.append(card.name)
            i=i+1
            print('\n=====Result #' + str(i) + '=====\n')
            print('Card Name: ' + card.name)
            if card.mana_cost != None:
                print('Card Mana Cost: ' + card.mana_cost)
            else:
                print('Card Mana Cost: N/A')
            if card.cmc != None:
                print('Card CMC: ' + str(card.cmc)) # Type of card.cmc is float
            else:
                print('Card CMC: N/A')
            print('Card Color Identity: ', end='') # Type of card.color_identity is list
            for color in card.color_identity:
                print(color)
            print('Card Type: ' + card.type)
            if 'Creature' in card.type:
                print('Card Power/Toughness: ' + card.power + '/' + card.toughness)
            print('Card Rarity: ' + card.rarity)
            print('Card Rules Text: ' + card.text)
            print('Card Unique ID: ' + card.id)
Example #12
0
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

    if message.content.startswith('$openthedoor'):
        await message.channel.send("I'm sorry %s, I cannot do that." %
                                   message.author)

    if message.content.startswith('$whisper'):
        await message.author.send("Hello %s." % message.author)

    if message.content.startswith('$goodnight'):
        await message.channel.send("Good night, %s.  Rest in peace." %
                                   message.author)

    if message.content.startswith('$card'):
        card_name = message.content[6:]
        try:
            # Add all found cards to a list.
            card_list = Card.where(name=card_name).array()

            # Get the last row in the array, which (theoretically) is the most recent printing.
            card = card_list[card_list.__len__() - 1]

            # Send picture of card.
            await message.channel.send(card['imageUrl'])

            # TODO  Send URL of page instead of image
        except IndexError:
            await message.channel.send(
                "Unable to find card \"{0}\".".format(card_name))
Example #13
0
def run(*args):
    """Add a card to the database from the mtgsdk."""
    if args:
        # import pdb; pdb.set_trace()
        set_str = args[0]
        cur_set = ''
        try:
            cur_set = sourceSet.find(set_str)
        except:
            print('Set id was invalid, please check id')
            return
        set_in_db = False
        all_sets = Set.objects.all()
        selected_set = ''
        for one_set in all_sets:
            if cur_set.name == one_set.name:
                set_in_db = True
                selected_set = one_set
        if set_in_db:
            cards_in_set = selected_set.card_set.all()
            cards_in_set.delete()
            gen_set(set_str, selected_set)
        else:
            new_set = Set(name=cur_set.name,
                          set_id=cur_set.code,
                          slug=slugify(cur_set.code))
            new_set.save()
            gen_set(set_str, new_set)

    else:
        all_cards = Card.objects.all()
        all_cards.delete()
        sets = Set.objects.all()
        if not sets:
            return
        cur_set = sets[0]
        rivals = SourceCard.where(set='rix')
        rivals_cards = rivals.all()
        for card in rivals_cards:
            new_card = Card.objects.create(name=card.name,
                                           colors=card.colors,
                                           cmc=card.cmc,
                                           image=card.image_url,
                                           mana_cost=card.mana_cost,
                                           rarity=card.rarity,
                                           card_type=card.types,
                                           card_subtypes=card.subtypes,
                                           card_text=card.text,
                                           number=card.number
                                           )
            if card.power:
                new_card.power = card.power
            if card.toughness:
                new_card.toughness = card.toughness
            if card.loyalty:
                new_card.loyalty = card.loyalty
            new_card.save()
            cur_set.card_set.add(new_card)
            if card.rarity == 'Common':
                pass
Example #14
0
    def test_find_returns_card(self):
        with vcr.use_cassette('fixtures/choice_of_damnations.yaml'):
            card = Card.find(88803)

            self.assertEqual('Choice of Damnations', card.name)
            self.assertEqual('{5}{B}', card.mana_cost)
            self.assertEqual(6, card.cmc)
            self.assertEqual('Sorcery — Arcane', card.type)
            self.assertTrue('Black' in card.colors)
            self.assertTrue('Sorcery' in card.types)
            self.assertTrue('Arcane' in card.subtypes)
            self.assertEqual('Rare', card.rarity)
            self.assertEqual('SOK', card.set)
            self.assertEqual("Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.text)
            self.assertEqual("\"Life is a series of choices between bad and worse.\"\n—Toshiro Umezawa", card.flavor)
            self.assertEqual('Tim Hildebrandt', card.artist)
            self.assertEqual('62', card.number)
            self.assertEqual(88803, card.multiverse_id)
            self.assertEqual('http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=88803&type=card', card.image_url)
            self.assertTrue(len(card.rulings) > 0)
            self.assertTrue({"name":"Scelta della Dannazione","language":"Italian","multiverseid":105393} in card.foreign_names)
            self.assertTrue('SOK' in card.printings)
            self.assertEqual("Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.original_text)
            self.assertEqual('Sorcery — Arcane', card.original_type)            
            self.assertTrue({"format":"Commander","legality":"Legal"} in card.legalities)
            self.assertEqual('1c4aab072d52d283e902f2302afa255b39e0794b', card.id)
Example #15
0
    def exchangeRareForToken(self, playerId, cardId):
        card = False
        try:
            card = Card.find(cardId)
        except:
            pass
        if not card or (card.rarity != 'Rare'
                        and card.rarity != 'Mythic Rare'):
            return False

        playerInfo = self.getPlayerInfo(playerId)
        if not playerInfo:
            return False

        cardTokenValue = 2 if card and card.rarity == 'Mythic Rare' else 1
        playerInfo.rareTokens += cardTokenValue

        rare = next((r for r in self.rarePool if r.id == cardId), False)
        if rare:
            rare.count += 1
        else:
            self.rarePool += [self.RarePoolCard(cardId)]

        self.db.save()
        return True
Example #16
0
 def downloadCards(self):
     #Downloading the cards from each set based in the sets list
     with open('dataSet/allSets.csv', 'r', encoding='utf-8') as setsFile:
         reader = csv.DictReader(setsFile)
         totalRows = sum(1 for row in reader)
         setsFile.seek(0)
         downloadedRows = 0
         for row in reader:
             cards = Card.where(set= row['code']).all()    
             filename = re.sub(r'[\\/:"*?<>|]+', '', row['name'])
             with open('dataSet/sets/'+filename+ '.csv', 'w', encoding='utf-8') as exSetFile:
                 writerCard = csv.writer(exSetFile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
                 writerCard.writerow(['name','multiverse_id','layout','mana_cost','cmc','colors',
                                     'color_identity','type','supertypes','subtypes','rarity','text','flavor',
                                     'artist','number','power','toughness','loyalty','variations','watermark','border',
                                     'timeshifted','hand','life','reserved','release_date','starter','rulings','foreign_names',
                                     'printings','original_text','original_type','legalities','source','image_url',
                                     'set','set_name'])
                 for card in cards:
                     writerCard.writerow([card.name,card.multiverse_id,card.layout,card.mana_cost,card.cmc,card.colors,card.color_identity,
                         card.type,card.supertypes,card.subtypes,card.rarity,card.text,card.flavor,
                         card.artist,card.number,card.power,card.toughness,card.loyalty,card.variations,card.watermark,card.border,
                         card.timeshifted,card.hand,card.life,card.release_date,card.starter,card.rulings,card.foreign_names,
                         card.printings,card.original_text,card.original_type,card.legalities,card.source,card.image_url,
                         card.set,card.set_name])
             
             downloadedRows = downloadedRows + 1
             print('Downloaded '+ str(downloadedRows) + ' from ' + str(totalRows) + ' total sets')
Example #17
0
 def test_all_with_params_return_cards(self):
     with vcr.use_cassette('fixtures/legendary_elf_warriors.yaml'):
         cards = Card.where(supertypes='legendary') \
                     .where(subtypes='elf,warrior') \
                     .all()
                     
         self.assertEqual(13, len(cards))
Example #18
0
    def test_all_with_params_return_cards(self):
        with vcr.use_cassette('fixtures/legendary_elf_warriors.yaml'):
            cards = Card.where(supertypes='legendary') \
                        .where(subtypes='elf,warrior') \
                        .all()

            self.assertTrue(len(cards) >= 13)
def render_page_template(request):
    number = 8675309
    cards = Card.where(set="dom").all()
    return render_template("landing/landing.html",
                           name=request.args.get("name"),
                           number=number,
                           cards=cards)
Example #20
0
    def test_find_returns_card(self):
        with vcr.use_cassette('fixtures/choice_of_damnations.yaml'):
            card = Card.find(88803)

            self.assertEqual('Choice of Damnations', card.name)
            self.assertEqual('{5}{B}', card.mana_cost)
            self.assertEqual(6, card.cmc)
            self.assertEqual('Sorcery — Arcane', card.type)
            self.assertTrue('Black' in card.colors)
            self.assertEqual(['B'], card.color_identity)
            self.assertTrue('Sorcery' in card.types)
            self.assertTrue('Arcane' in card.subtypes)
            self.assertEqual('Rare', card.rarity)
            self.assertEqual('SOK', card.set)
            self.assertEqual('Saviors of Kamigawa', card.set_name)
            self.assertEqual("Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.text)
            self.assertEqual("\"Life is a series of choices between bad and worse.\"\n—Toshiro Umezawa", card.flavor)
            self.assertEqual('Tim Hildebrandt', card.artist)
            self.assertEqual('62', card.number)
            self.assertEqual(88803, card.multiverse_id)
            self.assertEqual('http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=88803&type=card', card.image_url)
            self.assertTrue(len(card.rulings) > 0)
            self.assertTrue({"name":"Scelta della Dannazione","language":"Italian","multiverseid":105393, "imageUrl":"http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=105393&type=card"} in card.foreign_names)
            self.assertTrue('SOK' in card.printings)
            self.assertEqual("Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.original_text)
            self.assertEqual('Sorcery — Arcane', card.original_type)            
            self.assertTrue({"format":"Commander","legality":"Legal"} in card.legalities)
            self.assertEqual('1c4aab072d52d283e902f2302afa255b39e0794b', card.id)
Example #21
0
    def post(self, request):
        form = LoginForm()
        submitted_form = self.form_class(request.POST)

        if submitted_form.is_valid():
            try:
                username = submitted_form.cleaned_data["username"]
                password = submitted_form.cleaned_data["password"]
                user = authenticate(username=username, password=password)
                if user is not None:
                    login(request, user)
                    """
                    Querying MTG DB for random 200 cards vs entire collection of 37000.
                    Could query asynchonously to save time or save one through caching and then move to static files during production???
                    """
                    cache.set(
                        "small_card_set",
                        Card.where(page=1).where(pageSize=20,
                                                 random=True).all(), 200)
                    # Setting total card type in cache
                    cache.set("card_type_total", Type.all(), 200)
                    # Setting total card substype in cache
                    cache.set("card_subtype_total", Subtype.all(), 200)
                    return redirect("/home")
                else:
                    messages.warning(
                        request,
                        'Username or password does not match our records')
                    return redirect("/login")
            except:
                messages.warning(
                    request, 'Username or password does not match our records')
                return render(request, self.template_name, {"form": form})
Example #22
0
def mtg(searchstring, unsafe=False):
    if (re.search(r":", searchstring)):
        return advancedsearch(searchstring)
    else:
        cards = Card.where(name=searchstring, page=0, pageSize=1).all()
        if cards:
            return cards[0].image_url
        else:
            return
Example #23
0
def index(request):
    # if request.method == "POST":
    search_term = request.GET.get('keywords')
    search_filter = request.GET.get('searchFilter')

    if search_filter == 'Type':
        cards = Card.where(subtypes=search_term).all()
    elif search_filter == 'Set':
        cards = Card.where(set_name=search_term).all()
    else:
        cards = Card.where(name=search_term).all()

    card_query = cards
    form = CardDisplayForm()
    context = {'cards': card_query, 'form': form }
    if search_term is None:
        context = {}
    return render(request, 'index.html', context)
    async def get_card(self, args, mobj):
        author = mobj.author
        try:
            cards = Card.where(name=" ".join(args)).iter()
        except BaseException:
            await self.bot.error(mobj.channel,
                                 "Something broke when requesting cards.")
            return None

        cards_ = dict()
        entered = []
        a = 0
        for cur in cards:
            if cur.name not in entered:
                cards_[a] = cur
                a += 1
                entered.append(cur.name)
                if len(entered) >= 50:
                    break
        if len(cards_) == 0:
            await self.bot.error(mobj.channel, "No cards found.")
            return None
        if len(cards_) > 1:
            order = sorted(cards_.values(),
                           key=lambda x: fuzz.ratio(" ".join(args), x.name),
                           reverse=True)[:15]
            cards_ = OrderedDict([(i, v) for i, v in enumerate(order)])

            message = "```What card would you like:\n"
            for anime in cards_.items():

                message += "[{}] {}\n".format(str(anime[0] + 1), anime[1].name)

            message += "\nUse the number to the side of the name as a key to select it!```"

            await self.bot.message(mobj.channel, message)

            msg = await self.bot.client.wait_for_message(timeout=10.0,
                                                         author=author)

            if not msg:
                await self.bot.error(
                    mobj.channel, "Operation has timed out, please try again.")
                return None
            try:
                key = int(msg.content) - 1
            except:
                await self.bot.error(mobj.channel, "Invalid Key")
                return None
        else:
            key = 0

        try:
            return cards_[key]
        except (ValueError, KeyError):
            await self.bot.error(mobj.channel, "Invalid key.")
            return None
Example #25
0
 def get(self, request):
     test_card = Card.find(386616)
     # Additional context use to populate spans set in cache to avoid redundant queries
     context = {
         "card": test_card,
         "card_type_total": len(cache.get("card_type_total")),
         "card_subtype_total": len(cache.get("card_subtype_total"))
     }
     return render(request, self.template_name, context)
Example #26
0
def _handle_card(card_data, output_path):
    """Look for card in database and download all card images found."""
    cards_found = Card.where(name=card_data['name'],
                             artist=card_data['artist']).all()
    if not cards_found:
        warnings.warn("No cards found for: " + card_data)

    for card in cards_found:
        _download_card_image(card, output_path)
Example #27
0
def get_card_image_url_by_name(name):
    if name in cache:
        return cache[name].image_url
    cards = Card.where(name=f'"{name}"').all()
    for c in cards:
        if c.image_url:
            cache[name] = c

            return c.image_url
Example #28
0
def card_list():
    """
    FOR TESTING PURPOSES
    cards = Card.where(page=1) \
                .where(pageSize=5) \
                .all()
    """
    # Returns a list of cards from the set named "Khans of Tarkir"
    return Card.where(setName='Khans of Tarkir') \
                .all()
Example #29
0
 def update(self, filename='cardnames.txt'):
     """This will take a long time like 20+ mins"""
     cards = Card.all()
     # get a set of all the  card names lower case
     cs = {card.name.lower() for card in cards}
     self.card_names = cs  # save to current instance
     with open(filename, 'w') as fi:
         for a_card_name in cs:
             fi.write("%s\n" % a_card_name)
     pickle.dump(cards, open("cards.p", "wb"))  # dump all the cards
Example #30
0
 def __init__(self, set):
     if set == 'all':
         self.AllCards = Card.where(language='English').all()
     else:
         self.AllCards = Card.where(language='English', set=set).all()
     self.cards = {
         card.multiverse_id: {
             'name': card.name,
             'multiverse_id': card.multiverse_id,
             'text': card.text,
             'power': card.power,
             'toughness': card.toughness,
             'color_identity': card.color_identity,
             'type': card.type,
             'cmc': card.cmc,
             'imageurl': card.image_url
         }
         for card in self.AllCards
     }
Example #31
0
def download_cards_in_set(s):
    cards = Card.where(set=s).all()
    print("Set: {0}, #={1}".format(s, len(cards)))
    for card in cards:
        if card.name in ['Plains', 'Island', 'Swamp', 'Mountain', 'Forest']:
            continue  #기본대지는 다운로드하지 않음
        print(card.name)
        url = get_kor_url(card)
        multiverseid = get_jap_id(card)
        download_image(url, multiverseid)
Example #32
0
def do_mtg_search(app, responseURL, searchTerm):
    with app.app_context():
        with app.test_request_context():
            retTotal = ""
            for term in searchTerm.split(","):
                term = term.strip()
                ret = term + " not found."
                found = False
                query = Card.where(pageSize=1).where(page=1)
                query.params['contains'] = 'multiverseid,imageUrl'
                query.params['orderBy'] = 'multiverseid desc'

                img = ""

                for c in Card.where(pageSize=10).where(page=1).where(
                        name="\"" + term + "\"").all():
                    if c.image_url != None:
                        img = c.image_url
                        if '//' in c.name:
                            img = img + "&options=rotate90"
                        ret = "<" + img + "|" + c.name + ">"
                        found = True
                        break

                if found is False:
                    for c in Card.where(pageSize=10).where(page=1).where(
                            name=term).all():
                        if c.image_url != None:
                            img = c.image_url
                            if '//' in c.name:
                                img = img + "&options=rotate90"
                            ret = "<" + img + "|" + c.name + ">"
                            break

                retTotal = retTotal + ret + " "

            requests.post(responseURL,
                          headers={"Content-Type": "application/json"},
                          data=json.dumps({
                              "response_type": "in_channel",
                              "text": retTotal
                          }))
Example #33
0
def main():

    cards = Card.where(set="AVR").all()
    card_j = read_json()

    for x in card_j:
        name = card_j[x]["name"]
        card_j[x]["multiverseid"] = get_multiverseid(name, cards)
        card_j[x]["jp_multiverseid"] = get_multiverseid_jp(name, cards)

    save_data(card_j)
Example #34
0
    def update(self):
        if not os.path.isfile("mtg.db"):
            raise OperationalError(
                "mtg  database file does not exist, run buildDatabase.exe to recreate the database"
            )

        print("Comparing online database to local database...")

        self.numberOfCards = self.getLastId()
        self.numberOfSets = self.readSetCounter()
        onlineSets = self.readSetsFromOnline()
        localSets = self.readSetsFromFile()
        sets = self.compareSetLists(onlineSets, localSets)
        connection = self.createConnection()
        memory = connection.cursor()
        cards = []

        if len(sets) > 0:
            print("Missing sets:")
            for s in sets:
                print(s[1])
            print()
        else:
            print("Database is already up to date")
            input("Press enter to continue:")
            sys.exit()

        for i, set in enumerate(sets):
            try:
                print("searching for", set[1])
                cards = Card.where(set=set[0]).all()
                self.insertSet(set, memory)
            except OperationalError:
                raise OperationalError("Error accessing database")

            print("gathered cards for ", set[1], "set")

            for card in cards:
                cardProperties = self.getCardProperties(
                    card, self.numberOfCards, set[0])
                self.insertCard(cardProperties, memory)
                self.numberOfCards += 1  # increment the id used for each card

            connection.commit()
            self.numberOfSets += 1  # increment the self.numberOfSets used to keep track of which set of the total we are on
            print(set[1], "complete,", (i + 1), "of", len(sets))
            print(self.numberOfCards)
            self.setNewId(self.numberOfCards)
            self.writeSetCounter(self.numberOfSets)

            # this is used to space out the requests since it will throw an error if the program grabs all the card at once
            if self.numberOfSets % 10 == 0:
                time.sleep(30)
Example #35
0
def ask_card(cardname):
    cards = Card.where(name=cardname).all()
    l = []
    n = []
    i = 0
    for card in cards:
        if i == 20:
            break
        if card.name not in n:
            msg = "**" + card.name + "**" + " "
            if card.mana_cost is not None:
                msg += card.mana_cost
                # if card.set_name=='Unhinged' or card.set_name=='Unglued' :
                msg += " - *"
                last_set = card.printings[-1]
                for set in card.printings:
                    msg += set
                    if set == last_set:
                        msg += "*"
                    else:
                        msg += ", "
            msg += "\n"
            if card.type is not None:
                msg += card.type
            if "Creature" in card.types:
                msg += " " + card.power + "/" + card.toughness
            elif "Planeswalker" in card.types:
                msg += ". Starting Loyalty " + str(card.loyalty)
            if card.text is not None:
                msg += "\n" + card.text
            msg += "\n"
            if cardname.lower() == card.name.lower():
                l = [msg]
                break
            else:
                l.append(msg)
                i += 1
                n.append(card.name)
    return l
  # You can chain 'where' clauses together. The key of the hash
  # should be the URL parameter you are trying to filter on
  cards = Card.where(supertypes='legendary') \
              .where(types='creature') \
              .where(colors='red,white') \
              .all()
=======
def filedownload(cmd):
  try:
    file = File.select().where(File.id == cmd).get()
    filepath = ('static/files/uploads/'+ str(file.filename)).replace(" ", "")
    return send_file(filepath, as_attachment=True, attachment_filename = file.fulltitle)
>>>>>>> parent of 9e7bcc7... Mering with master
  
  # Get cards on a specific page / pageSize
  cards = Card.where(page=50).where(pageSize=50).all()
  return(str(cards))



>>>>>>> 9c35178847f7ffcfba3bec48c69e42fc82e14e93









    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).where(pageSize=1).all()

            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).all()

            self.assertEqual(100, len(cards))
    def test_all_with_params_return_cards(self):
        with vcr.use_cassette("fixtures/legendary_elf_warriors.yaml"):
            cards = Card.where(supertypes="legendary").where(subtypes="elf,warrior").all()

            self.assertTrue(len(cards) >= 13)