aboutsummaryrefslogtreecommitdiff
path: root/examples/views/confirm.py
diff options
context:
space:
mode:
authorRapptz <[email protected]>2021-06-29 04:17:20 -0400
committerRapptz <[email protected]>2021-06-29 04:19:12 -0400
commit7386a971f85bfc66f31132e8f0c98e9b4879ee3b (patch)
tree9ae83ea0258f56b2601a6563b4c05cedd0a9d07f /examples/views/confirm.py
parentType hint channel.py (diff)
downloaddiscord.py-7386a971f85bfc66f31132e8f0c98e9b4879ee3b.tar.xz
discord.py-7386a971f85bfc66f31132e8f0c98e9b4879ee3b.zip
Add examples for how to use views
Diffstat (limited to 'examples/views/confirm.py')
-rw-r--r--examples/views/confirm.py57
1 files changed, 57 insertions, 0 deletions
diff --git a/examples/views/confirm.py b/examples/views/confirm.py
new file mode 100644
index 00000000..6ec81369
--- /dev/null
+++ b/examples/views/confirm.py
@@ -0,0 +1,57 @@
+from discord.ext import commands
+
+import discord
+
+
+class Bot(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 confirmation menu
+class Confirm(discord.ui.View):
+ def __init__(self):
+ super().__init__()
+ self.value = None
+
+ # When the confirm button is pressed, set the inner value to `True` and
+ # stop the View from listening to more input.
+ # We also send the user an ephemeral message that we're confirming their choice.
+ @discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
+ async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
+ await interaction.response.send_message('Confirming', ephemeral=True)
+ self.value = True
+ self.stop()
+
+ # This one is similar to the confirmation button except sets the inner value to `False`
+ @discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
+ async def cancel(self, button: discord.ui.Button, interaction: discord.Interaction):
+ await interaction.response.send_message('Cancelling', ephemeral=True)
+ self.value = False
+ self.stop()
+
+
+bot = Bot()
+
+
+async def ask(ctx: commands.Context):
+ """Asks the user a question to confirm something."""
+ # We create the view and assign it to a variable so we can wait for it later.
+ view = Confirm()
+ await ctx.send('Do you want to continue?', view=view)
+ # Wait for the View to stop listening for input...
+ await view.wait()
+ if view.value is None:
+ print('Timed out...')
+ elif view.value:
+ print('Confirmed...')
+ else:
+ print('Cancelled...')
+
+
+bot.run('token')