Reputation: 63
I have a command that is supposed to get the price of a given cryptocurrency but it's not working. Heres the code:
@commands.command()
async def crypto(self, ctx, cc = None):
try:
if cc is None:
ccbed=discord.Embed(title='Command Usage:', description=f'/crypto [crypto currency]', colour=random.randint(0x000000, 0xffffff), timestamp=datetime.utcnow())
await ctx.send(embed=ccbed)
else:
url = f"https://api.coingecko.com/api/v3/simple/price?ids={cc}&vs_currencies=usd%2Ceur%2Cgbp"
stats = requests.get(url)
json_stats = stats.json()
usdprice = json_stats["usd"]
europrice = json_stats["eur"]
gbpprice = json_stats["gbp"]
ccbed2 = discord.Embed(title=f"**Current price of {cc}**", description="This data might be inaccurate.", colour=random.randint(0x000000, 0xffffff), timestamp=datetime.utcnow())
ccbed2.add_field(name="**USD:**", value=usdprice, inline=True)
ccbed2.add_field(name="**EURO:**", value=europrice, inline=True)
ccbed2.add_field(name="**GBP:**", value=gbpprice, inline=True)
await ctx.send(embed=ccbed2)
except:
ccbed3 = discord.Embed(title="Invalid crypto currency or API error.", colour=random.randint(0x000000, 0xffffff), timestamp=datetime.utcnow())
ccbed3.set_author(name="Error!")
await ctx.send(embed=ccbed3)
When I run the command it triggers the Invalid cryptocurrency or API error.
Upvotes: 1
Views: 389
Reputation: 5330
>>> url = "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd%2Ceur%2Cgbp"
>>> import requests
>>> stats = requests.get(url)
>>> json_stats = stats.json()
>>> json_stats
{'bitcoin': {'usd': 39125, 'eur': 32474, 'gbp': 28473}}
>>> usdprice = json_stats["usd"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'usd'
>>> usdprice = json_stats["bitcoin"]["usd"]
>>>
Execute your code, line by line then you will see the error.
usdprice = json_stats["usd"]
will always return an error. Do something like usdprice = json_stats[cc]["usd"]
or better iterate over it in case you specified multiple currencies:
for k, v in json_stats.items():
Don't write a general try except block (except KeyError:
). Specify the error you expect in the except. Also when posting a debugging question you should supply the error traceback.
https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd%2Ceur%2Cgbp returns some result but https://api.coingecko.com/api/v3/simple/price?ids=btc&vs_currencies=usd%2Ceur%2Cgbp results an empty dictionary.
Both will lead to an error in your current code but they are of different origin.
Upvotes: 1