不和谐.py | 播放 url 中的音频

rap*_*iel 5 python bots discord discord.py

我想让我的机器人从某个网址播放音频,但我不想下载该文件......

这是我的代码:

@commands.command(name='test')
    async def test(self, ctx):

        search = "morpheus tutorials discord bot python"

        if ctx.message.author.voice == None:
            await ctx.send(embed=Embeds.txt("No Voice Channel", "You need to be in a voice channel to use this command!", ctx.author))
            return

        channel = ctx.message.author.voice.channel

        voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)

        voice_client = discord.utils.get(self.client.voice_clients, guild=ctx.guild)

        if voice_client == None:
            await voice.connect()
        else:
            await voice_client.move_to(channel)

        search = search.replace(" ", "+")

        html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())

        #################################
        await ctx.send("https://www.youtube.com/watch?v=" + video_ids[0])
        # AND HERE SHOULD IT PLAY
        #################################
Run Code Online (Sandbox Code Playgroud)

我尝试过 create_ytdl_player 方法,但发现它不再支持,我该怎么办?

LoC*_*LoC 3

使用帕菲。

首先导入一些东西并设置 FFmpeg 选项...

import pafy
from discord import FFmpegPCMAudio, PCMVolumeTransformer


FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5','options': '-vn'}
Run Code Online (Sandbox Code Playgroud)

然后播放它

@commands.command(name='test')
    async def test(self, ctx):

        search = "morpheus tutorials discord bot python"

        if ctx.message.author.voice == None:
            await ctx.send(embed=Embeds.txt("No Voice Channel", "You need to be in a voice channel to use this command!", ctx.author))
            return

        channel = ctx.message.author.voice.channel

        voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)

        voice_client = discord.utils.get(self.client.voice_clients, guild=ctx.guild)

        if voice_client == None:
            voice_client = await voice.connect()
        else:
            await voice_client.move_to(channel)

        search = search.replace(" ", "+")

        html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())

        
        await ctx.send("https://www.youtube.com/watch?v=" + video_ids[0])

        song = pafy.new(video_ids[0])  # creates a new pafy object

        audio = song.getbestaudio()  # gets an audio source

        source = FFmpegPCMAudio(audio.url, **FFMPEG_OPTIONS)  # converts the youtube audio source into a source discord can use

        voice_client.play(source)  # play the source
        
Run Code Online (Sandbox Code Playgroud)

  • 请在您的答案中添加更多解释 (2认同)