首页 > 解决方案 > 我无法在我的 Discord Bot 上播放带有 Youtube URL 的歌曲

问题描述

因此,由于 Rhythm 和 Groovy 不可用,我尝试使用 Python 为我自己的服务器创建自己的音乐机器人,但我无法使用 YouTube URL 播放它。有没有人有解决方案?

    @commands.command()
    async def play(self,ctx,*,url):
        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(url, download=False)
         if 'entries' in info:
           url2 = info["entries"][0]["formats"][0]['url']
         elif 'formats' in info:
           url2 = info["entries"][0]["formats"][0]['url']
         source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
         vc.play(source)

标签: pythondiscorddiscord.py

解决方案


    @commands.command(name='play')
    async def _play(self, ctx: commands.Context, *, search: str):
        """Plays a song.
        If there are songs in the queue, this will be queued until the
        other songs finished playing.
        This command automatically searches from various sites if no URL is provided.
        
        """

        if not ctx.voice_state.voice:
            await ctx.invoke(self._join)

        async with ctx.typing():
            try:
                source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
            except YTDLError as e:
                await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
            else:
                song = Song(source)

                await ctx.voice_state.songs.put(song)
                await ctx.send('Enqueued {}'.format(str(source))) 

上面的代码取自这里。由于这是一个常见问题,我认为使用预先测试的代码将是创建选项。


推荐阅读