如何在discord.py音乐机器人中让youtube-dl支持关键词替代URL搜索播放
核心实现逻辑
youtube-dl原生支持关键词直接搜索,无需调用额外接口:给搜索关键词添加ytsearch1:前缀即可获取YouTube搜索结果的第一条内容,全程保持download=False参数就不会下载文件,完全保留你现有的流媒体播放逻辑。
需要修改的两处代码
调整play命令参数定义
原来的参数只能接收单个无空格的URL,修改后可以接收带空格的整句搜索词:
把async def play(self, ctx, url):改为async def play(self, ctx, *, search_keyword):,*符号会把后面所有输入内容合并为一个字符串参数。修改youtube-dl搜索和取值逻辑
原来的逻辑是直接解析传入的URL,修改后先给搜索词拼接搜索前缀,再适配搜索结果的返回结构取值:
with youtube_dl.YoutubeDL(ydl_options) as ydl: # 拼接搜索前缀,取第一条搜索结果 info = ydl.extract_info(f"ytsearch1:{search_keyword}", download=False)["entries"][0] url2 = info["formats"][0]["url"] source = await discord.FFmpegOpusAudio.from_probe(url2, **ffmpeg_options) vc.play(source) # 可选:发送正在播放的歌曲名提示 await ctx.send(f"正在播放:*{info['title']}*")
修改后的完整代码
import discord from discord.ext import commands import youtube_dl class Music(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def join(self, ctx): if ctx.author.voice is None: await ctx.send("你当前不在语音频道中!") 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) @commands.command() async def disconnect(self, ctx): await ctx.voice_client.disconnect() @commands.command() async def play(self, ctx, *, search_keyword): try: if ctx.author.voice is None: await ctx.send("你当前不在语音频道中!") 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' } ydl_options = { 'format': 'bestaudio' } vc = ctx.voice_client with youtube_dl.YoutubeDL(ydl_options) as ydl: info = ydl.extract_info(f"ytsearch1:{search_keyword}", download=False)['entries'][0] url2 = info['formats'][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(url2, **ffmpeg_options) vc.play(source) await ctx.send(f"正在播放:*{info['title']}*") except discord.ClientException: await ctx.send("当前正在播放歌曲") @commands.command() async def pause(self, ctx): ctx.voice_client.pause() embed = discord.Embed( title="", description="***已暂停播放***", color=0x2f3136 ) await ctx.send(embed=embed) @commands.command() async def resume(self, ctx): ctx.voice_client.resume() embed = discord.Embed( title="", description="***已恢复播放***", color=0x2f3136 ) await ctx.send(embed=embed) def setup(client): client.add_cog(Music(client))
使用说明
修改完成后直接发送.play 搜索关键词即可触发搜索播放,比如.play take my horse会自动匹配搜索结果第一条进行流媒体播放,不会下载任何文件到本地。
内容的提问来源于stack exchange,提问作者Witalik Zarscikov
相关产品推荐
相关产品推荐

