Skip to content
Advertisement

discord.py Set a command to only work if the user doesn’t have a certain role

I’m trying to set up a verification command that gives a role upon its use, but I want to set it so the user can only use the command if they don’t already have the role. This is my code:

@client.command()
async def verify(ctx):
  if str(ctx.guild.id) in verify_roles:
    guild = ctx.message.author.guild
    rolegiven = ctx.message.author.guild.get_role(verify_roles.get(str(guild.id)))
    await ctx.message.author.add_roles(rolegiven)

Advertisement

Answer

One thing you could do is to retrieve rolegiven at the very beginning of your code. You can then check if the ctx.author has this role via member.roles. Here is a simplified version of the explained.

@client.command()
async def verify(ctx):
    await ctx.message.delete() # deletes the message the author sent
    if str(ctx.guild.id) in verify_roles:
        verify_role = ctx.guild.get_role(verify_roles.get(str(guild.id)))
        # check if the role is not in the author's current roles
        if verify_role not in ctx.author.roles:
            await ctx.author.add_roles(verify_role)
            await ctx.send("You have been verified!")
        else:
            await ctx.send(f"You already have {verify_role.name}")

Command working as seen here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement