You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py调用some-random-api笑话接口报KeyError: 'Joke'问题求助

问题解决方案

报错根因

KeyError: 'Joke' 报错说明你读取的键名在接口返回的JSON中不存在:你调用的some-random-api笑话接口返回的笑话内容字段为小写开头的joke,和你代码里写的大写开头Joke大小写不匹配,直接读取就会抛出异常。

注意:你贴出的示例代码中@client.command()装饰器前有多余的缩进,如果你的实际代码也是这样写的,需要把这部分缩进删掉,否则joke命令不会被正常注册。

修复方案

基础修复(仅解决字段名问题)

只需要把取值代码里的jokejson['Joke']改成jokejson['joke']即可。

完整优化代码(新增异常处理,避免请求失败时崩溃)

import discord
import random
import aiohttp
from discord.ext import commands
client = commands.Bot(command_prefix = '.')

@client.command()
async def joke(ctx):
    async with aiohttp.ClientSession() as session:
        # 发送接口请求
        request = await session.get('https://some-random-api.ml/joke')
        # 处理请求失败的情况
        if request.status != 200:
            await ctx.send("暂时拉取不到笑话,请稍后重试")
            return
        jokejson = await request.json()
    
    embed = discord.Embed(title="我知道这个很好笑", color=discord.Color.purple())
    # 修正字段名大小写
    embed.set_footer(text=jokejson['joke'])
    await ctx.send(embed=embed)

内容的提问来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:06:05