如何从discord.py创建一个机器人,在语音聊天中播放音乐?

aemubtdh  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(654)

我已经安装了youtube模块。当我说!像g6一样播放歌曲,它会出现错误,因为它在语音聊天中未连接,但它已连接。

@bot.command(name='play_song', help='To play song')
async def play(ctx,url):
    try :
        server = ctx.message.guild
        voice_channel = server.voice_client

        async with ctx.typing():
            filename = await YTDLSource.from_url(url, loop=bot.loop)
            voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename))
        await ctx.send('**Now playing:**{}'.format(filename))
    except:
        await ctx.send("The bot is not connected to a voice channel.")
zphenhs4

zphenhs41#

idk如何解决这个问题,但是如果你需要yt的play music命令,你可以在这里使用我的代码,只需更改描述和命令名。

@client.command()
async def playyt(ctx, url):
    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
    except PermissionError:
        em8 = discord.Embed(title = "Music Is Currently Playing", description = 'Please wait for the current playing music to end or use %leave <:_Paimon6:827074349450133524>.\nMusic provided by {ctx.author.mention} <:_Paimon6:827074349450133524>',color = ctx.author.color)
        await ctx.send(embed = em8)
        return

    voiceChannel = discord.utils.get(ctx.guild.voice_channels)
    await voiceChannel.connect()
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    em6 = discord.Embed(title = "Downloading Youtube Music", description = f'{url}\n\nPlease wait for paimon to setup the music you provide.\nMusic provided by {ctx.author.mention} <:_Paimon6:827074349450133524>',color = ctx.author.color)
    await ctx.send(embed = em6, delete_after = 2)
    await ctx.message.delete()

    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '196',
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            os.rename(file, "song.mp3")
    voice.play(discord.FFmpegPCMAudio("song.mp3"))
    em1 = discord.Embed(title = "Now Listening Youtube Music", description = f'{url}\n\nPlease use %leave first to change music.\nMusic provided by {ctx.author.mention} <:_Paimon6:827074349450133524>',color = ctx.author.color)

    videoID = url.split("watch?v=")[1].split("&")[0]

    em1.set_thumbnail(url = f'https://img.youtube.com/vi/{videoID}/default.jpg'.format(videoID = videoID))
    await ctx.send(embed = em1)

此命令将使用yt_dl直接从youtube下载音乐,然后下载的音乐将存储在您的bot目录中,下载完成后,您的bot将通过将下载的文件转换为mp3来处理歌曲,只需等待片刻,歌曲就会自动播放。此命令只能播放一首歌曲,您需要断开机器人与vc的连接才能播放另一首音乐。

相关问题