Search code examples
pythondiscorddiscord.py

How do I issue a role when entering a command?


I need that when entering a command, a certain role is given to the person who entered it. I have a code, but it works if you enter a command and a nickname (.command @nickname), I need to make it work just when you enter a command (.command). How can I redo the code to make it work?

@client.command(pass_context = True )
@commands.has_role("role1234")
async def command (ctx, author: discord.Member):
    role0 = ctx.guild.get_role(981971100898582539) 
    role1 = ctx.guild.get_role(981594840879988807)
    role3 = ctx.guild.get_role(981971134893395990) 
    role2 = discord.utils.get(ctx.guild.roles, id = 981971065486057492)
    if role2 in author.roles:
        await ctx.channel.purge( limit = 1000)
        await ctx.author.add_roles(role3)
        await ctx.author.remove_roles(role1)
        await ctx.author.remove_roles(role2)
        await ctx.author.remove_roles(role0)

Solution

  • [...] but it works if you enter a command and a nickname (.command @nickname), I need to make it work just when you enter a command

    I understand perfectly. So, do you know how you can get the author as a discord.Member object without passing it as an argument to the command?

    async def command(ctx):
        author = ctx.author # Then you can use this variable in the whole scope of the function
    

    So, in your case, the only thing to change except for the prototype of the function is this line:

    if role2 in author.roles:
    

    That should become:

    if role2 in ctx.author.roles: