Discord Bot歌名搜索播放报TypeError字符串拼接错误如何修复?
错误原因
当传入歌名进行搜索时,你设置的ytsearch模式会让yt-dlp返回搜索结果集合对象,该对象本身没有title字段,单条歌曲的标题存储在entries列表的第一个元素中。你原有逻辑仅替换了播放用的url变量,读取标题时仍然从搜索结果集合对象取值,返回None后和字符串拼接就触发了类型错误。直接传入视频URL时,yt-dlp返回的是单条视频信息对象,本身带有title字段,所以不会报错。
修复方案
统一提取单条视频的信息对象,无论入参是歌名还是URL都从该对象中读取标题,同时可以加默认值避免极端情况的空值问题,修改后的代码如下:
@client.command(pass_context = True) async def play(ctx, *, url): if (ctx.author.voice): channel = ctx.message.author.voice.channel voice = get(client.voice_clients, guild=ctx.guild) if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() else: await ctx.send('`You are not in a voice channel`') YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True', 'default_search':"ytsearch"} FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} voice = get(client.voice_clients, guild=ctx.guild) with YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) # 新增逻辑:统一获取单条视频信息 if 'entries' in info: video_info = info["entries"][0] url = video_info["formats"][0]['url'] else: video_info = info url = video_info["formats"][0]['url'] if not voice.is_playing(): voice.play(FFmpegPCMAudio(url, **FFMPEG_OPTIONS), after=lambda x=0: check_queue(ctx, ctx.message.guild.id)) embed_p = discord.Embed(colour = discord.Colour.magenta()) # 改用video_info读取标题,加默认值兜底 embed_p.add_field(name='Playing:『 ' + video_info.get('title', '未知歌曲')+' 』', value='『'+ctx.author.mention+'』' , inline=False) await ctx.send(embed=embed_p)
内容的提问来源于stack exchange,提问作者Aina
相关产品推荐
相关产品推荐

