2
votes

I've got a bot that I want to listen to a command only if the user calling it is in the same voice channel. Here is my code.

@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.')

However, my issue is that those print lines return different strings. User channel: vc 2, Bot channel: <\discord.voice_client.VoiceClient object at 0x000001D4E168FB20> How can I get them both to read the ID of the voice channel so I can compare them?

1

1 Answers

3
votes

The only issue with your code was that you were comparing the user's current voice channel object to the voice client object. You could've added .channel to the end of ctx.guild.voice_client.

Comparing the two channel objects will do just the same as comparing the channels' IDs. If you really want to compare them by their IDs, then just add on .id to each of them.

Example:

@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.')

Please note that I added ctx.author.voice.channel and so that you don't run into an attribute error if both the command executor and bot aren't in channels.

If you weren't to check that one of the objects aren't None, then you would get an error saying that NoneType has no attribute disconnect() as the expression None == None would be True and run the statement.


References: