【问题标题】:How can you check voice channel id that bot is connected to? (discord.py)如何检查机器人连接的语音通道 ID? (discord.py)
【发布时间】:2020-09-06 02:26:01
【问题描述】:

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

@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,机器人频道: 我怎样才能让它们都读取语音通道的 ID,以便我可以比较它们?

【问题讨论】:

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


    【解决方案1】:

    您的代码的唯一问题是您将用户当前的语音通道对象与语音客户端对象进行比较。您可以将.channel 添加到ctx.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并运行语句。


    参考资料:

    【讨论】:

    • 就是这样!谢谢!
    • 很高兴听到这个消息!如果您不介意accepting 的答案,因为它将帮助其他有相同问题的人更快地找到他们的解决方案!祝机器人好运:)
    猜你喜欢
    • 2020-12-18
    • 2020-05-31
    • 2021-08-05
    • 1970-01-01
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多