diff options
| author | Rapptz <[email protected]> | 2021-06-29 04:17:20 -0400 |
|---|---|---|
| committer | Rapptz <[email protected]> | 2021-06-29 04:19:12 -0400 |
| commit | 7386a971f85bfc66f31132e8f0c98e9b4879ee3b (patch) | |
| tree | 9ae83ea0258f56b2601a6563b4c05cedd0a9d07f /examples/views/ephemeral.py | |
| parent | Type hint channel.py (diff) | |
| download | discord.py-7386a971f85bfc66f31132e8f0c98e9b4879ee3b.tar.xz discord.py-7386a971f85bfc66f31132e8f0c98e9b4879ee3b.zip | |
Add examples for how to use views
Diffstat (limited to 'examples/views/ephemeral.py')
| -rw-r--r-- | examples/views/ephemeral.py | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/examples/views/ephemeral.py b/examples/views/ephemeral.py new file mode 100644 index 00000000..770d4b65 --- /dev/null +++ b/examples/views/ephemeral.py @@ -0,0 +1,47 @@ +from discord.ext import commands + +import discord + +class EphemeralCounterBot(commands.Bot): + def __init__(self): + super().__init__(command_prefix=commands.when_mentioned_or('$')) + + async def on_ready(self): + print(f'Logged in as {self.user} (ID: {self.user.id})') + print('------') + +# Define a simple View that gives us a counter button +class Counter(discord.ui.View): + + # Define the actual button + # When pressed, this increments the number displayed until it hits 5. + # When it hits 5, the counter button is disabled and it turns green. + # note: The name of the function does not matter to the library + @discord.ui.button(label='0', style=discord.ButtonStyle.red) + async def count(self, button: discord.ui.Button, interaction: discord.Interaction): + number = int(button.label) if button.label else 0 + if number + 1 >= 5: + button.style = discord.ButtonStyle.green + button.disabled = True + button.label = str(number + 1) + + # Make sure to update the message with our updated selves + await interaction.response.edit_message(view=self) + +# Define a View that will give us our own personal counter button +class EphemeralCounter(discord.ui.View): + # When this button is pressed, it will respond with a Counter view that will + # give the button presser their own personal button they can press 5 times. + @discord.ui.button(label='Click', style=discord.ButtonStyle.blurple) + async def receive(self, button: discord.ui.Button, interaction: discord.Interaction): + # ephemeral=True makes the message hidden from everyone except the button presser + await interaction.response.send_message('Enjoy!', view=Counter(), ephemeral=True) + +bot = EphemeralCounterBot() + +async def counter(ctx: commands.Context): + """Starts a counter for pressing.""" + await ctx.send('Press!', view=EphemeralCounter()) + +bot.run('token') |