【发布时间】:2021-11-28 07:51:34
【问题描述】:
我目前正在使用 discord.py 创建一个不和谐的机器人来播放音乐。
使用“-play”命令时,机器人应该播放指定的歌曲。如果在机器人当前播放时播放歌曲,则会将其添加到队列中,一旦歌曲播放完毕,就会播放歌曲。
如果在另一首歌曲完成后请求指定歌曲,则无论如何它都应该简单地播放指定歌曲。
但是,目前,机器人只实现了两者中的第一个。虽然如果在另一首歌曲期间排队,歌曲确实会播放......在另一首歌曲完成后使用“-play”命令时,它仍会将歌曲添加到队列中。播放歌曲的唯一方法是“跳过”当前播放的歌曲,即使没有听到任何声音。
相关代码如下:
class Player(commands.Cog):
def __init__(self,bot):
self.bot = bot
self.song_queue = {}
self.setup()
def setup(self):
for guild in self.bot.guilds:
self.song_queue[guild.id] = []
async def check_queue(self,ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.bot.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#other code...
@commands.command()
async def play(self, ctx, *, song=None):
if song is None:
return await ctx.send("Gotta tell me what to play before I can bust out the music")
if ctx.voice_client is None:
return await ctx.send("Come on bud, why would I sing my tunes if you're not even listening!?")
if not("youtube.com/watch?" in song or "https:youtu.be/" in song):
await ctx.send("Searching for song, gonna have to wait a sec")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Are you sure this is really a song? Maybe try search for it with my command, =play insert song name here")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"The song's been added to your queue, position {queue_len+1}.")
await self.play_song(ctx, song)
await ctx.send(f"Tonight I'll be listening to {song}")
【问题讨论】:
标签: python discord discord.py audio-streaming