python - 音乐机器人 discord.py 的队列系统
问题描述
我正在尝试使用教程和我的头脑来制作一个带有 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
任何帮助将不胜感激。
解决方案
推荐阅读
- go - 使用反射比较结构字段
- c# - 是否可以在方法参数中使用变量名和布尔值?
- c - 如何只读取输入的一个元素?或一个字符
- selenium - 为什么有些网站不能使用 Selenium 实现自动化
- ansible-facts - 如果嵌套数组中不存在嵌套值,则 Ansible
- pandas - 将两列转换为 datetime.datetime 格式的问题
- mysql - MySql 查询代码从单个 ID 获取唯一数据
- php - 使用 php sqlsrv_prepare 将中文字符插入 sql server
- dicom - DICOM StudyInstanceUID 对患者来说应该是唯一的吗?
- selenium - 如何使用 webdriverio 重新运行黄瓜中功能文件的失败步骤/secnario