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

时间:2018-04-08 17:28:45

标签: python python-3.x discord discord.py

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

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

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

1 个答案:

答案 0 :(得分:5)

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

你必须首先建立一个队列来存储你的播放器将播放你的对象的网址。我假设你还应该制作一个队列字典来存储不同服务器的不同网址。

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

self.player = None
self.voice = None

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

mvoice = await client.join_voice_channel(voice channel id here)
self.voice = mvoice

然后我们必须创建两个函数,因为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()

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

def play_next(client, message):
    asyncio.run_coroutine_threadsafe(play_music(client, message), client.loop)