我正在尝试使用discord.py创建一个Discord音乐Bot,我是Python的新手。 我不知道如何让Bot自动播放下一首歌曲。我尝试了许多不同的事情。 这是我当前播放一首歌曲的代码:
vc.play(discord.FFmpegPCMAudio(executable="C:/FFmpeg/bin/ffmpeg.exe", source=sound + ".mp3"))
await message.channel.send("Spiele nun " + str(sound) +"weiter")
使用上面的代码,我没有遇到任何问题。
答案 0 :(得分:1)
您应该使用after
函数的FFmpegPCMAudio
参数。此参数将callable作为参数,并在当前歌曲结束时执行。
song_queue = []
play()
函数:source = sound + '.mp3'
soung_queue.append(source)
if not vc.is_playing():
vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
await ctx.send("Now playing...")
else:
await ctx.send('Song queued')
play_next()
函数:import asyncio
def play_next(ctx, source):
if len(self.song_queue) >= 1:
del self.song_queue[0]
vc = get(self.bot.voice_clients, guild=ctx.guild)
vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."))
您可以根据需要命名play_next()
函数。
如果您希望机器人从播放声音到现在已经太久而断开连接,请将play_next()
函数更改为:
import asyncio
def play_next(ctx, source):
vc = get(self.bot.voice_clients, guild=ctx.guild)
if len(self.song_queue) >= 1:
del self.song_queue[0]
vc.play(discord.FFmpegPCMAudio(source=source, after=lambda e: play_next(ctx))
else:
asyncio.sleep(90) #wait 1 minute and 30 seconds
if not vc.is_playing():
asyncio.run_coroutine_threadsafe(vc.disconnect(ctx), self.bot.loop)
asyncio.run_coroutine_threadsafe(ctx.send("No more songs in queue."))