Skip to content
Advertisement

How do I give user roles in discord when the user types a command?

I am having trouble assigning a role to a user when they type in a command

Code:

@client.command()
async def BMOrole(ctx, member: discord.Member = None):
    role = discord.utils.get(ctx.guild.roles, name='BMO')
    await member.add_roles(role)
    await ctx.send('Role given!')

When the user types “!BMOrole”, I want to give them a role called, “BMO” and also display a message.

The error I’m receiving is:

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'add_roles'

Advertisement

Answer

you forget set a default user:

@client.command()
async def BMOrole(ctx, member: discord.Member = None):
    if member is None:
        member = ctx.author

    role = discord.utils.get(ctx.guild.roles, name='BMO')
    await member.add_roles(role)
    await ctx.send('Role given!')
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement