python - 如何改进我的队列系统 - Discord.py
问题描述
我创建了这个音乐机器人,我想改进我的队列命令,因为它目前不是很实用。每次我排队一首歌我都必须使用播放命令来播放它,但我想自动播放下一首歌曲,在播放命令中实现队列命令也很酷,但我不知道如何去做吧。你能帮忙吗??
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])
编辑:所以我尝试做这样的事情,但它不起作用,当我尝试使用 !play 播放歌曲时它不会将它放入队列中,它说: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
函数中,您有以下代码行:
voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
如您所见,有一个参数可用于在机器人完成向语音通道播放音频后执行操作。我建议您更改代码以使用after=
参数递归播放下一首歌曲,而不是按照您目前的方式使用它。您可以通过将 lambda 中的当前打印语句更改为play
再次异步调用该函数来做到这一点。
我还想指出,虽然学习如何使用该del()
函数非常适合学习如何优化代码,但这并不是您想要实现它的方式。在这种情况下,您应该改为.pop()
将值从队列中取出(就像这样:queue.pop(0)
。您还应该知道弹出值会返回值,因此您可以直接将其实现到YTDLSource.from_url()
函数的第一个参数中)。
我可以提供的最后一点信息是您为队列系统编写了一个类。显然,这实际上不会改变您解决问题所需要做的事情,但是学习如何编写 OOP 对象和类将对您将来有所帮助,并且由于它变得更有条理,它也使编写代码更容易。
总结一下:
- 首先删除,然后将方法中的参数值
del(queue[0])
替换为。queue[0]
from_url()
queue.pop(0)
- 最佳情况下,您应该使用 Queue 类更改整个
queue
数组,因为您可以很容易地向其中添加方法和其他有用的包装函数,但这不是必须的。 - 最后,代替 lambda 中的 print 语句(在
.play()
方法的after
参数中),再次异步调用该play
函数。(例如,像这样lambda e: await play(ctx)
- )
推荐阅读
- javascript - Stripe js + React/JS 在条带重定向后访问数据
- r - R中我的for循环函数的并行处理
- java - 每次我要求我的 JPanel 重新绘制时,它都不会重新绘制
- javascript - Bcrypt 比较总是返回 false
- rgraph - 更改条形值而不重绘整个图表
- amazon-s3 - 在整个 S3 存储桶上运行 AWS MediaConvert 作业
- python - Pyautogui:我必须手动移动鼠标才能让 pyautogui 点击
- android - 如何使用 Jsoup 提取图片链接?
- google-apps-script - 如何在新的 google appscript 界面上缩进代码?
- postgresql - 如何加快分区表中的选择查询?