首页 > 解决方案 > discord.py keyerror 中的歌词命令

问题描述

所以我最近做了一个歌词命令和它的工作!唯一的问题是,当我写胡言乱语时,它发送了错误“发生错误:命令引发异常:KeyError:'lyrics'”,我为此添加了一个除了 KeyError 错误处理程序,但它不起作用,知道为什么吗?

@commands.command()
async def lyrics(self, ctx,*, title):
     url = f"https://some-random-api.ml/lyrics?title={title}"
     response = requests.get(url)
     json_data = json.loads(response.content)
     lyrics = json_data['lyrics']
     try:
       if len(lyrics) > 2048:
          em = discord.Embed(title=title,description = f"I wasn't able to send the lyrics for that song since it exceeds 2000 characters. However, here's the file for the lyrics!",color=0xa3a3ff)
          await ctx.send(embed=em)
          file = open("lyrics.txt", "w")
          file.write(lyrics)
          file.close() 
          return await ctx.send(file=discord.File("lyrics.txt"))
       else:
          em = discord.Embed(title=title,description=lyrics,color=0xa3a3ff)
          await ctx.send(embed=em)
     except KeyError:
       em = discord.Embed(title="Aw Snap!",description="I wasn't able to find the lyrics of that song.",color = 0xa3a3ff)
       em.set_thumbnail(url='https://cdn.discordapp.com/attachments/830818408550629407/839555682436251698/aw_snap_large.png')
       await ctx.send(embed=em)

标签: pythondiscorddiscord.py

解决方案


您的 try-except 块位于导致错误的行之后。

# ...
lyrics = json_data['lyrics'] # Erroneous line
try:
    # ...

如果您希望异常发生并被捕获,就像 Python 的方式一样,您可以将lyrics声明行移动到 try 块中。

或者,您可以使用 get() 安全地获取值并将 try-except 块替换为 if-else:

# ...
lyrics = json_data.get('lyrics')
if lyrics:
    # Show lyrics
    if len(lyrics) > 2048:
        em = discord.Embed(title=title,description = f"I wasn't able to send the lyrics for that song since it exceeds 2000 characters. However, here's the file for the lyrics!",color=0xa3a3ff)
        await ctx.send(embed=em)
        # ...
else:
    # Show message
    em = discord.Embed(title="Aw Snap!",description="I wasn't able to find the lyrics of that song.",color = 0xa3a3ff)
    em.set_thumbnail(url='https://cdn.discordapp.com/attachments/830818408550629407/839555682436251698/aw_snap_large.png')
    await ctx.send(embed=em)

推荐阅读