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

Discord音乐Bot搜索播放功能触发KeyError报错求助

解决Discord音乐Bot搜索功能的KeyError问题

问题根源

你遇到的KeyError是因为youtube-dl处理搜索词和直接视频链接时返回的数据结构完全不同:

  • 传入直接链接时,ytdl.extract_info()返回的字典里会包含以该链接为键的条目
  • 传入搜索词(比如macarena)时,返回的字典是一个「搜索结果集合」,包含entries列表,里面是匹配到的视频数据,根本不存在以搜索词为键的字段,所以song = data[url]必然报错

修复代码

修改play命令中的数据提取逻辑,兼容两种输入场景:

voice_clients = {}

yt_dl_opts = {'format': 'bestaudio/best', 'default_search': 'auto'}
ytdl = youtube_dl.YoutubeDL(yt_dl_opts)

ffmpeg_options = {'options': "-vn"}
        
@bot.command()
async def play(msg, *, query):
    try:
        voice_client = await msg.author.voice.channel.connect()
        voice_clients[voice_client.guild.id] = voice_client
    except:
        print("Already in vc!")
    
    loop = asyncio.get_event_loop()
    data = await loop.run_in_executor(None, lambda: ytdl.extract_info(query, download=False))

    # 处理搜索结果或直接链接
    if 'entries' in data:
        # 搜索场景:取第一个结果
        song_info = data['entries'][0]
    else:
        # 直接链接场景:使用返回的本身数据
        song_info = data

    # 提取音频URL和视频标题
    song_url = song_info['url']
    song_title = song_info['title']

    player = nextcord.FFmpegPCMAudio(song_url, **ffmpeg_options)
    voice_clients[msg.guild.id].play(player)
    await msg.send(f"Now playing **{song_title}**")

关键修改说明

  1. 把参数名从url改为query,更贴合「支持搜索/链接两种输入」的场景
  2. 通过判断data中是否存在entries字段,区分搜索结果和直接链接
  3. 统一从song_info中提取音频URL(song_info['url']),这是youtube-dl返回数据中固定存在的字段
  4. 提取视频标题song_title,发送消息时显示标题,比显示搜索词/原始链接更友好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:55:32