Discord音乐机器人play命令仅识别首个单词 如何获取完整歌曲名
问题原因
discord.py 命令框架默认按空格分割位置参数,因此play命令的url参数仅能捕获.play后第一个空格前的内容,后续文本会被判定为多余参数直接丢弃。
修复方案
调整命令函数的参数声明即可,*标记在discord.py的命令参数规则中代表:后续所有输入内容会合并为单个字符串传入下一个参数,无需修改其他业务逻辑。
修改后的代码如下:
@client.command() async def play(ctx, *, url): search_keyword = add(url) print(url) html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword) video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode()) link = "https://www.youtube.com/watch?v=" + video_ids[0] print(link) YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'} FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} voice = get(client.voice_clients, guild=ctx.guild) if not voice.is_playing(): with YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(link, download=False) URL = info['url'] voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS)) voice.is_playing()
可选优化
为避免搜索词包含特殊符号导致搜索异常,可对拼接的搜索参数做URL编码处理,导入urllib.parse模块后,将拼接搜索链接的行修改为:
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + urllib.parse.quote(search_keyword))
内容的提问来源于stack exchange,提问作者Yash Sharma
相关产品推荐
相关产品推荐

