pythondiscord.pynextcord

The button resets after restarting the bot in discord.py


After restarting the bot, the buttons do not work. I was looking for ways to fix it, but I didn't find it.

Code:

https://pastebin.com/yJwMhvF5

class TicketButton(nextcord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @nextcord.ui.button(label="Заявка", style=nextcord.ButtonStyle.blurple)
    async def zayavka(self, button: nextcord.ui.Button, interaction: Interaction):
        await interaction.response.send_modal(EmbedModal())

@bot.command()
async def createticket(ctx):
    em = nextcord.Embed(color=nextcord.Color.blue())
    em.add_field(name="**Подача заявки👮**", value="Нажмите на кнопку ниже для открытия поля заполнения заявки", inline=False)
    em.add_field(name="", value="*Подать заявку снова будет невозможно!*", inline=False)
    await ctx.send(embed=em, view=TicketButton())

Solution

  • This is expected behaviour. You'll need to make a view "persistent" for it to persist between restarts. You'll need to use bot.add_view to add the view for persistence. To do so, your view's timeout should be None (which it already is) and then your UI components will need to have custom IDs.

    class TicketButton(nextcord.ui.View):
        def __init__(self):
            super().__init__(timeout=None)
    
        @nextcord.ui.button(label="Заявка", style=nextcord.ButtonStyle.blurple, custom_id="my_custom_button")
        async def zayavka(self, button: nextcord.ui.Button, interaction: Interaction):
            await interaction.response.send_modal(EmbedModal())
    
    
    # and then register the view for persistence
    @bot.event
    async def on_ready():
        bot.add_view(TicketButton())
    

    Further reading:

    I know you're using nextcord but the libraries are still quite similar so these examples might be useful.