Files
pycord-reactive-views/examples/counter.py

54 lines
1.6 KiB
Python
Raw Normal View History

2024-08-02 15:13:21 +02:00
# ruff: noqa: INP001
import os
import discord
from dotenv import load_dotenv
from pycord_reactive_views import ReactiveButton, ReactiveValue, ReactiveView
load_dotenv()
bot = discord.Bot()
class Counter(ReactiveView):
"""A simple counter view that increments a counter when a button is clicked."""
def __init__(self):
super().__init__()
self.counter = 0
self.counter_button = ReactiveButton(
2024-08-03 11:29:52 +02:00
label=ReactiveValue(lambda: f"Count: {self.counter}", "Count: 0"),
2024-08-02 15:13:21 +02:00
style=ReactiveValue(
lambda: discord.ButtonStyle.primary if self.counter % 2 == 0 else discord.ButtonStyle.secondary,
discord.ButtonStyle.primary,
),
)
self.reset_button = ReactiveButton(
label="Reset",
style=discord.ButtonStyle.danger,
2024-08-03 11:29:52 +02:00
disabled=ReactiveValue(lambda: self.counter == 0, True),
2024-08-02 15:13:21 +02:00
)
2024-08-03 11:29:52 +02:00
self.counter_button.callback = self._increment
self.reset_button.callback = self._reset
2024-08-02 15:13:21 +02:00
self.add_item(self.counter_button)
self.add_item(self.reset_button)
2024-08-03 11:29:52 +02:00
async def _increment(self, interaction: discord.Interaction) -> None:
2024-08-02 15:13:21 +02:00
await interaction.response.defer()
self.counter += 1
await self.update()
2024-08-03 11:29:52 +02:00
async def _reset(self, interaction: discord.Interaction) -> None:
2024-08-02 15:13:21 +02:00
await interaction.response.defer()
self.counter = 0
await self.update()
@bot.slash_command()
async def counter(ctx: discord.ApplicationContext) -> None:
"""Send the counter view."""
await Counter().send(ctx)
bot.run(os.getenv("TOKEN"))