Discord Bot 不会告诉某人加入语音频道,而只是抛出一个错误。其他部分工作完全正常

Discord Bot won't tell someone to join a voice channel, instead it just throws an error. Other parts work totally fine

我为我的 Discord 机器人开发这个功能已经有一段时间了,终于搞定了大部分 运行,但是我 运行 遇到了我的“Connect”的问题到语音频道”警告。代码段如下:

 @commands.command(name="play", help="Plays a selected song from youtube")
    async def p(self, ctx, *args):
        query = " ".join(args)
        
        voice_channel = ctx.message.author.voice.channel
        if voice_channel is None:
            #you need to be connected so that the bot knows where to go
            await message.channel.send("Connect to a voice channel!")
        else:
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])

现在,除了“如果 voice_channel 是 None”部分,这一切似乎都运行良好。不断抛出错误,提示“NoneType' 对象没有属性 'channel'”。

我确定这很简单,我理解问题的要点(显然这不是我第一次看到 'NoneType' 对象错误,但我似乎无法弄清楚是什么我这里需要改一下。

正如我之前所说,只要我在语音频道中,一切都会完美无缺。机器人连接、下载和播放音乐。

您需要像这样使用 try:

@commands.command(name="play", help="Plays a selected song from youtube")
    async def p(self, ctx, *args):
        query = " ".join(args)
        try:
            voice_channel = ctx.message.author.voice.channel
            song = self.search_yt(query)
            if type(song) == type(True):
                await ctx.send("Could not download the song. Incorrect format try another keyword. This could be due to playlist or a livestream format.")
            else:
                await ctx.send("Song added to the queue")
                self.music_queue.append([song, voice_channel])
        except:
            await message.channel.send("Connect to a voice channel!")

如果用户不在语音通道中,语音将为None,因此将没有属性“语音”。

尝试:

voice_channel = ctx.message.author.voice.channel if ctx.message.author.voice else None

https://discordpy.readthedocs.io/en/stable/api.html#discord.VoiceState