【问题标题】:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'link'discord.ext.commands.errors.CommandInvokeError:命令引发异常:KeyError:'link'
【发布时间】:2022-01-16 07:01:06
【问题描述】:

我尝试创建一个 discord.py 机器人命令来发送随机的狗事实和图像,但我遇到了这个错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'link'

代码如下:

@bot.command()
async def dog(ctx):
    response = requests.get('https://some-random-api.ml/animal/dog')
    json_data = json.loads(response.text) 

    embed = discord.Embed(color = 0xff9900, title = 'random dog fact') 
    embed.set_image(url = json_data['link']) 
    await ctx.send(embed = embed)

【问题讨论】:

    标签: python python-3.x discord.py


    【解决方案1】:

    JSON 响应中没有名为 "link" 的键。使用"fact" 代替狗事实,使用"image" 代替随机狗图像。

    另外,代替这个代码块:

    response = requests.get('https://some-random-api.ml/animal/dog')
    json_data = json.loads(response.text)
    

    你可以使用

    json_data = requests.get('https://some-random-api.ml/animal/dog').json()
    

    使用 Requests 的内置 json() 方法。

    【讨论】:

    • 我按照你说的做了一切,但我遇到了另一个错误“命令引发异常:HTTPException:400 错误请求(错误代码:50035):无效的表单正文”我认为有些问题api
    • API 对我来说运行良好。也许你已经打了太多次,你已经被禁止了一段时间。
    猜你喜欢
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多