python - 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)
解决方案
您的 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)
推荐阅读
- python - 根据另一列中的条件选择两列中的值(Python)
- java - 如何让计数器在此代码中工作?
- django - Django+React:对从 React 到 Django 后端的 API 请求正确实施身份验证和安全性的最佳方法是什么
- arrays - 您将如何在 Julia 中使用 map() 创建对现有组合类型数组的修改?
- node-opcua - 一个订阅中的多个变量
- cmd - 我无法对程序文件使用 where 命令
- r - 修改一行数据以获得漂亮的输出(摘要),重塑 - 将行拆分为新的多列
- java - 缓冲阅读器抛出异常
- testing - 赛普拉斯,如何检查属性是否存在
- python - Fizzbuzz Challenge in Twilio quest