Discord bot role assignment function not working properly

I’m encountering an issue with my Discord bot’s command for adding roles to users. It operates correctly when I mention just a user, but fails when I try to include a role along with the user.

@bot.command()
async def assign_role(ctx, target_user: discord.Member = None, target_role: discord.Role = None):
    if target_user is None:
        await ctx.send("Please mention a user!")
    elif target_role is None:
        await ctx.send("Please specify a role to assign!")
    else:
        await target_user.add_roles(target_role)
        await ctx.send("Role successfully assigned!")

The problem arises when I use the command like !assign_role @user @role; the bot appears to see the role mention as part of the user’s name instead of as a separate argument. It returns an error indicating that the member could not be found, even though I am mentioning a valid user and role.

As I’m new to discord.py, I’m struggling to understand what’s causing this issue. Any assistance would be greatly appreciated!

I’ve hit this exact problem before. Discord’s converter processes arguments one by one, and when it sees a role mention while expecting a Member object, it tries to parse everything as a single argument. Switch to user/role IDs instead of mentions - that’s what fixed it for me. Modify your command to accept mentions or raw IDs, then use bot.get_member() and discord.utils.get() to grab the objects manually. This skips Discord’s automatic conversion and gives you way more control. You could also try commands.Greedy for multiple mentions, but for basic role assignment the ID method works better.

This is a known Discord bug with role assignment. When you mention both a role and user in the command, Discord gets confused about argument order and can’t fetch the mentioned user properly. Try flipping the order to !assign_role @role @user instead - that usually fixes it. If it’s still acting up, you might need to parse the message content yourself rather than relying on Discord’s mention handling.

Had this exact issue last week! Discord.py’s argument parsing breaks when you mix mentions. Use quotes around the role name instead of mentioning it directly - !assign_role @user "role name" works way better and avoids parsing conflicts.