admin管理员组

文章数量:1391975

async def role(ctx, member: discord.Member, *, role_name: str):
    if ctx.author.id == ctx.guild.owner_id:
        role_name = role_name.strip()  # Remove leading and trailing spaces
        role = discord.utils.find(lambda r: r.name.lower() == role_name.lower(), ctx.guild.roles)
        if role:
            if role in member.roles:
                await ctx.send(f"{member.mention} already has the {role_name} role.")
            else:
                try:
                    await member.add_roles(role)
                    await ctx.send(f"{role_name} role has been added to {member.mention}.")
                except discord.Forbidden:
                    await ctx.send("I do not have permission to add this role.")
                except discord.HTTPException as e:
                    await ctx.send(f"An error occurred: {e}")
        else:
            await ctx.send(f"Role '{role_name}' not found.")
    else:
        await ctx.send("You do not have permission to use this command.")

I tried to create an add role command but its not detecting the roles in the server "Role '@✨ Active [LVL 5]' not found." it clearly mentioned the role i've been trying to fix it but i can't

async def role(ctx, member: discord.Member, *, role_name: str):
    if ctx.author.id == ctx.guild.owner_id:
        role_name = role_name.strip()  # Remove leading and trailing spaces
        role = discord.utils.find(lambda r: r.name.lower() == role_name.lower(), ctx.guild.roles)
        if role:
            if role in member.roles:
                await ctx.send(f"{member.mention} already has the {role_name} role.")
            else:
                try:
                    await member.add_roles(role)
                    await ctx.send(f"{role_name} role has been added to {member.mention}.")
                except discord.Forbidden:
                    await ctx.send("I do not have permission to add this role.")
                except discord.HTTPException as e:
                    await ctx.send(f"An error occurred: {e}")
        else:
            await ctx.send(f"Role '{role_name}' not found.")
    else:
        await ctx.send("You do not have permission to use this command.")

I tried to create an add role command but its not detecting the roles in the server "Role '@✨ Active [LVL 5]' not found." it clearly mentioned the role i've been trying to fix it but i can't

Share Improve this question asked Mar 13 at 9:22 HxtredHxtred 1 1
  • It's just easier if you get the role from the ID rather than the name. – Łukasz Kwieciński Commented Mar 13 at 9:22
Add a comment  | 

1 Answer 1

Reset to default 0

I've noticed your error message says Role '@✨ Active [LVL 5]' not found implying you ran a command like .role @user @✨ Active [LVL 5]. Assuming your role name doesn't actually have an ampersand (@) in it, this will produce either one of two erroneous results:

  1. You will be searching for a role name with the ampersand, for example, '@role_name' == 'role_name' . This will always return False.

  2. If it completes into a role mention, then Discord will be seeing the mention form of the role. For example, if the ID of your role is 123456, then a role mention like @Role will appear to your Discord code as <@&123456>, and the search comparison will look like '<@&123456>' == 'role_name', which will also always return False.


To test it myself, I made a role called ✨ Active [LVL 5], ran the following code modeled after your code, and it successfully found the role when searching for only the role name (;testrole @user ✨ Active [LVL 5]) (no ampersand: @)

@commandsmand()
async def testrole(self, ctx, member: discord.Member, *, role_name: str):
    if ctx.author.id == ctx.guild.owner_id:
        role_name = role_name.strip()  # Remove leading and trailing spaces
        role = discord.utils.find(lambda r: r.name.lower() == role_name.lower(), ctx.guild.roles)
        print(f"Searching for role: {role_name} / `{role_name}`, found {role}.")

As a side note, you mention "it clearly mentioned the role I've been trying to [find] but it can't", but that's inaccurate because it's only mentioning the role_name argument that you passed. It hasn't actually found anything.

Also, if there's even an extra space in your role name somewhere, or anything at all different, then your search will fail. I recommend one of the following two ideas.

  1. Searching by Role ID (lambda r: r.id == int(role_id). It's harder for the average user to use because they have to copy the Role ID, but it is more failsafe.

  2. Use a looser name searching requirement. For example, lambda r: role_name.lower() in r.name.lower(). Then you could do something like .role @user LVL 5 and it'll still find the role (assuming there are not two roles with "LVL 5" in the name). This also avoids potential complications in parsing the emoji correctly.


If you wanted to get a bit more complicated, you could write a small function to put as the predicate of find(), or just iterate yourself over the guild roles. For example,

@commandsmand()
async def testrole(self, ctx, member: discord.Member, *, role_name: str):
    if ctx.author.id != ctx.guild.owner_id:
        return
    
    # Remove leading and trailing spaces
    role_name = role_name.strip()
    
    # If user tried and failed to mention role
    if role_name.startswith("@"):
        role_name = role_name[1:]
    
    role = None
    
    # Step 1: Try parsing as mention or raw ID
    role_id_match = re.fullmatch(r'<@&(\d+)>|(\d+)', role_name)
    if role_id_match:
        role_id = int(role_id_match.group(1) or role_id_match.group(2))
        role = ctx.guild.get_role(role_id)
    
    # Step 2: Exact name match if no ID match found
    if not role:
        role = discord.utils.find(lambda r: r.name.lower() == role_name.lower(), ctx.guild.roles)
    
    # Step 3: Partial name match as fallback
    if not role:
        role = discord.utils.find(lambda r: role_name.lower() in r.name.lower(), ctx.guild.roles)
    
    print(f"Searching: {role_name} / `{role_name}`, found {role}.")     

Result:

>>> ;testrole @user @✨ Active [LVL 5] 
Searching: @✨ Active [LVL 5] / <@&1349768558653210634>, found ✨ Active [LVL 5].

>>> ;testrole @user 1349768558653210634
Searching: 1349768558653210634 / 1349768558653210634, found ✨ Active [LVL 5].

>>> ;testrole @user LVL 5
Searching: LVL 5 / LVL 5, found ✨ Active [LVL 5].

本文标签: discordpy addroles command not working its not detecting the existing roles in the serverStack Overflow