pythonpycord

Which means property custom_id in discord(pycord)


Which means property custom_id in discord(pycord) and show examples with this property

I do not understand what is where and why it is needed. I have a cat, but I want to understand what the custom_id is for and, if possible, add the code to the bot.


Solution

  • Documentation

    By custom_id I'm assuming you mean the parameter for button creation. See here.

    The custom_id is:

    The ID of the button that gets received during an interaction. If this button is for a URL, it does not have a custom ID.

    Source

    Usefulness

    Have you ever had the problem of past interactable views not being accessible after a bot restart? Well, the custom_id can be useful for this purpose. If we set the custom_id to anything, after the bot restarts it should keep the view saved (if the bot loads the view & the view has no timeout).

    Here's some example code:

    import os
    import discord
    from discord.ui import View, Button
    
    # --- Bot Setup ---
    bot = discord.Bot()
    
    @bot.listen()  # ensures that it doesn't override the event method that syncs the bot
    async def on_connect():
        bot.add_view(EpicView())  # Add the view to make it persistent
        print("Bot is connected!")
    
    
    class EpicView(View):  # The persistent view
        def __init__(self, ):
            super().__init__(timeout=None)  # A timeout of None is required
    
        @discord.ui.button(
            label="Hello!",
            style=discord.ButtonStyle.blurple,
            custom_id="hello_button",
        )
        async def hello(self, button: discord.Button, interaction: discord.Interaction):  # the button that uses the custom_id to make the persistent view
            await interaction.respond("This works!")
    
    
    @bot.slash_command()
    async def send_view(ctx):  # basic slash command to send the view
        view = EpicView()
        await ctx.respond("Hi!", view=view)
    

    This produces:

    First button press

    Above is the first button press

    Second button press

    Above is the second button press AFTER the bot restarted.