问题
Summary
I'm really new to discord.py and am trying to figure out how to retrieve a list of people in a discord server channel. I'm working on a command that would randomly separate the channel into two different calls, but I am wondering how I would retrieve the members in a voice channel, create a list of the members, randomly split them, and lastly move the members.
My main concern right now is just retrieving a list of members into a list [] format
this is what I have so far:
async def team(ctx):
team_select = [discord.VoiceChannel.members(ctx.guild.channels, id=742871631751282829)]
print(team_select)
^ this code, which I'm using to gives me the error: "TypeError: 'property' object is not callable"
回答1:
You can do this by using discord.utils.get. Here is an example. you can also use
await bot.fetch_guild(guild_id)
to get the guild object instead of ctx.guild
Note: bot.fetch_guild require you to use discord.ext.commands
@bot.command()
async def voice(ctx):
VC = discord.utils.get(ctx.guild.channels, id=705524214270132368)
print(VC.members) # each user is a member object
for user in VC.members:
# Code here
print(user.name)
回答2:
You can do this by VoiceChannel.members, but some things should be changed from Abdulaziz
's answer.
1.Use Bot.get_channel()
Use bot.get_channel if you have channel's ID or Guild.get_channel if you know in which Guild the channel is and have its ID, utils.get should be called only when you don't have ID.
get_ methods are O(1) while utils.get is internally a for loop, therefore O(n).
If you're not familiar with big O notation, O(1) means operation time is the same with any number of items while O(n) is linear, the more items there are, the longer it takes.
Read more about
O(n) vs O(1)
here.
2. Use Bot.get_guild()
fetch_guild is an API call and can get your bot rate-limited soon while get_guild is not an API call.
Using the Guild object returned by fetch_guild will not give you the guild's channels.
Read more about it in the documentation here.
Here is the revised code:
@bot.command()
async def team(ctx):
vc = ctx.guild.get_channel(742871631751282829)
await ctx.send("\n".join([str(i) for i in vc.members]))
来源:https://stackoverflow.com/questions/63367489/retrieve-list-of-members-in-channel-discord-py-rewrite