我正在尝试使用 discord.py 创建一个 Discord 音乐机器人,我是 Python 新手.我不知道如何让 Bot 自动播放下一首歌曲.我尝试了很多不同的东西.这是我当前播放一首歌曲的代码:
I'm trying to create a Discord music Bot with discord.py, I'm new to Python. I don't know how to let the Bot automatically play the next song. I tried many different things. This is my current code for playing one song:
vc.play(discord.FFmpegPCMAudio(executable="C:/FFmpeg/bin/ffmpeg.exe", source=sound + ".mp3"))
await message.channel.send("Spiele nun " + str(sound) +"weiter")
使用上面的代码我没有遇到问题.
With the above code I didn't get a problem.
您应该使用 FFmpegPCMAudio
函数的 after
参数.此参数接受一个可调用对象作为参数,并在当前歌曲结束时执行它.
You should use the after
parameter of the FFmpegPCMAudio
function. This parameter takes a callable as an argument and executes it when the current song is over.
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()
函数更改为:
You can name the play_next()
function whatever you want.
If you want your bot to disconnect because it's been too long since it was playing sound, change the play_next()
function to :
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."))
这篇关于首次完成 Discord Bot 后如何播放下一首歌曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!