python - 如何改进我的队列系统 - Discord.py

标签 python discord discord.py bots youtube-dl

我创建了这个音乐机器人,我想改进我的队列命令,因为它目前不是很实用。每次我将一首歌排队时,我都必须使用播放命令来播放它,但我想自动播放下一首歌曲,将队列命令实现到播放命令中也很酷,但我不知道如何去做吧。
你能帮忙吗??

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)
如您所见,有一个参数可用于在机器人完成将音频播放到语音 channel 后执行操作。我建议您使用 after= 更改代码以递归播放下一首歌曲,而不是按照您目前的方式使用它。范围。您可以通过将 lambda 中的当前打印语句更改为异步调用 play 来实现此目的。再次发挥作用。
我还想指出,在学习如何使用 del() 的同时函数非常适合学习如何优化代码,但这并不是您想要实现它的方式。在这种情况下,您应该改为 .pop()将其从队列中取出的值(例如: queue.pop(0) 。您还应该知道弹出值会返回值,因此您可以直接将其实现到 YTDLSource.from_url() 函数的第一个参数中)。
我可以提供的最后一条信息是您为队列系统编写了一个类。显然,这实际上不会改变您解决问题所需要做的事情,但是学习如何编写 OOP 对象和类将在 future 对您有所帮助,并且由于它变得更有条理,它还使编写代码变得更加容易。
总结一下:
  • 首先删除 del(queue[0]) ,而是交换 queue[0] from_url()中的参数值方法与 queue.pop(0) .
  • 最佳情况下,您应该更改整个 queue带有 Queue 类的数组,因为您可以很容易地向其中添加方法和其他有用的包装函数,但这不是必须的。
  • 最后,代替 lambda 中的打印语句(在 .play() 方法的 after 参数中),异步调用 play再次发挥作用。 (例如,像这样- lambda e: await play(ctx) )
  • 关于python - 如何改进我的队列系统 - Discord.py,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67284492/

    相关文章:

    python - 如何让机器人每 5 分钟或由于其他事件发布/发送一条消息?

    python - 可以在不使用括号的情况下调用单参数 Python 函数吗?

    python - Gmail API 是否支持使用 OAuth 服务帐户?

    discord - 如何回复发送给机器人的私信?

    javascript - 通过变量访问对象

    javascript - 离开命令 Discord JS

    javascript - 从 Django 的 javascript 函数中获取 map 坐标的最快方法

    python - 将图像临时存储在 Google App Engine 中?

    python - 如何使用 discord.py 事件处理程序 on_voice_state_update 仅在用户加入语音 channel 时运行

    python - 用户输入给出 “ValueError: invalid literal for int() with base 10:”