You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord音乐bot按歌名播放触发KeyError: 'url'错误如何解决?

问题根因

当你传入搜索关键词而非直接传入视频URL时,youtube-dl的extract_info返回的元数据结构和URL模式不同:搜索结果会被包装为播放列表结构,单条视频的元数据存放在info['entries']列表中,直接访问info['url']自然会触发KeyError。

修复代码

修改extract_info后的取值逻辑即可兼容URL输入和关键词搜索两种场景,同时优化参数适配带空格的歌名:

@bot.command(name='play', help='Plays audio in connected voice channel')
async def play(ctx, *, q): # 加*让带空格的歌名可以正常传入
    YDL_OPTIONS = {'default_search': 'auto', 'format': 'bestaudio', 'noplaylist':'True'}
    FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    voice = ctx.message.guild.voice_client

    if not voice:
        await ctx.send("请先让机器人加入语音频道")
        return
    
    with YoutubeDL(YDL_OPTIONS) as ydl:
        info = ydl.extract_info(q, download=False)
        # 判断是否是搜索结果的播放列表结构,是就取第一条
        if 'entries' in info:
            # 取第一条有效搜索结果
            video = info['entries'][0]
        else:
            # 直接是URL的情况
            video = info
        a = video['url']   
    if not voice.is_playing():
        voice.play(FFmpegPCMAudio(a, **FFMPEG_OPTIONS))
    else:
        await ctx.send("当前已有音频正在播放")
补充说明
  • 目前代码只取搜索结果的第一条,如果需要做多结果选择可以扩展entries的遍历逻辑
  • 原youtube-dl已经停止维护,建议替换为仍在更新的yt-dlp,接口完全兼容,稳定性和解析成功率更高
  • 可以根据需要补充歌名、时长等信息的回复,提升使用体验

内容的提问来源于stack exchange,提问作者Earl Watkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:36:04