首页 > 解决方案 > 如何构建自动播放音乐机器人 Discord.py

问题描述

我想建立一个自动播放音乐机器人。我有一首歌曲,我希望机器人在当前歌曲结束后自动播放下一首歌曲。我怎样才能做到这一点?

    async def play(self, ctx, input: str):
        YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
        voice = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
        print(type(voice))
        # input = input.strip("<>")
        with YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(input, download=False)
        description = ""
        count = 0
        if "entries" in info.keys():
            for id, ent in enumerate(info["entries"]):
                count += 1
                self.queue.add(ent)
                description += f"{id}.  {str(ent['title'])[:70].rjust(80)}" + \
                               ("..." if len(ent['title'][70:]) else "") + \
                               f"`{ent['duration'] // 60}:{ent['duration'] % 60}`\n" if count < 4 else ""
        else:
            URL = info['formats'][0]['url']
            self.queue.add(info)
            description += f"1. {str(info['title'])[:70].rjust(80)}" + \
                           ("..." if len(info['title'][70:]) else "") + \
                           f"`{info['duration'] // 60}:{info['duration'] % 60}`\n"

        if not voice.is_playing() and re.match(URL_REGEX, input):
            voice.play(FFmpegPCMAudio(executable="ffmpeg.exe", source=self.queue._queue[self.queue.position]['url'],
                                      **Music.FFMPEG_OPTIONS))
            await ctx.send(embed=self.get_embed(ctx, self.queue._queue, [self.queue.position + 1, self.queue.length]))
        elif voice.is_playing():
            pass # some staff here

标签: pythondiscord.py

解决方案


你可以做的一件事是你可以有一个 async 函数,它有一段时间 True 并不断检查机器人是否没有播放任何内容,如果不是,则推进队列。

async def check(self, guild):
    while True:
        voice = discord.utils.get(self.client.voice_clients, guild=ctx.guild)
        if not voice.is_playing:
            self.queueIndex += 1
            await self.playNext()

然后制作一个使用 self.queueIndex 播放歌曲的 playNext 函数。抱歉,如果这不起作用,我还没有使用 Ydl 制作不和谐音乐机器人。


推荐阅读