How to add roles to a member using role id using discord.py?

44 Views Asked by At

how can i add a role to a person i mention through discord.py via role id?

i tried many commands that came into my search but every command left me with an error which was:

File "C:\Users\mxgak\OneDrive\Documents\Own Coded DC Tools\Stone MM Bot V1\main.py", line 350, in client
    await member.add_roles(role)
  File "C:\Users\mxgak\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\member.py", line 777, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
                                 ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
1

There are 1 best solutions below

1
RISHI CORPORATION On
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True

bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
print('Bot is ready.')

 @bot.command()
 async def giverole(ctx, member_id: 
 int, role_id: int):
 member = 
 
discord.utils.get(ctx.guild.members, 
 id=member_id)
 role = 
 discord.utils.get(ctx.guild.roles, 
 id=role_id)

if member is None:
    await ctx.send("Member not found.")
    return

if role is None:
    await ctx.send("Role not found.")
    return

await member.add_roles(role)
await ctx.send(f"Role {role.name} given to {member.display_name}")

   bot.run('YOUR_TOKEN')

I know you can use this as example||as a template