I have a few commands in my discord bot that I'd like to ask for confirmation before running. Something like this example:
@tree.command(name='test')
async def testCommand(interaction: discord.Interaction):
if await confirmationPrompt(interaction, 'run this test command'):
# Do stuff
But for that, i need confirmationPrompt()
to return either True
or False
.
I'd like to make the options to this confirmation prompt with buttons, so i wrote this:
async def confirmationPrompt(interaction: discord.Interaction, warning: str):
class ConfirmationButtons(discord.ui.View):
@discord.ui.button(label = '✅', style = discord.ButtonStyle.blurple)
async def returnTrue(self, interaction: discord.Interaction, button: discord.ui.Button):
return()
@discord.ui.button(label = '❌', style = discord.ButtonStyle.blurple)
async def returnFalse(self, interaction: discord.Interaction, button: discord.ui.Button):
return()
await interaction.response.send_message(
embed = discord.Embed(title = 'Are you sure you want to ' + warning),
view = ConfirmationButtons()
)
The issue is: I can't figure out a way to make confirmationPrompt()
return something from within returnTrue()
or returnFalse()
. What should I write to do that? Or if there's a better way to achieve the same result with a different method i would also like to know.
The simplest way is to simply have an instance attribute in the confirmation view and set it to True
when the user clicks the ✅ button, inside the confirmationPrompt
function after waiting for the view you can just return it:
class ConfirmationButtons(discord.ui.View):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.confirmed: bool = False
@discord.ui.button(label = '✅', style = discord.ButtonStyle.blurple)
async def returnTrue(self, interaction: discord.Interaction, button: discord.ui.Button):
self.confirmed = True
# also need to send a message, otherwise you'll get a "Interaction Failed" error
@discord.ui.button(label = '❌', style = discord.ButtonStyle.blurple)
async def returnFalse(self, interaction: discord.Interaction, button: discord.ui.Button):
# you need to send a message, otherwise you'll get a "Interaction Failed" error
async def confirmationPrompt(interaction: discord.Interaction, warning: str) -> bool:
view = ConfirmationButtons()
await interaction.response.send_message(
embed=discord.Embed(title='Are you sure you want to ' + warning), view=view
)
await view.wait()
return view.confirmed