[英]How can I play a list of songs with my discord bot (discord.py)
我尝试创建字典并将.create_ytdl_player()实例的列表存储到每个不和谐服务器ID。
我只需要知道在上一个游戏完成后如何使游戏者玩。
我认为我必须使用.is_playing()或.is_done(),但我不知道如何使用它们。 有人可以帮忙吗?
我将使用适用于单个实例的代码来回答这个问题(尽管通过从字典中获取正确的播放器和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不支持异步lamda,而只能通过异步函数来管理流播放器。 每当用户键入相关命令时,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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.