Discord.py(rewrite)如何检查漫游器是否已经在您要加入的频道中?

问题描述 投票:0回答:1

我在让我的漫游器检查是否已经被要求加入频道时遇到了一些麻烦。

仅作为示例,这是一些代码:

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()

我面临的问题是,如果在僵尸程序仍在语音通道中时我使用命令>声音,我会收到一条错误消息,指出该僵尸程序已在通道中。我尝试比较客户端通道和用户通道,如果它们相同,则断开连接,然后重新连接以避免该错误,但我做对了。这是我尝试过但没有起作用的方法:

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个回答
1
投票

您可以通过VoiceClient在该行会中获得机器人的ctx.voice_client。然后,您可以在通道之间移动该客户端(如果已经存在,则不执行任何操作),或者如果不存在,则通过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()
© www.soinside.com 2019 - 2024. All rights reserved.