Python Discord bot如何用youtube-dl搜索替代URL播放音乐并修复报错
问题原因
你遇到的两个问题根因如下:
- 关键词只能识别第一个:discord.py的命令参数默认按空格分割,你当前的
play函数只定义了一个url位置参数,用户输入多词搜索内容时只会把第一个单词传给参数 - 报错
TypeError: expected str, bytes or os.PathLike object, not dict:搜索结果返回entries结构时,你直接把整个格式字典赋值给了url2,没有取字典里的url字段
修复后的代码
@commands.command() # 用*query接收所有空格分隔的参数,自动拼接成完整搜索词 async def play(self, ctx, *, query): if ctx.author.voice is None: await ctx.send("You are not in a voice channel!") return voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) ctx.voice_client.stop() FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} # 指定ytsearch1仅返回第一个匹配结果,提升搜索效率 YDL_OPTIONS = {'format':"bestaudio", 'default_search':"ytsearch1"} vc = ctx.voice_client with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(query, download=False) if 'entries' in info: # 补全url字段取值,避免传入格式字典触发类型错误 url2 = info["entries"][0]["formats"][0]['url'] elif 'formats' in info: url2 = info["formats"][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS) vc.play(source)
修改点说明
- 命令参数调整为
*, query:*后面的所有输入内容都会作为完整字符串传给query参数,不会按空格拆分,支持多词搜索 - 搜索结果取值逻辑修复:搜索返回的
entries结构下取音频流时补全['url']字段,获取真实的流地址字符串 default_search调整为ytsearch1:明确只返回第一个匹配的搜索结果,减少不必要的信息拉取
内容的提问来源于stack exchange,提问作者PypypieYum
相关产品推荐
相关产品推荐

