Button#
A simple example on the use of buttons with disnake-ext-components.
First and foremost, we create a bot as per usual. Since we don’t need any
prefix command capabilities, we opt for an InteractionBot
.
import os
import typing
import disnake
from disnake.ext import commands, components
Next, we make a component manager and register it to the bot.
manager = components.get_manager()
Then we make a simple component and register it to the manager. This component is a button that increments its label each time it is clicked.
@manager.register
class MyButton(components.RichButton):
label: typing.Optional[str] = "0"
count: int
async def callback(self, interaction: components.MessageInteraction) -> None:
self.count += 1
self.label = str(self.count)
Set the label
of the button…
class MyButton(components.RichButton):
Define a custom_id
parameter…
Then in the callback we increment the count, update the label to match the count and update our component.
async def callback(self, interaction: components.MessageInteraction) -> None:
self.count += 1
self.label = str(self.count)
Finally, we make a command that sends the component.
@bot.slash_command() # pyright: ignore # still some unknowns in disnake
async def test_button(inter: disnake.CommandInteraction) -> None:
wrapped = components.wrap_interaction(inter)
component = MyButton(count=0)
Tip
Wrapping the interaction allows you to send the component as-is.
If we had not wrapped the interaction, we would have needed to do await inter.send(components=await component.as_ui_component())
instead.
Lastly, we run the bot.
Source code#
1import os
2import typing
3
4import disnake
5from disnake.ext import commands, components
6
7bot = commands.InteractionBot()
8
9manager = components.get_manager()
10manager.add_to_bot(bot)
11
12
13@manager.register
14class MyButton(components.RichButton):
15 label: typing.Optional[str] = "0"
16
17 count: int
18
19 async def callback(self, interaction: components.MessageInteraction) -> None:
20 self.count += 1
21 self.label = str(self.count)
22
23 await interaction.response.edit_message(components=self)
24
25
26@bot.slash_command() # pyright: ignore # still some unknowns in disnake
27async def test_button(inter: disnake.CommandInteraction) -> None:
28 wrapped = components.wrap_interaction(inter)
29 component = MyButton(count=0)
30
31 await wrapped.response.send_message(components=component)
32
33