用户离开后如何断开不和谐机器人与语音通道的连接?

时间:2021-01-07 14:33:19

标签: asynchronous discord discord.py youtube-dl

我想添加一个事件,如果用户在歌曲仍在播放时离开,我的音乐机器人会立即离开语音频道。如果频道中有多个用户,机器人当然应该留在频道中。我只有一种方法,但需要帮助。我会尝试以下操作:

async def check_member(self, ctx):
    channel = ctx.author.voice.channel
    member_count = len(voice_channel.members)
    if member_count == 1:
        await channel.disconnect

但不知何故这似乎不起作用。 我确实知道有一个 similar post 但这对我也不起作用,因为我定义了一些不同的东西。

我的第二次尝试是:

    async def check_member(self, ctx):
        channel = ctx.author.voice.channel
        member_count = len(channel.members)
        client = ctx.guild.voice_client
        if member_count == 1:
            await client.disconnect()

(也没有用。)

定义 does not work:我现在以不同的方式构建函数:

    @tasks.loop(seconds=2)
    async def check(self, ctx):
        voice_channel = ctx.author.voice.channel
        member_count = len(voice_channel.members)
        client = ctx.guild.voice_client
        if member_count == 1:
            await client.disconnect()

这现在完全不同了。我想要做的是每 2 秒循环一次 commands.Cog.listener() 函数。为了测试,我播放了一首歌并在机器人开始播放后立即离开。我以为机器人也会离开频道,但它没有。我的日志中没有输出我定义错误的内容。

1 个答案:

答案 0 :(得分:0)

一个环是有点儿效率不高,就可以简单地使用on_voice_state_update事件

async def on_voice_state_update(member, before, after):
    voice_state = member.guild.voice_client
    # Checking if the bot is connected to a channel and if there is only 1 member connected to it (the bot itself)
    if voice_state is not None and len(voice_state.channel.members) == 1:
        # You should also check if the song is still playing
        await voice_state.disconnect()

参考: