播放队列中的所有歌曲



这是我的代码:

@commands.command(pass_context=True, aliases= ["aq"])
async def add_queue(self, ctx, *, url):
a = ctx.message.guild.id
b = servers[a]
global queue
try: 
b[len(b)] = url 
user = ctx.message.author.mention
await ctx.send(f'``{url}`` was added to the queue by {user}!')
except:
await ctx.send(f"Couldnt add {url} to the queue!")
@commands.command(pass_context=True, aliases= ["qp"], case_insensitive=True)
async def pq(self,ctx, number):
a = ctx.message.guild.id
b = servers[a]
if int(number) in b:
source = b[int(number)]
self.cur_song_id = int(number)
await ctx.send(f"**Now Playing:** {source}")
await self.transformer(ctx, source)

async def transformer(self,ctx, url):
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
if not ctx.message.author.voice:
await ctx.send("You are not connected to a voice channel!")
return
elif ctx.voice_client and ctx.voice_client.is_connected():
print('Already connected to voice')
pass
else:
channel = ctx.message.author.voice.channel
await ctx.send(f'Connected to ``{channel}``')
await channel.connect()
ctx.voice_client.play(player)

我可以为每个服务器创建一个单独的队列,并通过以下命令向其中添加歌曲:

-aq song_name

示例队列:

Your current queue is {0: 'abcdefu', 1: 'stereo hearts', 2: 'shivers'}

我可以用以下命令播放队列中的歌曲:

-pq 0 or -pq 1 or -pq 2

但问题是,机器人只播放一首歌,并在它结束后停止,我希望机器人在当前歌曲结束后播放下一首歌并继续播放,直到播放完队列中的最后一首歌。

请帮我解决这个问题。。。。

提前感谢!!!

首先,您的字典({0: 'abcdefu', 1: 'stereo hearts', 2: 'shivers'}(实际上可以只是一个列表,因为键基本上只是索引。

其次,我对discord.py中的音频没有任何经验,但似乎你的pq功能实际上并没有进入下一首歌。它只调用transformer函数一次,就这样。看起来你所要做的就是在队列中循环并播放每首歌。以下是一些可能有用的伪代码:

@commands.command()
async def play_queue(self,ctx,number=0):
for num in range(number,len(queue)):
song = queue[num]
# play the song

若并没有指定号码,默认的number=0将允许播放整个队列。

所以,为了解决我的问题,我实现了这段代码,它很有效。

我将我的队列(一个字典(传递给了transformer函数,并传递了一个默认为0的数字(用于从一开始播放队列(。

在play函数中使用after参数,我不断调用该函数,并不断迭代数字,只要它小于队列的长度。

它自动播放队列中的歌曲。

我知道这个代码是有效的,但是,如果可以做任何改进,我愿意接受建议。

async def transformer(self,ctx, number, que):
player = await YTDLSource.from_url(que[number], loop=self.bot.loop,stream=True)
await ctx.send(f"**Now Playing:** {que[number]}")
ctx.voice_client.play(player, after=lambda e: asyncio.run_coroutine_threadsafe(self.transformer(ctx,number+1 , que),self.bot.loop) if number < len(que) else ctx.voice_client.pause())

谢谢!。

最新更新