Button

Step-by-Step

A simple example on the use of buttons with disnake-compass. This component is a button that increments its label each time it is clicked.

examples/button.py - create a component
class MyButton(disnake_compass.RichButton):
    label: str | None = "0"

    count: int = 0

    async def callback(
        self, interaction: disnake.MessageInteraction[disnake.Client]
    ) -> None:
        self.count += 1
        self.label = str(self.count)

This button comes with its label = "0", and an integer variable count = 0 that is stored in the custom id. In the callback – which is ran every time the button is clicked – we increment the count and update the label to match the count. We then edit the message with the updated button.

Finally, we make a command that sends the component. Since count has a default, we do not need to specify it when instantiating the component.

examples/button.py - create a command and send the component
        await interaction.response.edit_message(components=component)


@bot.slash_command()
async def test_button(interaction: disnake.CommandInteraction[disnake.Client]) -> None:
    component = await MyButton().as_ui_component()

Source code

View on GitHub: button.py

examples/button.py
 1"""A simple example on the use of buttons with disnake-compass."""
 2
 3import os
 4
 5import disnake
 6import disnake_compass
 7from disnake.ext import commands
 8
 9bot = commands.InteractionBot()
10
11manager = disnake_compass.get_manager()
12manager.add_to_client(bot)
13
14
15@manager.register
16class MyButton(disnake_compass.RichButton):
17    label: str | None = "0"
18
19    count: int = 0
20
21    async def callback(
22        self, interaction: disnake.MessageInteraction[disnake.Client]
23    ) -> None:
24        self.count += 1
25        self.label = str(self.count)
26
27        component = await self.as_ui_component()
28        await interaction.response.edit_message(components=component)
29
30
31@bot.slash_command()
32async def test_button(interaction: disnake.CommandInteraction[disnake.Client]) -> None:
33    component = await MyButton().as_ui_component()
34    await interaction.response.send_message(components=component)
35
36
37bot.run(os.getenv("EXAMPLE_TOKEN"))