首页 > 解决方案 > 如何为自定义 Discord Bot 添加/创建队列 - Python

问题描述

我是编码新手,目前正在学习如何创建自定义 Discord 音乐机器人。我开始了可以将机器人添加到服务器并让它播放来自 youtube 的歌曲的部分。但是,我还想实现一个队列,这样每当一首歌曲结束时,下一首歌曲就会自动播放,但无济于事。我很想听听有人提出任何可以指导我在代码中实现队列的建议。

import discord 
from discord.ext import commands
import youtube_dl
from discord import FFmpegPCMAudio
import random

class music(commands.Cog):
    def __init__(self, client):
        self.client = client

    # adding a "join" command:
    @commands.command()
    async def join(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("You're not in a voice channel!")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            # random audio array:
            audio_file = ['1.wav','2.wav','3.wav','4.wav','5.wav','6.wav','7.wav','8.wav','8.wav','9.wav','9.wav','10.wav','11.wav']
            randomized = random.SystemRandom()
            item = randomized.choice(audio_file)
            print(item)
            voice = await voice_channel.connect()
            # making the bot say something upon entering:
            source = FFmpegPCMAudio(f'{item}')
            voice.play(source)
        else:
            await ctx.voice_client.move_to(voice_channel)

    # adding a "disconnect" command:
    @commands.command()
    async def d(self,ctx):
        await ctx.voice_client.disconnect()

    # playing new song if new song is added:

    @commands.command()
    async def play(self,ctx,url):
        ctx.voice_client.stop()
        # ffmpeg handles the steaming on discord official api:
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        # YDL options for audio format:
        YDL_OPTIONS = {'format': 'bestaudio'}
        vc = ctx.voice_client

        # streaming the audio:
        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)
            await ctx.channel.send('**Now playing** - ' + info.get('title'))

    # adding pause button:
    @commands.command()
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.send("Paused ⏸")

    # adding resume button:
    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.send("Resume ▶")

def setup(client):
    client.add_cog(music(client))

标签: pythondiscord

解决方案


推荐阅读