Search code examples
pythondiscorddiscord.py

How to give and take a role by clicking on the same button?


I created a button that, when pressed, adds a role to the user. However, I need to make sure that when pressed again the role is removed. I've tried to do it, but the role is added and immediately removed.

How do I make it so that the role is added and when the same button is pressed again, it is removed?

Code:

@bot.event
async def on_button_click(inter):
    res = 'You give role!'
    guild = bot.get_guild(inter.guild.id)
    if inter.component.id == "button":
        role = guild.get_role(IDROLE)
        member = inter.author
        await member.add_roles(role)
        await member.remove_roles(role)
        res = 'You remove role!'
        await inter.reply(res, ephemeral = True)

Solution

  • Rather than adding and then removing the role right after, you need to check, when they press the button, if they have the role or not to then add or remove it.

    @bot.event
    async def on_button_click(inter):
        guild = bot.get_guild(inter.guild.id)
        if inter.component.id == "button":
            role = guild.get_role(IDROLE)
            member = inter.author
            if role not in member.roles:
                # give the role if they do not have it
                await member.add_roles(role)
                res = 'You give role!'
                await inter.reply(res, ephemeral = True)
            else:
                # remove the role if they do have it
                await member.remove_roles(role)
                res = 'You remove role!'
                await inter.reply(res, ephemeral = True)