从用户 ID discord.py 获取语音通道 ID

时间:2021-04-16 20:59:29

标签: python discord

我的问题是,如果我知道用户的用户 ID,我如何在不输入任何聊天内容的情况下获取用户所在的语音频道 ID。

示例代码:

USER_ID = 1234578654

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

分步骤

  1. 找出用户在哪个频道中使用了 id
  2. 加入该频道

1 个答案:

答案 0 :(得分:1)

您可以尝试通过 member 参数获取频道。您现在可以使用用户的名称或 ID。

看看下面的例子:

@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

我们做了什么?

  • 获取discord.Member的语音频道。
  • 如果成员在语音频道中,则连接到频道。
  • 如果 member 未连接到频道,则发出错误消息。

要定义用户,您可以使用以下函数:

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

有关详细信息,您还可以查看 docs