我的discord 机器人不会与语音通道断开连接

问题描述 投票:0回答:1

我正在使用 .py 制作一个不和谐的机器人,我有很多“on_message”的东西,我让它们工作,来自不同的文件和东西,现在的问题是我现在正在使用“on_voice_state_update”,它检测是否用户加入/离开语音频道(就我而言)

现在我有这个代码:

@client.event
async def on_voice_state_update(member, before, after):
    if after.channel and before.channel is None:
        if not client.voice_clients:
            await after.channel.connect()

它有效,它的作用是,当我加入语音频道时,我的机器人也会加入同一个语音频道(它之前没有加入过),

我有一个问题,当该通道没有用户时,我不知道如何让它离开语音通道(当然不考虑机器人)

我已经使用命令使其工作:

intents = discord.Intents.all()
intents.messages = True
intents.voice_states = True

client = commands.Bot(command_prefix = '!', intents = intents)

@client.command(pass_context = True)
async def join(ctx):
    if (ctx.author.voice):
        channel = ctx.message.author.voice.channel
        await channel.connect()
    else:
        await ctx.send("Try joining a voice channel yourself first!")

@client.command(pass_context = True)
async def leave(ctx):
    if (ctx.author.voice):
        await ctx.guild.voice_client.disconnect()
        await ctx.send("I have left the voice channel!")
    else:
        await ctx.send("I'm not in a voice channel!")

这样,当我说命令“!join”时,它会加入语音频道,“!leave”它会离开语音频道,但我不知道如何自动使其在频道(成员)空了,机器人也离开了

我已经尝试过了,但似乎不起作用

@client.event
async def on_voice_state_update(member, before, after):
    if after.channel and before.channel is None:
        if not client.voice_clients:
            await after.channel.connect()
    elif before.channel and after.channel is None:
        if member == client.user and len(before.channel.members) == 1:
            await before.channel.disconnect()
discord.py bots voice
1个回答
0
投票

您的解决方案似乎没问题,除了您正在检查

member
是否是
client.user
又名机器人本身,在这种情况下是错误的,因为机器人正在等待成员离开语音通道,而机器人它自己会留在那里直到每个人都离开:

elif before.channel and after.channel is None:
     if len(before.channel.members) == 1:
            await before.channel.disconnect()
© www.soinside.com 2019 - 2024. All rights reserved.