I'm adding a music feature to my bot so that it can play songs from youtube. So far the bot can play one song but I want to add a queue, so that if a song is playing at the moment, the song will be added to a list. I've tried some methods already but always ended up having errors here and there so I want to know what the best way to add a queue in my case is. I've seen some people use asyncio but I don't lnow how I could use it in here. I think the last part of the script is the most important one so the code before is not significant but I still put it in. Thanks for helping me already!
@commands.command()
async def play(self, ctx, *, keywords: str):
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3") #Removing song if old one is in directory
except PermissionError:
await ctx.send("`Wait for the current playing music to end or use the 'stop' command.`")
return #Can't delete because song is playing at the moment
if ctx.author.voice and ctx.author.voice.channel:
channel = ctx.author.voice.channel
if not self.bot_is_connected(ctx):
await channel.connect() #Joining channel if it hasn't happened yet
else:
pass
else:
await ctx.send("`You are not connected to a voice channel.`")
if ctx.author.voice and ctx.author.voice.channel:
video = get_url(f"{keywords}") #Getting Song URl from Youtube using an imported request
print(video)
voice = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([video]) #Downloading song
meta = ydl.extract_info(video, download=False)
video_name = (meta["title"])
for file in os.listdir("./"):
if file.endswith(".mp3"): #Renaming the song so that it can be found by the player
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3")) #Playing the song
question from:
https://stackoverflow.com/questions/65874029/discord-music-bot-im-python-adding-a-queue 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…