Discord py 删除语音通道,如果它是空的

Discord py delete voicechannel if its empty

好吧,我正在尝试通过命令创建一个语音频道,以便我可以加入。 一旦我离开频道,它就会被删除。

我尝试了什么:

if message.content.startswith('/voice'):
    guild = message.guild
    voicechannel = await guild.create_voice_channel(f"{str(message.author)}")
    await asyncio.sleep(5)

    while True:
       if len(voicechannel.voice_states) == 0:
           await voicechannel.delete()
           break

甚至没有用

我认为您的问题在于您陷入了无限 while True 循环。我首先建议您改用 discord.ext.commands,它大大简化了创建 Discord Bot 的过程。如果您使用的是 discord.ext.commands.Bot,您可以使用 wait_for() 功能等待语音通道为空。

from discord.ext.commands import Bot

client = Bot(command_prefix="/")

@client.command(name="voice")
async def voice(ctx):
    guild = ctx.guild
    voice_channel = await guild.create_voice_channel(f"{str(ctx.author)}")

    def check(member, before, after):
        return member == ctx.author and before.channel == voice_channel and after.channel is None

    await client.wait_for("voice_state_update", check=check)
    await voice_channel.delete()

client.run("TOKEN")

我认为唯一可能发生的问题是成员从未加入语音频道。为了解决这个问题,我们可以设置另一个 wait_for() 函数来确定成员是否在等待成员离开语音频道之前加入。

from asyncio import TimeoutError

@client.command(name="voice")
async def voice(ctx):
    guild = ctx.guild
    voice_channel = await guild.create_voice_channel(f"{str(ctx.author)}")

    def check(member, before, after):
        return member == ctx.author and before.channel is None and after.channel == voice_channel

    try:
        await client.wait_for("voice_state_update", check=check, timeout=60)
    except TimeoutError:
        await voice_channel.delete()
        return