Help

Script problem

Solved
Jump to Solution
1608 4
cancel
Showing results for 
Search instead for 
Did you mean: 
jblackford22
4 - Data Explorer
4 - Data Explorer

jblackford22_0-1676585625527.gif

This is a code that uses the Scryfall API to search for Magic the Gathering cards based on user input. The first line prompts the user to enter the name of the card they want to search for. The second line sends a request to the Scryfall API with the user's query, and the third line converts the response to JSON format.

The code then checks if the API returned any search results. If there are no results, the code outputs "No results found." If there is only one result, the code creates a new record in a table called "Cards" in a service like Airtable with the card's information, and outputs a confirmation message. If there are multiple results, the code prompts the user to select the correct card from a list, and then creates a new record for that card in the "Cards" table.

The issue arises when after the list of potential cards is loaded as search results, if it cant parse the card name it gives a bunch of options, no matter what option you choose, it wont actually add the choice as a record. What could I do to modify it to add the card as a record?

 

 

let userQuery = await input.textAsync('Enter the name of the Magic the Gathering card you want to search for:');
let scryfallResponse = await fetch(`https://api.scryfall.com/cards/search?q=${encodeURIComponent(userQuery)}`);
let cardList = await scryfallResponse.json();

if (cardList.data.length === 0) {
    output.text('No results found.');
} else if (cardList.data.length === 1) {
    let cardData = cardList.data[0];
    let newCard = await base.getTable('Cards').createRecordAsync({
        'Card Name': cardData.name,
        'Mana Cost': cardData.mana_cost,
        'Card Type': cardData.type_line,
        'Power': cardData.power,
        'Toughness': cardData.toughness,
        'Oracle Text': cardData.oracle_text,
        'Card Image': cardData.image_uris.normal,
    });
    // @ts-ignore
    output.text(`The card "${newCard.getCellValueAsString('Card name')}" has been added to the "Cards" table.`);
} else {
    let cardNames = cardList.data.map(card => card.name);
    let selectedIndex = await input.buttonsAsync('Select the correct card:', cardNames);
    console.log(`selectedIndex = ${selectedIndex}`);
    if (selectedIndex !== -1) {
        console.log(`cardNames[selectedIndex] = ${cardNames[selectedIndex]}`);
        let selectedCard = cardList.data.find(card => card.name === cardNames[selectedIndex]);
        console.log(`selectedCard = ${JSON.stringify(selectedCard)}`);
        if (selectedCard) {
            let newCard = await base.getTable('Cards').createRecordAsync({
                'Card Name': selectedCard.name,
                'Mana Cost': selectedCard.mana_cost,
                'Card Type': selectedCard.type_line,
                'Power': selectedCard.power,
                'Toughness': selectedCard.toughness,
                'Oracle Text': selectedCard.oracle_text,
                'Card Image': selectedCard.image_uris.normal,
            });
            output.text(`The card "${newCard.getCellValueAsString('Card name')}" has been added to the "Cards" table.`);
        } else {
            output.text('No card was selected.');
        }
    } else {
        output.text('No card was selected.');
    }
}

 

 

1 Solution

Accepted Solutions
Ben_Young1
11 - Venus
11 - Venus

Hey @jblackford22

This was incredibly fun to troubleshoot.
Here's my edited version of your script:

 

const cardTable = base.getTable("tblKoUhbrXuRBUP3C");
const userQuery = await input.textAsync('Enter the name of the Magic the Gathering card you want to search for:');
const cardList = await fetch(`https://api.scryfall.com/cards/search?q=${encodeURIComponent(userQuery)}`)
    .then(response => response.json());

const createCardRecord = async cardObject => {
    await cardTable.createRecordAsync({
        'fld9eHRoqJrPmOmIS': cardObject.name,
        'fldLxyhp4550H9fCX': cardObject.mana_cost,
        'flduAN2ny19YOlXKr': cardObject.type_line,
        'flduFbhREOy6eEkMK': cardObject.power,
        'fldgIP5tVrDxwNYFH': cardObject.toughness,
        'fldhxyKLI5M6uOJ2I': cardObject.oracle_text        
    })
        .then(() => output.text(`The card "${cardObject.name}" has been added to the "Cards" table.`));
};

