使机器人创建可播放音乐的代码

时间:2020-10-24 10:02:30

标签: discord.py

因此,我尝试做一个音乐机器人,但它没有播放音频。这是我得到的错误:

'VoiceClient' object has no attribute 'create_ytdl_player'

我已经知道我必须执行以下操作:

author = ctx.message.author
channel = author.voice_channel
await bot.join_voice_channel(channel)

但问题是它也给与错误。所以我想出了以下代码:

@client.command(pass_context=True)
async def play(ctx):
    channel = ctx.author.voice.channel
    voice = await channel.connect()
    
    await ctx.send("**Playing** Lofi music")
    player = await voice.create_ytdl_player("https://www.youtube.com/watch?v=-FlxM_0S2lA&ab_channel=ChilledCow")
    players[server.id] = player
    player.start()

但是,它又出现了上面的错误。有办法解决吗?

1 个答案:

答案 0 :(得分:0)

您的问题是重复的:Discord Music bot VoiceClient' object has no attribute 'create_ytdl_player'
但是youtube-dl已被删除,不再使用plublic。因此,我将添加更多信息。
为了使代码正常工作,您必须使用pafy之类的库,该库仍然可以访问youtube-dl

这是一个简短的例子:

from pafy import new
from discord import FFmpegPCMAudio

@client.command(pass_context=True)
async def play(ctx):
    ffmpeg_opts = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
    channel = ctx.author.voice.channel
    voice = await channel.connect()
        
    await ctx.send("**Playing** Lofi music")
    video = new("https://www.youtube.com/watch?v=-FlxM_0S2lA&ab_channel=ChilledCow")
    audio = video.getbestaudio().url
    voice.play(FFmpegPCMAudio(audio, **ffmpeg_opts))
    voice.is_playing()

更多信息在这里:

  • 要使代码正常工作,您需要install ffmpeg
  • ffmpeg_opts解决了here中解释的一个已知问题。
  • 如果您想了解有关pafy的更多信息,请访问documentation