You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 the AttributeError directly.
  • Added role existence check: Prevents crashes if the server doesn't have a role named "Muted".
  • Used display_name instead of nick: member.nick can be None if the user hasn't set a server nickname, but display_name will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:00:19