如何检查机器人已连接的语音通道ID? (discord.py)

时间:2020-05-19 21:18:25

标签: python discord discord.py discord.py-rewrite

我有一个机器人,只有当用户在同一语音通道中调用命令时,我才想听命令。这是我的代码。

@bot.command(name='leave', help='Disconnects the bot.')
async def leave(ctx):
    user_channel = ctx.message.author.voice.channel
    bot_channel =  ctx.guild.voice_client
    print(user_channel)
    print(bot_channel)
    if user_channel == bot_channel:
        client = ctx.guild.voice_client
        await client.disconnect()
    else:
        await ctx.send('You have to be connected to the same voice channel to disconnect me.')

但是,我的问题是这些打印行返回不同的字符串。用户通道:vc 2,Bot通道:<\ discord.voice_client.VoiceClient对象位于0x000001D4E168FB20> 我怎样才能让他们两个都读取语音通道的ID,以便进行比较?

1 个答案:

答案 0 :(得分:2)

代码的唯一问题是您正在将用户的当前语音通道对象与语音客户端对象进行比较。您可以在.channel的末尾添加ctx.guild.voice_client

比较两个通道对象将与比较通道的ID相同。如果您真的想通过它们的ID来比较它们,则只需将.id添加到每个ID。

示例:

@bot.command(help='Disconnects the bot.')
async def leave(ctx):
    if ctx.author.voice.channel and ctx.author.voice.channel == ctx.voice_client.channel:
                                  # comparing channel objects ^

        await ctx.voice_client.disconnect()
    else:
        await ctx.send('You have to be connected to the same voice channel to disconnect me.')

请注意,我添加了ctx.author.voice.channel and,以便在命令执行程序和bot都不在通道中时,您不会遇到属性错误。

如果您不检查其中一个对象不是None,则会收到一个错误消息,指出NoneType没有属性disconnect()作为表达式{{ 1}}将是None == None并运行该语句。


参考: