discord bot独自离开语音通道



我正在寻找代码,让我的机器人断开时,它是单独在一个语音通道,即使它正在播放音乐。我尝试了不同的代码片段,但它们都不起作用。这就是我所拥有的,但每当它检测到一个事件时,我就会得到一个错误。(它在一个齿轮中),我想在一个叫做music(music ._leave)的类中使用另一个叫做_leave的命令

@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
    if before.channel and len(before.channel.members) == 1:
        voice = get(bot.voice_clients, guild=member.guild)
        if voice is None:
            return
        else:
            #use _leave command

_leave代码:

@commands.command(name='leave', aliases=['l'])
async def _leave(self, ctx: commands.Context):
    if not ctx.voice_state.voice:
        embedVar = discord.Embed(title="",
                                 description='Not connected to any voice channel.',
                                 color=0x000000)
        return await ctx.send(embed=embedVar)
    await ctx.voice_state.stop()
    del self.voice_states[ctx.guild.id]

Guild.voice_client可以是None,如果机器人没有连接到语音通道,您可以使用简单的if语句检查它

@client.event
async def on_voice_state_update(member, before, after):
    voice_state = member.guild.voice_client
    if voice_state is None:
        # Exiting if the bot it's not connected to a voice channel
        return 
    if len(voice_state.channel.members) == 1:
        await voice_state.disconnect()

同时确保启用intents.voice_states

参考:

  • Guild.voice_client
  • Intents.voice_states

最新更新