如何使用我的discord bot播放歌曲列表(discord.py)

Exc*_*pse 0 python python-3.x discord discord.py

我已经尝试创建一个字典并将.create_ytdl_player()实例列表存储到每个discord服务器id.

我只需要知道如何让玩家在前一个玩家完成后玩牌.

我想我必须使用.is_playing()或.is_done(),但我不知道如何使用它们.有人可以帮忙吗?

Orp*_*iel 5

我将使用适用于单个实例的代码来回答这个问题(尽管通过从字典中获取正确的播放器和voice_channel对象来编辑多个实例并不困难).

您必须首先创建一个队列,存储您的播放器将播放您的对象的URL.我假设您还应该创建一个队列字典来存储不同服务器的不同URL.

要帮助管理stream_player工作流程,请首先在最外层范围内声明语音和播放器对象.

self.player = None
self.voice = None
Run Code Online (Sandbox Code Playgroud)

应该在机器人加入语音通道后设置语音对象:

mvoice = await client.join_voice_channel(voice channel id here)
self.voice = mvoice
Run Code Online (Sandbox Code Playgroud)

然后我们必须创建两个函数,因为Python不支持异步lamdas,而管理流播放器只能通过异步函数完成.每当用户键入相关命令时,bot应该调用play_music函数:

#pass the url into here when a user calls the bot
async def play_music(client, message, url=None):
    if url is None:
    #function is being called from after (this will be explained in the next function)
        if queue.size() > 0:
            #fetch from queue
            url = queue.dequeue()
        else:
            #Unset stored objects, also possibly disconnect from voice channel here
            self.player = None
            self.voice = None
            return
    if self.player is None:
        #no one is using the stream player, we can start playback immediately
        self.player = await self.voice.create_ytdl_player(url, after=lambda: play_next(client, message))
        self.player.start()
    else:
        if self.player.is_playing():
            #called by the user to add a song
            queue.enqueue(url)
        else:
            #this section happens when a song has finished, we play the next song here
            self.player = await self.voice.create_ytdl_player(url, after=lambda: play_next(client, message))
            self.player.start()
Run Code Online (Sandbox Code Playgroud)

在流播放器完成一首歌之后,将从终结器调用play_next函数,并且将再次调用上述函数但没有url参数.

def play_next(client, message):
    asyncio.run_coroutine_threadsafe(play_music(client, message), client.loop)
Run Code Online (Sandbox Code Playgroud)