Raffaello Banhammer
Raffaello Banhammer

Reputation: 21

commands.check analog for buttons?

I have function that checks whether guild is in the whitelist that I use with commands.check for every my command:

async def is_active(ctx):
    return ctx.guild.id in get_whitelist()

Is there some sort of analog of commands.check for buttons, or I have to manually write is_active check to every button handler?

Upvotes: 2

Views: 31

Answers (1)

Łukasz Kwieciński
Łukasz Kwieciński

Reputation: 15689

Rather than putting the if-statement in each button, it's much easier if you create a check in the View class by using the interaction_check method:

class MyView(discord.ui.View):
    async def interaction_check(self, discord.Interaction) -> bool:
        return interaction.guild.id in get_whitelist()

    @discord.ui.button(label="Example")
    async def button(self, interaction: discord.Interaction) -> None:
        await interaction.response.send_message("This guild is not whitelisted")

If you want to add some sort of error handler, you have to do it inside of the interaction_check method, since it doesn't actually throw an error when it doesn't pass:

async def interaction_check(self, discord.Interaction) bool | None:
    if not interaction.guild.id in get_whitelist():
        await interaction.response.send_message("This guild is whitelisted")
    else:
        return True

Reference: https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.interaction_check

Upvotes: 0

Related Questions