首次完成 Discord Bot 后如何播放下一首歌曲
问题描述
我正在尝试使用 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."))
相关文章