【发布时间】: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 programs 和to use a debugger 的好时机,逐步检查您的代码并观察每一行代码的作用。通过将这些中间结果与预期结果进行比较,确定您的程序与您的预期有何不同。从那里向后工作以缩小问题的原因。如果您仍然对代码的行为感到困惑,请提出一个特定 问题。转储代码并期望其他人为您调试它是不行的。
-
请阅读tour,阅读what's on-topic here、How to Ask和question checklist。欢迎使用 Stack Overflow!
-
您好,感谢您的回复!我马上去看看!
标签: python discord discord.py