首页 > 解决方案 > 用户离开后如何断开不和谐机器人与语音通道的连接?

问题描述

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

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

但不知何故,这似乎不起作用。我知道事实上有一个类似的帖子,但这对我也不起作用,因为我定义了一些不同的东西。

我的第二次尝试是:

    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()

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

标签: asynchronousdiscorddiscord.pyyoutube-dl

解决方案


循环有点低效,您可以简单地使用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()

参考:


推荐阅读