且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

(Python) Discord 机器人与语音聊天断开连接

更新时间:2023-02-22 20:23:59

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

You'll need the voice client object which is returned from await client.join_voice_channel(voice_channel). This object has a method disconnect() which allows you to do just that. The client also has an attribute voice_clients which returns an iterable of all the connected voice clients as can be seen at the docs. With that in mind, we can add a command called leavevoice (or whatever you want to call it).

@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!")

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

Here in the leavevoice command, we looped over all the voice clients the bot is connected to in order to find the voice channel for that server. Once found, disconnects. If none, then the bot isn't connected to a voice channel in that server.