SomeGuy
SomeGuy

Reputation: 89

Get voice channel id from user id discord.py

My question is how can i get the voice channel id a user is in without that person typing in any chats, if i know the persons user ID.

Example Code:

USER_ID = 1234578654

@bot.command()
async def join():
    account = bot.get_user(USER_ID)
    channel = account.voice.channel
    voice = await channel.connect()

In steps

  1. Figure out which channel a user is in with there id
  2. join that channel

Upvotes: 1

Views: 9426

Answers (1)

Dominik
Dominik

Reputation: 3592

You can try and get the channel by the member argument. You can now either use the name or ID of the user.

Take a look at the following example:

@bot.command()
async def join(ctx, member : discord.Member):
    try:
        channel = member.voice.channel
        if channel: # If user is in a channel
            await channel.connect() # Connect
            await ctx.send("User is connected to a channel, joining...")
        else:
            await ctx.send("I am already connected to a channel.") # If the bot is already connected
    except AttributeError:
        return await ctx.send("User is not in a channel, can't connect.") # Error message

What did we do?

  • Get the voice channel of discord.Member.
  • Connect to the channel if the member is in a voice channel.
  • Give out an error if the member is not connected to a channel.

To define a user you can use the following function:

from discord.utils import get

@bot.command()
async def join(ctx):
    try:
        member = ctx.guild.get_member(YourID) # Get the member by ID
        if member:  # If it is the defined member
            await member.voice.channel.connect()  # Connect
            return await ctx.send("User is connected to a channel, joining...")
        else:
            await ctx.send("Not the defined user.")
    except AttributeError:
        return await ctx.send("The defined user is not in a channel.")  # Error message

For more information you can also look at the docs

Upvotes: 1

Related Questions