Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

How to add ui.View to discord interaction and on button click change message?

  1. User

    How to add ui.View to discord interaction and on button click change message?

  2. Assistant

    Discord doesn't have native support for ui.View as 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:

    1. First, make sure you have discord.py 2.0.0 or newer.
    pip install discord.py>=2.0.0
    
    1. 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")
    
    1. Handle the button click and change the message using the Interaction event.
    @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_message slash command that sends a message with a button. Clicking the button updates the message using the on_interaction event handler.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.