Search code examples
discord.pyrolesmember

discord.py how add role to member


I cannot solve the problem. How to add a role to the user who called the !role command. Please, help.

import discord
from discord.ext import commands
from apex_legends import ApexLegends
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='!', intents = intents)

@client.command()
async def rank(ctx, user_name,):
    rank = get_apex_rank(user_name) #return str role name
    await ctx.send(f"{rank}")# successfully receiving a response from the bot 
    member = ctx.author
    role = discord.utils.get(member.guild.roles, name=rank)
    await member.add_roles(role)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'guild'
def get_apex_rank(name):
    try:
        player = apex.player(name)
        a = player.__dict__
        return a['_data']['metadata']["rankName"]
    except:
        return "Wrong name"

Solution

  • @client.command():
    async def role(ctx):
        role = discord.utils.get(ctx.guild.roles, name="enter role name") #enter role name here
        user = ctx.message.author
        await user.add_roles(role)