首页 > 解决方案 > discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'price_change_pct'

问题描述

我正在尝试创建一个 Discord.py 机器人命令,通过 API 告诉比特币百分比变化。

这是我写的代码:

@bot.command(name='btcpercent', aliases=['bitcoinpercent'])
async def btcpricepercent(ctx):
    url = "https://api.nomics.com/v1/currencies/ticker?key=<key>&ids=BTC&interval=1d,&convert=USD&per-page=1&page=1"
    async with ClientSession() as session:
        async with session.get(url) as response:
            r = await response.json()
            await ctx.send(f"Price has changed by **{r[0]['price_change_pct']}%** for each Bitcoin.")

这是 API 返回的内容:

[{"id":"BTC","currency":"BTC","symbol":"BTC","name":"Bitcoin","logo_url":"https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg","status":"active","price":"11407.91143811","price_date":"2020-10-14T00:00:00Z","price_timestamp":"2020-10-14T05:19:00Z","circulating_supply":"18516612","max_supply":"21000000","market_cap":"211235869830","num_exchanges":"364","num_pairs":"39697","first_candle":"2011-08-18T00:00:00Z","first_trade":"2011-08-18T00:00:00Z","first_order_book":"2017-01-06T00:00:00Z","rank":"1","rank_delta":"0","high":"19337.69352527","high_timestamp":"2017-12-16T00:00:00Z","1d":{"volume":"17775118517.27","price_change":"-81.08743454","price_change_pct":"-0.0071","volume_change":"-3865622342.16","volume_change_pct":"-0.1786","market_cap_change":"-1489550471.70","market_cap_change_pct":"-0.0070"}}]

老实说,我不知道我做错了什么,如果有人可以提供帮助会很棒:thumbs_up:!

标签: pythondiscorddiscord.py

解决方案


This issue is taking the data. When you are in this situation use a website to check the layout of your Json file jsonlint.

This is the correct layout.

r[0]['1d']['price_change_pct']

This is the data organized as you can see price_change_pct is inside 1d

[{
    "id": "BTC",
    "currency": "BTC",
    "symbol": "BTC",
    "name": "Bitcoin",
    "logo_url": "https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg",
    "status": "active",
    "price": "11407.91143811",
    "price_date": "2020-10-14T00:00:00Z",
    "price_timestamp": "2020-10-14T05:19:00Z",
    "circulating_supply": "18516612",
    "max_supply": "21000000",
    "market_cap": "211235869830",
    "num_exchanges": "364",
    "num_pairs": "39697",
    "first_candle": "2011-08-18T00:00:00Z",
    "first_trade": "2011-08-18T00:00:00Z",
    "first_order_book": "2017-01-06T00:00:00Z",
    "rank": "1",
    "rank_delta": "0",
    "high": "19337.69352527",
    "high_timestamp": "2017-12-16T00:00:00Z",
    "1d": {
        "volume": "17775118517.27",
        "price_change": "-81.08743454",
        "price_change_pct": "-0.0071",
        "volume_change": "-3865622342.16",
        "volume_change_pct": "-0.1786",
        "market_cap_change": "-1489550471.70",
        "market_cap_change_pct": "-0.0070"
    }
}]

推荐阅读