gpt-4-0314· openai
Suzhen/CodeChat
How to add ui.View to discord interaction and on button click change message?
- User
How to add ui.View to discord interaction and on button click change message?
- Assistant
Discord doesn't have native support for
ui.Viewas it's not a web-based platform. However, you can achieve similar functionality using Discord's built-in components like buttons and message interactions. Here's an example of how you can create a message with a button and handle the button click to change the message using discord.py:- First, make sure you have discord.py 2.0.0 or newer.
pip install discord.py>=2.0.0- Create a simple bot script with a slash command that sends a message with a button.
import discord from discord.ext import commands from discord.ui import Button, View intents = discord.Intents.default() intents.messages = True bot = commands.Bot(command_prefix="!", intents=intents, slash_command_guilds=[GUILD_ID]) class CustomView(View): def __init__(self): super().__init__() self.add_item(Button(label="Click me!", custom_id="my_button")) @bot.slash_command(name="button_message") async def button_message(ctx): view = CustomView() await ctx.send("Here's a message with a button:", view=view) @bot.event async def on_ready(): print(f"Logged in as {bot.user}!") bot.run("your_token_here")- Handle the button click and change the message using the
Interactionevent.
@bot.event async def on_interaction(interaction): if interaction.type != discord.InteractionType.component: # Ignore non-component interactions return if interaction.data["custom_id"] == "my_button": view = CustomView() view.clear_items() # Remove the button from the view await interaction.message.edit(content="You clicked the button!", view=view)This example creates a simple bot with a
/button_messageslash command that sends a message with a button. Clicking the button updates the message using theon_interactionevent handler.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.