(Python) Discord bot 与语音聊天断开连接

Cen*_*red 3 python discord discord.py

我需要知道如何使不和谐机器人与语音通道断开连接。目前这是我必须加入语音频道的代码

@client.command(pass_context=True)
async def joinvoice(ctx):
    #"""Joins your voice channel"""
    author = ctx.message.author
    voice_channel = author.voice_channel
    await client.join_voice_channel(voice_channel)
Run Code Online (Sandbox Code Playgroud)

我需要从语音通道断开连接的代码

Wri*_*ght 6

您将需要从 返回的语音客户端对象await client.join_voice_channel(voice_channel)。这个对象有一个方法disconnect()可以让你做到这一点。客户端还有一个属性voice_clients,它返回所有连接的语音客户端的迭代,如文档所示。考虑到这一点,我们可以添加一个名为 leavevoice 的命令(或您想调用的任何名称)。

@client.command(pass_context=True)
async def joinvoice(ctx):
    #"""Joins your voice channel"""
    author = ctx.message.author
    voice_channel = author.voice_channel
    vc = await client.join_voice_channel(voice_channel)

@client.command(pass_context = True)
async def leavevoice(ctx):
    for x in client.voice_clients:
        if(x.server == ctx.message.server):
            return await x.disconnect()

    return await client.say("I am not connected to any voice channel on this server!")
Run Code Online (Sandbox Code Playgroud)

leavevoice命令中,我们遍历了机器人连接的所有语音客户端,以便找到该服务器的语音通道。一旦发现,断开连接。如果没有,则机器人未连接到该服务器中的语音通道。