简体   繁体   English

discord.py中的歌词命令

[英]Lyrics command in discord.py

So I was trying to make a lyrics command using the lyrics ovh api in discord.py and I'm getting this error: "An error occurred: Command raised an exception: KeyError: 'lyrics'"因此,我尝试使用 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()```

If lyrics not in your json object then python will raise KeyError .如果lyrics不在您的json object 中,则 python 将引发KeyError If you want to avoid from this, you can use get method.如果你想避免这种情况,你可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM