【问题标题】:Discord.py (rewrite) How to check if the bot is already in the channel you're asking it to join?Discord.py(重写)如何检查机器人是否已经在您要求它加入的频道中?
【发布时间】:2020-01-07 06:38:18
【问题描述】:

我在让我的机器人检查它是否已经在它被要求加入的频道中时遇到了一点麻烦。

作为一个例子,这是一段代码:

async def _sound(self, ctx:commands.Context):
   voice_channel = None
   if ctx.author.voice != None:
        voice_channel = ctx.author.voice.channel

   if voice_channel != None:
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio('sound.mp3'))
        await asyncio.sleep(5)
        await vc.disconnect()

我面临的问题是,如果我在机器人仍在语音通道中时使用命令 >sound,我会收到一条错误消息,指出机器人已经在通道中。我尝试比较客户端通道和用户通道,如果它们相同,请断开连接然后重新连接以避免错误,但我无法正确处理。这是我尝试过但没有奏效的方法:

voice_client = ctx.voice_client
if voice_client.channel.id == voice_channel.id:
        await voice_channel.disconnect
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio('sound.mp3'))
        asyncio.sleep(4)
        await vc.disconnect()

【问题讨论】:

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


    【解决方案1】:

    您可以通过ctx.voice_client 获得该公会中机器人的VoiceClient(如果有)。然后,您可以在通道之间移动该客户端(如果它已经存在,则不会执行任何操作),或者如果它不存在,则通过 voice_channel.connect 创建一个新客户端:

    @commands.command()
    async def _sound(self, ctx):
        if ctx.author.voice is None or ctx.author.voice.channel is None:
            return
    
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            vc = await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)
            vc = ctx.voice_client
    
        vc.play(discord.FFmpegPCMAudio('sound.mp3'))
        await asyncio.sleep(5)
        await vc.disconnect()
    

    【讨论】:

    • 为此欢呼,但这似乎产生了与我得到的相同的错误。当机器人不在频道中时它工作正常但是当机器人仍在频道中时正在使用命令时我收到错误Command raised an exception: AttributeError: 'NoneType' object has no attribute 'play'
    • @ConnorPrice 我的错误,move_to 没有返回任何内容。试试更新的代码?
    • 完美,排序完毕。
    猜你喜欢
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 2020-08-30
    • 2021-12-13
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多