我有一个命令可以获取给定加密货币的价格,但它不起作用。代码如下:
@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)
当我运行该命令时,它会触发无效的加密货币或 API 错误。
答案 0 :(得分:1)
>>> 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"]
>>>
逐行执行您的代码,然后您将看到错误。
usdprice = json_stats["usd"]
将始终返回错误。如果您指定了多种货币,请执行类似 usdprice = json_stats[cc]["usd"]
或更好的迭代:
for k, v in json_stats.items():
除了块 (except KeyError:
) 之外不要写一般性的 try。在except中指定您期望的错误。此外,在发布调试问题时,您应该提供错误回溯。
https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd%2Ceur%2Cgbp 返回一些结果但是 https://api.coingecko.com/api/v3/simple/price?ids=btc&vs_currencies=usd%2Ceur%2Cgbp 结果是一个空字典。
两者都会导致您当前代码中的错误,但它们的来源不同。