How to get the sum and the names of all the users

2020-05-10 12:00发布

问题:

I use :

import discord

I need to get from each voice channel amount all users and then get their names (usernames). How to do it?

回答1:

You need to access the voice channel object. I recommend you use the voice channel's id. The command could look as follows:

@client.command(pass_context = True)
async def vcmembers(ctx, voice_channel_id):
    #First getting the voice channel object
    voice_channel = discord.utils.get(ctx.message.server.channels, id = voice_channel_id)
    if not voice_channel:
        return await client.say("That is not a valid voice channel.")

    members = voice_channel.voice_members
    member_names = '\n'.join([x.name for x in members])

    embed = discord.Embed(title = "{} member(s) in {}".format(len(members), voice_channel.name),
                          description = member_names,
                          color=discord.Color.blue())

    return await client.say(embed = embed)

And would work like this:

Where the number at the end is the channel id. If you don't know how to get the channel id, right click the channel and click Copy ID.

If you can't see the Copy ID, turn on Developer Mode in your Settings > Appearance > Developer Mode



回答2:

You can also get all the members of a voice channel like this (updated for discord.py versions 1.0.0+):

@client.command(brief="returns a list of the people in the voice channels in the server",)
async def vcmembers(ctx):
    #First getting the voice channels
    voice_channel_list = ctx.guild.voice_channels

    #getting the members in the voice channel
    for voice_channels in voice_channel_list:
        #list the members if there are any in the voice channel
        if len(voice_channels.members) != 0:
            if len(voice_channels.members) == 1:
                await ctx.send("{} member in {}".format(len(voice_channels.members), voice_channels.name))
            else:
                await ctx.send("{} members in {}".format(len(voice_channels.members), voice_channels.name))
            for members in voice_channels.members:
                #if user does not have a nickname in the guild, send thier discord name. Otherwise, send thier guild nickname
                if members.nick == None:
                    await ctx.send(members.name)
                else:
                    await ctx.send(members.nick)