我将使用适用于单个实例的代码来回答这个问题(尽管通过从字典中获取正确的 player 和 voice_channel 对象来为多个实例编辑它应该不难)。
您必须首先创建一个队列来存储播放器将在其中播放对象的 url。我假设您还应该创建一个队列字典来存储不同服务器的不同 url。
为了帮助管理您的 stream_player 工作流程,首先在最外层范围内声明一个语音和播放器对象。
self.player = None
self.voice = None
语音对象应在机器人加入语音通道后设置:
mvoice = await client.join_voice_channel(voice channel id here)
self.voice = mvoice
然后我们必须创建两个函数,因为 Python 不支持异步 lamdas,而管理流播放器只能通过异步函数完成。每当用户键入相关命令时,机器人都应调用 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)