Discord.py歌词查询机器人开发求助:求可用代码及现有代码修复指导
Discord.py 歌词查询机器人问题排查与修复方案
我来帮你搞定这个歌词查询机器人的问题。先拆解下你现有代码里的几个关键问题,再给你一个能稳定运行的修复版本:
现有代码的问题分析
- 未处理API请求异常:当网络出问题、API返回404/500这类错误状态码时,直接调用
response.json()或者访问data['lyrics']会抛出异常,导致机器人崩溃。 - KeyError风险:如果歌曲没找到,API返回的JSON里没有
lyrics字段,反而会有error字段,你直接取data['lyrics']会触发KeyError。 - 逻辑分支错误:第二个
if没有用elif或者return,哪怕已经发送了"Song not found"的提示,代码还是会继续执行创建embed的逻辑,大概率会报错。 - 多余的Session操作:
async with aiohttp.ClientSession()会自动管理Session的开启和关闭,手动调用await session.close()完全没必要,甚至可能引发错误。
修复后的完整代码
import aiohttp import discord async def lyrics(self, ctx, artist, *, title): # 对艺术家和歌曲名的空格进行URL编码,提升API匹配成功率 artist_encoded = artist.replace(" ", "%20") title_encoded = title.replace(" ", "%20") api_url = f"https://api.lyrics.ovh/v1/{artist_encoded}/{title_encoded}" try: async with aiohttp.ClientSession() as session: async with session.get(api_url) as response: # 先检查请求是否成功 if response.status != 200: await ctx.send("Song not found! Please enter correct Artist and Song title") return data = await response.json() # 验证lyrics字段是否存在且不为空 if "lyrics" not in data or data["lyrics"] is None: await ctx.send("Song not found! Please enter correct Artist and Song title") return lyrics_content = data["lyrics"] # 处理超过Discord消息长度限制的歌词 if len(lyrics_content) > 2048: lyrics_content = lyrics_content[:2047] + "..." await ctx.send("Lyrics are too long! Showing first 2048 characters:") # 创建更清晰的Embed消息 embed = discord.Embed( title=f"{title} by {artist}", description=lyrics_content, color=discord.Color.blue() ) await ctx.send(embed=embed) # 捕获网络相关错误 except aiohttp.ClientError as e: await ctx.send(f"Failed to connect to lyrics service: {str(e)}") # 捕获其他意外错误,防止机器人崩溃 except Exception as e: await ctx.send(f"Oops! Something went wrong: {str(e)}")
关键改进说明
- 全面异常处理:用
try-except捕获网络错误和其他意外情况,确保单个命令的故障不会导致整个机器人崩溃。 - 严谨的API响应检查:先判断状态码,再验证字段存在性,从根源上避免KeyError和无效数据处理。
- 逻辑流程优化:每一步错误判断后都用
return终止后续代码,避免无效执行。 - 用户体验提升:过长歌词时添加提示,Embed标题包含艺术家名字,还加了颜色让消息更美观。
- URL编码优化:处理带空格的艺术家/歌曲名,比如"Billie Eilish"这类名字,能让API更准确匹配到歌曲。
内容的提问来源于stack exchange,提问作者Haripreetham.js
相关产品推荐
相关产品推荐

