我创建了这个音乐机器人,我想改进我的队列命令,因为它目前功能不太好。每次我将一首歌排队时,我都必须使用play命令来播放它,但我想自动播放下一首歌,而且将queue命令实现到play命令中也很酷,但我不知道如何做。 你能帮忙吗
youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}
ffmpeg_options = {
'options': '-vn'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
queue = []
@client.command(name='queue', help='This command adds a song to the queue')
async def queue_(ctx, url):
global queue
queue.append(url)
await ctx.send(f'`{url}` added to queue!')
@client.command(name='play', help='This command plays songs')
async def play(ctx):
global queue
server = ctx.message.guild
voice_channel = server.voice_client
async with ctx.typing():
player = await YTDLSource.from_url(queue[0], loop=client.loop, stream=True)
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
await ctx.send('**Now playing:** {}'.format(player.title))
del(queue[0])
编辑:所以我试着做一些类似的事情,但它不工作,当我试图使用!播放一首歌曲时,它不会将其放入队列,它表示:ClientException: Already playing audio.
当歌曲播放完毕时,它表示:TypeError: next() missing 2 required positional arguments: 'queue' and 'song'
代码如下:
queue = []
def next(client, queue, song):
if len(queue)>0:
new_song= queue[0]
del queue[0]
play(client, queue, new_song)
@bot.command()
async def join (ctx):
member = ctx.author
if not ctx.message.author.voice:
await ctx.send(f"{member.mention} You are not connected to a voice channel ❌")
else:
channel=ctx.message.author.voice.channel
await channel.connect()
@bot.command(help="This command plays a song.")
async def play (ctx,*args):
server = ctx.message.guild
voice_channel= server.voice_client
url=""
for word in args:
url+=word
url+=''
async with ctx.typing():
player = await YTDLSource.from_url(url ,loop=bot.loop, stream=True)
queue.append(player)
voice_channel.play (player, after=lambda e: next(ctx))
await ctx.send(f"**Now playing:** {player.title}")
在异步
play
函数中,您有以下代码行:如您所见,有一个参数可用于在机器人完成向语音频道播放音频后执行动作。我建议您改变代码,使用
after=
参数递归播放下一首歌曲,而不是像现在这样使用它。可以通过将lambda中的当前print语句更改为再次异步调用play
函数来实现这一点我还想指出,虽然学习如何使用
del()
函数对于学习如何优化代码非常有用,但这并不是您想要实现它的方式。在这种情况下,您应该使用.pop()
值将其从队列中取出(如:queue.pop(0)
。您还应该知道,弹出该值将返回该值,因此可以将其直接实现到YTDLSource.from_url()
函数的第一个参数中)我能提供的最后一点信息是,您为队列系统编写了一个类。显然,这实际上不会改变解决问题所需的操作,但是学习如何编写OOP对象和类将在将来对您有所帮助,而且它还可以使编写代码变得更容易,因为它变得更有条理
总结如下:
del(queue[0])
,并将from_url()
方法中的queue[0]
参数值替换为queue.pop(0)
李>queue
数组,因为您可以非常轻松地向其中添加方法和其他有用的包装函数,但这不是必须的李>.play()
方法的after
参数中),而是再次异步调用play
函数。(例如,像so-lambda e: await play(ctx)
)相关问题 更多 >
编程相关推荐