Add role in discord.py

Viewed 205

I tried many different methods and I searched it up on youtube but everything I tried didn't work (was outdated or not relevant), how do I add a role to the mentioned user?

That's my code, look, and what I wrote in the () at the end.

@client.command()
@commands.has_permissions(kick_members=True)  
async def mute(ctx, member:discord.Member,*,reason=None):
    Embed = discord.Embed(title = f'✅{member} was muted by {ctx.author.name}!',color = 0x00ff00)
    Embed.add_field(name=f'Reason', value=f'{reason}')
    Embed.set_image(url='https://ak.picdn.net/shutterstock/videos/1014234401/thumb/1.jpg')
    await ctx.message.channel.send(embed=Embed)
    await (The command that should add the role "Muted" to the mentioned user)
2 Answers

First you need to get role from guild's roles.

role = ctx.guild.get_role(role_id)

or

role = discord.utils.get(ctx.guild.roles, name="Muted")

Now you can add role to target member

await member.add_roles(role)

Also you don't need to write

await ctx.message.channel.send()

You can do it with

await ctx.send()

You can use:

role = discord.utils.get(member.guild.roles, name="Test")
await member.add_roles(role)

So your code will look like this:

@client.command()
@commands.has_permissions(kick_members=True)  
async def mute(ctx, member:discord.Member,*,reason=None):
    Embed = discord.Embed(title = f'✅{member} was muted by {ctx.author.name}!',color = 0x00ff00)
    Embed.add_field(name=f'Reason', value=f'{reason}')
    Embed.set_image(url='https://ak.picdn.net/shutterstock/videos/1014234401/thumb/1.jpg')
    await ctx.message.channel.send(embed=Embed)
    role = discord.utils.get(member.server.roles, name="Muted") # Change name to the muted role name!
    await member.add_roles(role)

Related