我正在尝试使用教程和我的头脑混合使用 discord.py 制作音乐机器人。它可以工作,但是如果您在当前播放的同时尝试播放另一首歌曲,则会出现错误。为了解决这个问题,我试图添加一个队列系统,但我尝试过的所有教程似乎都太复杂了,完全适合他们的代码类型,而不是我的。我已经设法在当前歌曲结束时发生一些事情,但我不知道如何调用下一首歌曲。我正在考虑使用队列模块,但无法让它工作。这是我的代码:
@client.command()
async def play(ctx, url : str):
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except PermissionError:
await ctx.send("Wait for the current playing music to end or use the 'stop' command")
return
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
print(voice)
if voice == None:
search_keyword = url
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
finished_url = ("https://www.youtube.com/watch?v=" + video_ids[0])
video = pafy.new(finished_url)
value = video.length
if value > 420:
await ctx.send('Sorry, 7 minute maximum length on videos')
else:
voiceChannel = ctx.author.voice.channel
await voiceChannel.connect()
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([finished_url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
timer = value
while True:
asyncio.sleep(1)
timer -= 1
if timer < 0:
#this is where I could put something that calls up the next track in the queue if there is one as this is where the current song ends
else:
search_keyword = url
html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
finished_url = ("https://www.youtube.com/watch?v=" + video_ids[0])
video = pafy.new(finished_url)
value = video.length
if value > 420:
await ctx.send('Sorry, 7 minute maximum length on videos')
else:
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([finished_url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
timer = value
while True:
asyncio.sleep(1)
timer -= 1
if timer < 0:
#this is where I could put something that calls up the next track in the queue if there is one as this is where the current song ends
任何帮助将不胜感激。