Your trading Discord asks the same question all day: "what's this card worth?" This tutorial builds a bot that answers it. Type /price charizard and the bot replies with the live market price as an embed, pulled from the PkmnPrices API through its Python SDK. The finished bot is about 80 lines of Python, and you'll have it running locally by the end.
I built PkmnPrices, the API this tutorial uses.
Along the way you'll see the search-then-fetch pattern the SDK uses, how to register a slash command with autocomplete in discord.py v2, and how to stay inside a rate limit with a small cache.
What you'll build
A single slash command. A user types /price <card name>, and the bot replies with the card's set, condition, and current USD market price. It needs no database, and the SDK handles the HTTP.
Under the hood it's two steps, because the API splits search from pricing. client.cards.list() finds the card and returns its ID. client.cards.get() returns that card with its prices attached. The list call never returns price data, which trips people up: you always fetch the single card to get a number. And since a name like charizard matches dozens of printings across sets and variants, the bot lets the user pick the exact one before it fetches the price.
Before you start
You'll need three things:
- Python 3.10 or newer
- a Discord application with a bot token, from the Discord Developer Portal
- a PkmnPrices API key, free from the dashboard
Keep the two secrets out of your code. They go in a .env file:
DISCORD_TOKEN=your-bot-token PKMNPRICES_API_KEY=pk_your-api-key Set up the project
Create a folder, make a virtual environment, and install the dependencies. The pkmnprices SDK brings its own HTTP client, retries, and typed models.
mkdir price-bot && cd price-bot python -m venv .venv && source .venv/bin/activate pip install pkmnprices discord.py python-dotenv Meet the SDK
discord.py is async, and the SDK ships an async client for that: AsyncPkmnPrices. One call searches and one fetches.
from pkmnprices import AsyncPkmnPrices async with AsyncPkmnPrices("pk_your-api-key") as client: page = await client.cards.list(name="charizard", per_page=5) # no prices card = await client.cards.get(page.data[0].id, currency="usd") # with prices print(card.prices[0].market_price) # e.g. 12.19 list() returns a page with .data and .pagination. Each card is a typed object, so you write card.name and card.set.name and never index a dictionary. get() adds the prices list, where each entry has a condition, a variant, and a market_price.
Build the bot
bot.py comes together in four pieces: the skeleton, startup, an embed helper, and the command. Start with the imports and a bot with default intents.
# bot.py import os import discord from discord import app_commands from discord.ext import commands from dotenv import load_dotenv from pkmnprices import AsyncPkmnPrices, UnauthorizedError, RateLimitError, CreditLimitError load_dotenv() intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) Slash commands don't need the message-content intent, so the defaults are enough. commands.Bot requires a command_prefix, but this bot never uses it.
Register the command on startup
Two things have to happen once, when the bot boots: create an SDK client it can reuse for every request, and tell Discord the command exists. Both go in setup_hook, which discord.py runs before the bot connects.
@bot.event async def setup_hook(): bot.api = AsyncPkmnPrices(os.environ["PKMNPRICES_API_KEY"]) await bot.tree.sync() @bot.event async def on_ready(): print(f"Logged in as {bot.user}") bot.tree.sync() is what makes /price show up. Global syncs propagate in a few minutes, so while developing, sync to one server for instant updates with bot.tree.sync(guild=discord.Object(id=YOUR_GUILD_ID)).
Turn a card into an embed
Keep the presentation out of the command handler. This helper takes a card and returns a Discord embed. It prefers the Near Mint price and falls back to whichever price is first.
def build_embed(card): price = next( (p for p in card.prices if p.condition == "Near Mint"), card.prices[0] if card.prices else None, ) embed = discord.Embed(title=card.name, color=0x00E87B) if card.image_url: embed.set_thumbnail(url=card.image_url) embed.add_field(name="Set", value=card.set.name, inline=True) embed.add_field(name="Number", value=f"{card.number}/{card.total_set_number}", inline=True) embed.add_field(name="Condition", value=price.condition if price else "n/a", inline=True) embed.add_field( name="Market price", value=f"${price.market_price:.2f}" if price else "No data", inline=True, ) embed.set_footer(text="Data from PkmnPrices") return embed Define the /price command
A name search for charizard matches dozens of cards, one per set, reprint, and variant, so taking the first result would return an arbitrary one. Discord autocomplete fixes that. The user picks a real match as they type, and the value behind their choice is the card's ID. The command receives that ID and fetches it, with a fallback for text typed without picking a suggestion.
@bot.tree.command(name="price", description="Look up the market price of a Pokémon card") @app_commands.describe(card="Start typing a card name, then pick one from the list") async def price(interaction: discord.Interaction, card: str): await interaction.response.defer() try: if card.isdigit(): data = await bot.api.cards.get(int(card), currency="usd") else: page = await bot.api.cards.list(name=card, per_page=1) if not page.data: await interaction.followup.send(f"No card found for **{card}**.") return data = await bot.api.cards.get(page.data[0].id, currency="usd") await interaction.followup.send(embed=build_embed(data)) except Exception as err: await handle_error(interaction, err) await interaction.response.defer() runs first. Two round trips can outrun Discord's three-second reply window, and deferring extends it to fifteen minutes. handle_error comes in the next section.
Let the user pick the right card
The autocomplete callback fires as the user types and returns up to 25 choices, which is Discord's cap. Pairing each card name with its set turns a vague "Charizard" into a list the user can choose from: "Charizard · Base Set", "Charizard · Base Set 2", and so on.
@price.autocomplete("card") async def card_autocomplete(interaction: discord.Interaction, current: str): if len(current) < 3: return [] page = await bot.api.cards.list(name=current, per_page=10) return [ app_commands.Choice(name=f"{c.name} · {c.set.name}"[:100], value=str(c.id)) for c in page.data ] The len(current) < 3 check skips the search until the query is long enough to be useful, which matters because this runs on every keystroke.
The last line of the file starts the bot:
bot.run(os.environ["DISCORD_TOKEN"]) Handle errors and rate limits
The SDK raises typed exceptions, so you can handle the cases you care about by name. The two worth catching are a bad key and a limit.
async def handle_error(interaction, err): if isinstance(err, UnauthorizedError): await interaction.followup.send("API key is missing or invalid.") elif isinstance(err, (RateLimitError, CreditLimitError)): await interaction.followup.send("Rate or credit limit hit. Try again shortly.") else: print(err) await interaction.followup.send("Something went wrong. Try again in a moment.") The SDK already retries transient failures with backoff (tune it with AsyncPkmnPrices(key, max_retries=2)), so by the time RateLimitError reaches your handler, the limit is real.
The free tier allows 60 requests per minute and 500 credits per day, and list endpoints charge 1 credit per item returned (see the rate limit docs). Autocomplete is the expensive part. Each suggestion search returns up to ten cards and runs as the user types, so one lookup can spend more credits on suggestions than on the price.
Two things keep that affordable. The three-character check drops the shortest queries. A cache does the rest, because repeated prefixes can reuse one response. Prices update daily, so a ten-minute in-memory cache doesn't make the answers any less accurate.
import time _cache = {} TTL = 10 * 60 # seconds async def search_cached(api, name): key = name.lower() hit = _cache.get(key) if hit and time.monotonic() - hit["at"] < TTL: return hit["data"] page = await api.cards.list(name=name, per_page=10) _cache[key] = {"data": page.data, "at": time.monotonic()} return page.data Call search_cached(bot.api, current) from the autocomplete callback in place of bot.api.cards.list. Two users typing "chariz" within ten minutes then pay for one search.
The whole file
Here is bot.py with the cache wired into autocomplete.
# bot.py import os import time import discord from discord import app_commands from discord.ext import commands from dotenv import load_dotenv from pkmnprices import AsyncPkmnPrices, UnauthorizedError, RateLimitError, CreditLimitError load_dotenv() intents = discord.Intents.default() bot = commands.Bot(command_prefix="!", intents=intents) _cache = {} TTL = 10 * 60 # seconds @bot.event async def setup_hook(): bot.api = AsyncPkmnPrices(os.environ["PKMNPRICES_API_KEY"]) await bot.tree.sync() @bot.event async def on_ready(): print(f"Logged in as {bot.user}") async def search_cached(api, name): key = name.lower() hit = _cache.get(key) if hit and time.monotonic() - hit["at"] < TTL: return hit["data"] page = await api.cards.list(name=name, per_page=10) _cache[key] = {"data": page.data, "at": time.monotonic()} return page.data def build_embed(card): price = next( (p for p in card.prices if p.condition == "Near Mint"), card.prices[0] if card.prices else None, ) embed = discord.Embed(title=card.name, color=0x00E87B) if card.image_url: embed.set_thumbnail(url=card.image_url) embed.add_field(name="Set", value=card.set.name, inline=True) embed.add_field(name="Number", value=f"{card.number}/{card.total_set_number}", inline=True) embed.add_field(name="Condition", value=price.condition if price else "n/a", inline=True) embed.add_field( name="Market price", value=f"${price.market_price:.2f}" if price else "No data", inline=True, ) embed.set_footer(text="Data from PkmnPrices") return embed async def handle_error(interaction, err): if isinstance(err, UnauthorizedError): await interaction.followup.send("API key is missing or invalid.") elif isinstance(err, (RateLimitError, CreditLimitError)): await interaction.followup.send("Rate or credit limit hit. Try again shortly.") else: print(err) await interaction.followup.send("Something went wrong. Try again in a moment.") @bot.tree.command(name="price", description="Look up the market price of a Pokémon card") @app_commands.describe(card="Start typing a card name, then pick one from the list") async def price(interaction: discord.Interaction, card: str): await interaction.response.defer() try: if card.isdigit(): data = await bot.api.cards.get(int(card), currency="usd") else: page = await bot.api.cards.list(name=card, per_page=1) if not page.data: await interaction.followup.send(f"No card found for **{card}**.") return data = await bot.api.cards.get(page.data[0].id, currency="usd") await interaction.followup.send(embed=build_embed(data)) except Exception as err: await handle_error(interaction, err) @price.autocomplete("card") async def card_autocomplete(interaction: discord.Interaction, current: str): if len(current) < 3: return [] cards = await search_cached(bot.api, current) return [ app_commands.Choice(name=f"{c.name} · {c.set.name}"[:100], value=str(c.id)) for c in cards ] bot.run(os.environ["DISCORD_TOKEN"]) Deploy it
Locally, run python bot.py. Invite the bot to a server from the Developer Portal's OAuth2 URL generator with the applications.commands scope, and /price shows up in the command list.
For always-on hosting, anywhere that runs Python works: a small VPS, a container platform, or a hobby host. Your token and API key live in environment variables and never in the repo. If the API key leaks, rotate it from the dashboard.
Questions
Why use the SDK and not call the API directly?
The SDK ships an async client that fits discord.py, typed models, retries with backoff, and typed exceptions such as UnauthorizedError and RateLimitError. That leaves only the bot logic for you to write.
Does this work on the free tier?
Yes, with limits to know. The free tier serves English cards only, is for non-commercial use, and allows 500 credits per day at 60 requests per minute. A cached /price command fits inside that for a small or mid-sized server.
How many credits does one /price cost?
One credit when the user picks a suggestion, because that is a single-card fetch. Two on the free-text fallback. Autocomplete costs more, since each search returns up to 10 cards at 1 credit each, and that is what the three-character check and the cache are for.
Can the bot show price history?
Yes. The price history endpoint returns daily points over 7, 30, 90, or 365 days. Render them into an image and attach it to the embed for a /history command.
Wrap up
The same two-step pattern, search for an ID and then fetch the data, also works for sealed products, eBay sold listings, and Cardmarket offers. The API reference covers every endpoint.