Search code examples
buttondiscordcommandnextcord

Buttons On NEXTCORD


Why is this code not working ?The purpose of the code was to make the button work forever, because after a while, it stops working, can someone give me some naughty help? xD

@client.command()
async def teste(ctx, role : nextcord.Role):
    class buttons(nextcord.ui.View(timeout = 0)):
        def __init__(self):
            super().__init__()
            self.value = None
        @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
        async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
    view = buttons()
    await ctx.send("teste", view = view)
    await view.wait()

Solution

  • You cannot build a class inside a command.

    class buttons(nextcord.ui.View(timeout = 0)):
    
            def __init__(self):
                super().__init__()
                self.value = None
    
            @nextcord.ui.button(label = "teste", style = nextcord.ButtonStyle.blurple)
            async def teste(self, button : nextcord.ui.Button, interaction : nextcord.Interaction):
                if role in interaction.user.roles:
                    await interaction.user.remove_roles(role)
                else:
                    await interaction.user.add_roles(role)
    

    Make sure to keep your class above the actual command. That way it works.

    @client.command()
    async def teste(ctx, role : nextcord.Role):
        view = buttons()
        await ctx.send("teste", view=view)
        await view.wait()