如何获取Discord成员对应的用户对象?解决授予角色时“member没有添加角色的引用”错误
Alright, let's work through your Discord.py issues step by step—first fixing that role assignment error, then covering how to properly fetch a member object.
The root of this problem is that your current member parameter is just a plain string, not an actual discord.Member object. Discord.py can't call role-related methods on a string, hence the error.
To fix this, you need to add a type hint to the member parameter so Discord.py automatically converts the user's input (like a mention, user ID, or username) into a discord.Member instance. You should do the same for the rank parameter if you want to work directly with a discord.Role object instead of a role name string.
Here's the revised command code:
# Note: pass_context=True is deprecated in newer Discord.py versions, you can omit it @commands.command() async def grant(self, ctx, member: discord.Member, rank: discord.Role): # Now you can safely call add_roles on the member object await member.add_roles(rank) await ctx.send(f"Successfully assigned the {rank.name} role to {member.display_name}!")
A couple extra notes:
- Make sure your bot has the Manage Roles permission in the server, and its own role is positioned higher than the role you're trying to assign (otherwise Discord will block the action).
- If you need to handle cases where the role is provided as a name string (not a mention/ID), you can use
discord.utils.getto fetch the role from the guild first:rank = discord.utils.get(ctx.guild.roles, name=rank) if not rank: await ctx.send("That role doesn't exist in this server!") return
There are several reliable ways to fetch a discord.Member instance depending on your use case:
- Command parameter type hint: As shown above, adding
: discord.Memberto your command parameter lets Discord.py handle the conversion automatically when the user mentions a member, inputs their ID, or uses their unique username. - Fetch by user ID: If you have a user's numeric ID, use either:
# Uses cached member data (faster, but only works if the member is online/recently active) member = ctx.guild.get_member(user_id) # Fetches directly from Discord API (works for offline members, but requires an API call) member = await ctx.guild.fetch_member(user_id) - Search by username/nickname: Use
discord.utils.getto look up a member by their base username or server nickname:
Keep in mind this will return the first matching member if there are duplicates.# Search by base username member = discord.utils.get(ctx.guild.members, name="JohnDoe") # Search by server-specific nickname member = discord.utils.get(ctx.guild.members, display_name="Johnny") - Get the command author: If you need the member who ran the command, just use
ctx.author:author_member = ctx.author
内容的提问来源于stack exchange,提问作者user17109763

