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:
JavaScript
x
8
1
@client.command()
2
async def role(ctx):
3
user_id = ['752535843490616142' , '852495843390536197', '752595643220636947']
4
role = discord.utils.get(ctx.message.guild.roles, name = "Helpers")
5
for member in user_id:
6
await member.add_roles(role)
7
await ctx.send('roles have been given')
8
This is the error I got:
JavaScript
1
19
19
1
Ignoring exception in command role:
2
Traceback (most recent call last):
3
File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 85, in wrapped
4
ret = await coro(*args, **kwargs)
5
File "D:Python projectsDiscord BotsMC Server botLocaluntitled0.py", line 22, in role
6
await member.add_roles(role)
7
AttributeError: 'str' object has no attribute 'add_roles'
8
9
The above exception was the direct cause of the following exception:
10
11
Traceback (most recent call last):
12
File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandsbot.py", line 939, in invoke
13
await ctx.command.invoke(ctx)
14
File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 863, in invoke
15
await injected(*ctx.args, **ctx.kwargs)
16
File "C:Usersupaayanaconda3libsite-packagesdiscordextcommandscore.py", line 94, in wrapped
17
raise CommandInvokeError(exc) from exc
18
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'add_roles'
19
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.
JavaScript
1
9
1
@client.command()
2
async def role(ctx):
3
user_ids = [752535843490616142, 852495843390536197, 752595643220636947]
4
role = discord.utils.get(ctx.guild.roles, name="Helpers")
5
for user_id in user_ids:
6
member = ctx.guild.get_member(user_id)
7
await member.add_roles(role)
8
await ctx.send('roles have been given')
9