if (cardList.data.length === 0) {
    output.text('No results found.');
} else if (cardList.data.length === 1) {
    const cardData = cardList.data[0];
    await createCardRecord(cardData);
} else {
    let cardNames = cardList.data.map(card => ({
        label: card.name,
        value: card.id,
        variant: "primary"
    }));

    let userChoiceCard = await input.buttonsAsync('Select the correct card:', cardNames);

    if (userChoiceCard) {
        let selectedCard = cardList.data.find(card => card.id === userChoiceCard);
        if (selectedCard) {
            await createCardRecord(selectedCard);
        } else {
            output.text('No card was selected.');
        }
    } else {
        output.text('No card was selected.');
    }
}

 

Here's the same workflow you went through in your video:

Ben_Young1_0-1676592199564.png

Ben_Young1_1-1676592418722.png

You'll definitely need to swap out the field ids and table id from my script, but the structure remains the same.
I could definitely see this script getting some additional depth if you were to utilize the unique card id to facilitate duplicate comparisons and decision trees, but I digress. 

Lemme know if you're curious about anything or if something ain't working.
I definitely could've missed something.

See Solution in Thread

4 Replies 4
Ben_Young1
11 - Venus
11 - Venus

Hey @jblackford22

This was incredibly fun to troubleshoot.
Here's my edited version of your script:

 

const cardTable = base.getTable("tblKoUhbrXuRBUP3C");
const userQuery = await input.textAsync('Enter the name of the Magic the Gathering card you want to search for:');
const cardList = await fetch(`https://api.scryfall.com/cards/search?q=${encodeURIComponent(userQuery)}`)
    .then(response => response.json());

const createCardRecord = async cardObject => {
    await cardTable.createRecordAsync({
        'fld9eHRoqJrPmOmIS': cardObject.name,
        'fldLxyhp4550H9fCX': cardObject.mana_cost,
        'flduAN2ny19YOlXKr': cardObject.type_line,
        'flduFbhREOy6eEkMK': cardObject.power,
        'fldgIP5tVrDxwNYFH': cardObject.toughness,
        'fldhxyKLI5M6uOJ2I': cardObject.oracle_text        
    })
        .then(() => output.text(`The card "${cardObject.name}" has been added to the "Cards" table.`));
};

if (cardList.data.length === 0) {
    output.text('No results found.');
} else if (cardList.data.length === 1) {
    const cardData = cardList.data[0];
    await createCardRecord(cardData);
} else {
    let cardNames = cardList.data.map(card => ({
        label: card.name,
        value: card.id,
        variant: "primary"
    }));

    let userChoiceCard = await input.buttonsAsync('Select the correct card:', cardNames);

    if (userChoiceCard) {
        let selectedCard = cardList.data.find(card => card.id === userChoiceCard);
        if (selectedCard) {
            await createCardRecord(selectedCard);
        } else {
            output.text('No card was selected.');
        }
    } else {
        output.text('No card was selected.');
    }
}

 

Here's the same workflow you went through in your video:

Ben_Young1_0-1676592199564.png

Ben_Young1_1-1676592418722.png

You'll definitely need to swap out the field ids and table id from my script, but the structure remains the same.
I could definitely see this script getting some additional depth if you were to utilize the unique card id to facilitate duplicate comparisons and decision trees, but I digress. 

Lemme know if you're curious about anything or if something ain't working.
I definitely could've missed something.

@Ben_Young1 Thanks for the quick reply! I'm working on it more so down the line it will be able to increase the quantity of a card if its already been added, I'll definitely check into using the card id as a way to improve it even further! I am testing out the provide code you sent me and I'm running into one error, on line 33 I am getting an error regarding the selected card! 

Screenshot_1.png

Whoops - Misnamed a variable lol.
I just updated the script in my snippet found in the original post.
Try that snippet.

@Ben_Young1 Worked like a charm, thanks! Once I improve and expand on it I'll be sure to show it to you, thanks so much for your help!