#Is PersistentView unique?

1 messages · Page 1 of 1 (latest)

lusty sonnet
#

Recently, I was experimenting with persistent views and found out that only 1 instance can exist in memory. Consider this example:

class AutoroleView(discord.ui.View):
    def __init__(self, role_id=None, *args, **kwargs):
        super().__init__(*args, **kwargs, timeout=None)
        self.role_id = role_id

    @discord.ui.button(label="Вывести", custom_id="ar-button")
    async def button_callback(self, button, interaction: discord.Interaction):
        await interaction.response.send_message(f"{self.role_id=}")

This is a basic view that stores role_id inside it and displays it on button click. If I would send 2 views in one channel with first having role_id=15 and second role_id=17 it doesn't matter which button i'll press - it will display me that role_id is equal to 17. (latest value I suppose)

I want to create a persistent view that will give people roles based on their selection in select menu. The bot can possibly be on multiple servers. Will this mean that this persistent view will give SAME roles on DIFFERENT servers?

Also, after restart, if I press the button once again, it will show me that role_id is not set. I guess it's because I'm initializing it this way:

@bot.event
async def on_ready():
    bot.add_view(AutoroleView())
    print("Bot is ready")
#

Can anyone explain to me, it it possible to make autorole view persistent and if so, how would it know what roles to give after restart?

lusty sonnet
#

Can it display same output because I have custom-id set to constant? If so, how can I make it unique?

flat pumice
#

You are correct with it not working because you use the same custom id.

How it works is when you click a button on discord discord send the bot that the button belongs to a event that includes a little bit of information. Primarily a custom_id that the bot set when creating the message. What pycord does it finds what view that custom id is part of and gives that instance of the view. So when discord returns your custom_id the bot returns the button with that ID but because you have 2 it will retrun the first that it finds. The solution is to have a different custom_id for each button. The library will autogenerate a custom ID for you if you dont specify one.

To make your bot have persistent views between restarts you would need to store the button_id and the role_id together somewhere (most likely a database) and when you need to load it you need to gather all of the pairs and load them

for row in rows:
  bot.add_view(AutoroleView(row["roloe_id"], row["custom_id"])

A shortcut to this would to set the custom_id to be the role_id but this is somewhat hacky and would not be good if you have a lot of information you need to save.