Discord机器人静音切换命令报错:'Member'无'has_roles'属性求助
Fixing the AttributeError in Your Discord Mute/Unmute Command
Hey there! That error is popping up because discord.py's Member object doesn't have a has_roles() method—you're using a method that doesn't exist here. Let's fix that and polish up your command to avoid other potential issues too.
The Core Issue
Your line if member.has_roles(role): is invalid. Instead, to check if a member has a specific role, you need to verify if the role is present in the member's roles collection with:
if role in member.roles:
Updated, Robust Code
Here's the fixed version of your command, with extra safeguards to handle edge cases like missing roles or users without a server nickname:
@client.command() @commands.has_permissions(manage_messages=True) async def mute(ctx, member: discord.Member): # Get the Muted role from the server muted_role = discord.utils.get(member.guild.roles, name='Muted') # First, check if the Muted role even exists (prevents crashes) if not muted_role: await ctx.send("Oops! The 'Muted' role doesn't exist on this server. Please create it first.") return # Check if the member already has the Muted role if muted_role in member.roles: # Unmute the member await member.remove_roles(muted_role) # Use display_name instead of nick (handles users without a server nickname) await ctx.send(f'{member.display_name} has been unmuted successfully!') else: # Mute the member await member.add_roles(muted_role) await ctx.send(f'{member.display_name} has been muted successfully!')
Key Improvements
- Replaced
has_roles()with valid role check: Fixes theAttributeErrordirectly. - Added role existence check: Prevents crashes if the server doesn't have a role named "Muted".
- Used
display_nameinstead ofnick:member.nickcan beNoneif the user hasn't set a server nickname, butdisplay_namewill always show either their nickname or their default username. - Rearranged action and message: We modify the role first, then send the confirmation message—this ensures the action completes before notifying everyone.
内容的提问来源于stack exchange,提问作者Onur
相关产品推荐
相关产品推荐

