Search code examples
pythondiscord.py

Limits to Discord Bot UI Persistent Views?


I'm making a bot that generates interactable messages from slash commands. These messages require data grabbed from an API with the commands, and have buttons that make an API request with info stored in the message view. Each user has their own stored authentication tokens for said API, so buttons are meant to be reused by different users at different times. Given that, I kinda wanted to make the message Views persistent so that a user could, say, drop the command in a channel, and another user could use it anytime in the future. However, reading through the discord.py documentation, I realized that each view has to be re-initialized whenever the bot restarts. And on top of that, having as many messages as I'm expecting that don't time out kinda worries me on the performance/limitations side of things.

So I'm trying to figure out: does Discord have limits on how many persistent views a bot can have up per server? Are there performance/memory issues? Is this feasible or am I flying too close to the sun???


Solution

  • Using PersistentViews is not a good idea in your case, as you need to create several of them programmatically. My suggestion is that you use the on_interaction event to manage the callbacks for all the messages. Here's a sketch:

    import discord
    
    @bot.event
    async def on_interaction(itc: discord.Interaction):
        custom_id = itc.data.get("custom_id")
        if custom_id == "YOUR_BUTTON_CUSTOM_ID":
            await button_action(itc)
    
    async def button_action(itc: discord.Interaction):
        #  When someone clicks on a button in any message
        #  that contains a button with the custom_id YOUR_BUTTON_CUSTOM_ID
        #  this method will be triggered
        #  You can access your bot using itc.client
        #  You can access the user who clicked the button using itc.user
        #  You can access the user who sent the button via itc.message
        #  (assuming you include the author of the button in the message text)
        await itc.response.send_message(f"Hi {itc.user}", ephemeral=True)