0
votes

I'm having a little bit of trouble making my bot check if it's already in the channel it's being asked to join.

Just as an example, this is a bit of code:

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

The problem I'm facing is, if I use the command >sound while the bot is still in the voice channel, I get an error saying that the bot is already in the channel. I've attempted comparing the client channel and the user channel and if they're the same to disconnect and then reconnect avoiding the error but I can't get it right. This is what I tried but didn't work:

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

1 Answers

3
votes

You can get the VoiceClient of the bot in that guild (if any), through ctx.voice_client. You can then move that client between channels (which will do nothing if it's already there), or create a new client through voice_channel.connect if it doesn't exist:

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