pythondiscord.py

Reconnect to a view (with buttons etc.) in discord.py


I'm handling an attendance list with my discord.py bot. It's a simple view with 2 buttons. The view needs to run for 7 days straight, so its important that my bot doesn't bug/crash.

Is there a way to reconnect to a view (containing buttons and so on) after you stopped your bot? The reason is that my bot is doing other tasks as well and sometimes they bug out and I have to restart the bot, but this leads to the attendance lists being dead..

bot.run(config["TOKEN"], reconnect=True)

^ this is working fine for disconnects or me restarting my router, but I haven't found a solution to reconnect to the views after restarting the whole bot/script.

Any ideas?


Solution

  • If you need to save information after the bot either crashes or is restarted then you will need to hold that information in some sort of permanent storage like a database or json file. If you want to keep it simple you can just store information in a json and have your bot read/write to that file instead of handling it all in memory.

    Regarding the views, if you just need to get the view to start up again you can add this line to somewhere that is executed on your bot's start like "on_ready()" for example.

    async def on_ready(self):
        self.add_view(MyView())
    

    It is important for this to work that all the items (like buttons) in your view have a unique id given to them. For example:

        @discord.ui.button(
            label='Admin Menu 📝',
            style=discord.ButtonStyle.grey,
            custom_id='admin_menu' # <-- this needs to be set
        )
    

    If you go to the github page for discord.py they also have an "examples" folder, under views they have a example called "persistence.py" that shows a full example of what I am mentioning here