让机器人在语音聊天 discord.py 中播放 YouTube 视频

时间:2021-02-01 12:50:48

标签: python discord discord.py

我正在尝试让我的机器人能够加入语音聊天,离开他们,还能够通过命令链接播放 YouTube 视频。这是我到目前为止得到的代码。加入和离开都没有问题。试图从“播放”命令中获取链接对我来说有点困难

class Voice(commands.Cog):
    def init(self, bot):
      self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        print("VoiceCog loaded")

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.content.casefold().startswith("join voice rachel"):
            channel = message.author.voice.channel
            server = message.guild
            await channel.connect() #join voicechat cmd

        elif message.content.casefold().startswith("leave voice rachel"):
            channel = message.guild.voice_client
            await channel.disconnect() #leave voicechat cmd

        elif message.content.casefold().startswith("rachel play"):
            channel = message.author.voice.channel
            player = await channel.create_ytdl_player(url)
            player.start() #this would be the play youtube-link cmd
        else:
            return

我总是使用 on_message,因为它更适合我使用机器人的目的。我也用 ctx 尝试过,但结果并不好 :D

提前致谢!

1 个答案:

答案 0 :(得分:0)

您需要解析消息以提取 url。所以你可以使用空格分割字符串。例如,您可以执行以下操作:

parts = message.content.split()
url = parts[-1] #Assuming the last item in the message is the url

顺便说一句,您的 on_message 事件应该有装饰器 @commands.Cog.listener() 而不是 commands.command() 装饰器。