Python Discord py cryptocurrency API命令不工作
我有一个命令,该命令应该获取给定加密货币的价格,但它不起作用。代码如下:Python Discord py cryptocurrency API命令不工作,python,discord,discord.py,Python,Discord,Discord.py,我有一个命令,该命令应该获取给定加密货币的价格,但它不起作用。代码如下: @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]', col
@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错误。>url=”https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd%2Ceur%2Cgbp"
>>> 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"]
>>>
>>>导入请求
>>>stats=requests.get(url)
>>>json_stats=stats.json()
>>>json_统计数据
{‘比特币’:{‘美元’:39125,‘欧元’:32474,‘英镑’:28473}
>>>usdprice=json_统计数据[“usd”]
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
关键错误:“美元”
>>>usdprice=json_统计数据[“比特币”][“美元”]
>>>
逐行执行代码,然后您将看到错误。
usdprice=json\u stats[“usd”]
将始终返回错误。执行类似于usdprice=json_stats[cc][“usd”]
的操作,或者在指定多个货币的情况下更好地对其进行迭代:json_stats.items()中k,v的
:
不要编写常规的try-except块(except-KeyError:
)。指定在except中预期的错误。此外,在发布调试问题时,还应提供错误回溯
返回一些结果,但是
结果是一本空字典
两者都会导致当前代码出错,但它们的来源不同