How do I edit a message in dropdown? #8306
-
Hi, I just started using the new discord.py 2.0 and tried out using dropdowns and buttons. I was just wondering how you would edit the message sent every time a new dropdown option is selected instead of sending a new one, any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Instead of responding via |
Beta Was this translation helpful? Give feedback.
-
OverviewLet's walk through a small example on how to do this, then move onto some resources where you can obtain more information if needed. from typing import Optional
import discord
from discord.ext import commands
class MyView(discord.ui.View):
def __init__(self) -> None:
self.selected: Optional[str] = None
super().__init__(timeout=180)
@property
def content(self) -> str:
# return the content of the selection.
# (
# self.selection or "nothing" means return the selected
# attribute OR if it's None, return "nothing"
# )
return f'You returned {self.selected or "nothing :("}'
@discord.ui.select(
placeholder='Select me...', options=[discord.SelectOption(label=str(i), value=str(i)) for i in range(10)]
)
async def select_me(self, interaction: discord.Interaction, select: discord.ui.Select) -> None:
# To get the selected values from this dropdown, we can to "select.values".
# Because by default this select is limuted to one input -> we can index it
# at 0
self.selected = select.values[0]
# self.content is going to call the "content" property as shown above.
# It will return the selected value in a formnatted string.
# Remember, every interaction MUST be responded to, the response
# we're gonna do is responding via an edit.
return await interaction.response.edit_message(content=self.content)
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.command()
async def foo_bar(ctx: commands.Context) -> None:
view = MyView()
return await ctx.send(view.content, view=view)
bot.run('TOKEN') Other resources
Happy coding :) |
Beta Was this translation helpful? Give feedback.
Overview
Let's walk through a small example on how to do this, then move onto some resources where you can obtain more information if needed.