首页 > 解决方案 > 如何检查机器人连接的语音通道 ID?(discord.py)

问题描述

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

@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,机器人通道:<\discord.voice_client.VoiceClient object at 0x000001D4E168FB20> 如何让它们都读取语音通道的 ID,以便比较它们?

标签: pythondiscorddiscord.pydiscord.py-rewrite

解决方案


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

比较两个通道对象的作用与比较通道的 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如果命令执行器和机器人都不在通道中,我添加了这样您就不会遇到属性错误。

如果您不检查其中一个对象是否不是None,那么您会收到一条错误消息,指出NoneType没有disconnect()像表达式None == None那样的属性True并运行该语句。


参考:


推荐阅读