I want to give one role named helper to multiple users whose user id’s are in a list called user_id
Here is my code:
@client.command() async def role(ctx): user_id = ['752535843490616142' , '852495843390536197', '752595643220636947'] role = discord.utils.get(ctx.message.guild.roles, name = "Helpers") for member in user_id: await member.add_roles(role) await ctx.send('roles have been given')
This is the error I got:
Ignoring exception in command role: Traceback (most recent call last): File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 85, in wrapped ret = await coro(*args, **kwargs) File "D:Python projectsDiscord BotsMC Server botLocaluntitled0.py", line 22, in role await member.add_roles(role) AttributeError: 'str' object has no attribute 'add_roles' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandsbot.py", line 939, in invoke await ctx.command.invoke(ctx) File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 863, in invoke await injected(*ctx.args, **ctx.kwargs) File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 94, in wrapped raise CommandInvokeError(exc) from exc discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'add_roles'
Advertisement
Answer
I started by renaming some of the variables for clarity. I then got the member object using the user_ids and then added the role. Finally, I moved the await ctx.send('roles have been given')
outside of the for loop so that it’ll only send a single message.
@client.command() async def role(ctx): user_ids = [752535843490616142, 852495843390536197, 752595643220636947] role = discord.utils.get(ctx.guild.roles, name="Helpers") for user_id in user_ids: member = ctx.guild.get_member(user_id) await member.add_roles(role) await ctx.send('roles have been given')