【问题标题】:Lyrics command in discord.pydiscord.py 中的歌词命令
【发布时间】:2021-07-27 22:52:59
【问题描述】:

所以我试图使用 discord.py 中的歌词 ovh api 来制作歌词命令,但我收到了这个错误:“发生错误:命令引发异常:KeyError:'lyrics'”

import aiohttp

@commands.command()
    async def lyrics(self, ctx, artist,*, title):
        async with aiohttp.ClientSession() as session:
           async with session.get(f"https://api.lyrics.ovh/v1/{artist}/{title}") as response:
                data = await response.json()
                lyrics = data['lyrics']
                if lyrics is None:
                    await ctx.send("Song not found! Please enter correct Artist and Song title")
                if len(lyrics) > 2048:
                     lyrics = lyrics[:2048]
                emb = discord.Embed(title = f"{title}" , description = f"{lyrics}",color = 0xa3a3ff)
                await ctx.send(embed=emb)
        await session.close()```

【问题讨论】:

  • 当我遇到错误时,这就是我的想法:什么会引发 KeyError?访问不存在的字典键。我应该访问什么密钥?错误告诉我——"lyrics"。我在哪里尝试访问字典中的 'lyrics' 键?就在这里:lyrics = data['lyrics']。如果data 字典没有'lyrics' 键,这意味着什么?我将如何处理?提示:我已经有了,我只需要将这个其他条件添加到 if 语句中!
  • 现在是学习how to debug small programsto use a debugger 的好时机,逐步检查您的代码并观察每一行代码的作用。通过将这些中间结果与预期结果进行比较,确定您的程序与您的预期有何不同。从那里向后工作以缩小问题的原因。如果您仍然对代码的行为感到困惑,请提出一个特定 问题。转储代码并期望其他人为您调试它是不行的。
  • 请阅读tour,阅读what's on-topic hereHow to Askquestion checklist。欢迎使用 Stack Overflow!
  • 您好,感谢您的回复!我马上去看看!

标签: python discord discord.py


【解决方案1】:

如果lyrics 不在您的json 对象中,则python 将引发KeyError。如果你想避免这种情况,你可以使用get方法。

data = {
    "key1": "value1",
    "key2": "value2"
}

value1 = data["key1"] #no error
value2 = data.get("key2") #no error
value3 = data["key3"] #this will raise KeyError because key3 not in data
value3 = data.get("key3") #this will not raise any error and return default value
value3 = data.get("key3", "No lyrics could be found.") #we passed the default value so this will return
         #"No lyrics could be found" if key3 is not exist in json

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 1970-01-01
    • 2021-03-26
    • 2020-07-15
    • 1970-01-01
    • 2021-05-23
    • 2021-08-28
    • 2021-01-22
    • 2021-03-30
    相关资源
    最近更新 更多