From 7d0bd7ed20f0d2b2c2b0fc76170cbeaa019955b8 Mon Sep 17 00:00:00 2001 From: Nadir Chowdhury Date: Wed, 30 Jun 2021 01:02:55 +0100 Subject: [PATCH] add persistent view in on_ready to avoid loop issues --- examples/views/persistent.py | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/examples/views/persistent.py b/examples/views/persistent.py index 140a78693..717476677 100644 --- a/examples/views/persistent.py +++ b/examples/views/persistent.py @@ -2,15 +2,6 @@ from discord.ext import commands import discord -class PersistentViewBot(commands.Bot): - def __init__(self): - super().__init__(command_prefix=commands.when_mentioned_or('$')) - - async def on_ready(self): - print(f'Logged in as {self.user} (ID: {self.user.id})') - print('------') - - # Define a simple View that persists between bot restarts # In order a view to persist between restarts it needs to meet the following conditions: # 1) The timeout of the View has to be set to None @@ -36,14 +27,26 @@ class PersistentView(discord.ui.View): await interaction.response.send_message('This is grey.', ephemeral=True) -bot = PersistentViewBot() +class PersistentViewBot(commands.Bot): + def __init__(self): + super().__init__(command_prefix=commands.when_mentioned_or('$')) + self.persistent_views_added = False + + async def on_ready(self): + if not self.persistent_views_added: + # Register the persistent view for listening here. + # Note that this does not send the view to any message. + # In order to do this you need to first send a message with the View, which is shown below. + # If you have the message_id you can also pass it as a keyword argument, but for this example + # we don't have one. + self.add_view(PersistentView()) + self.persistent_views_added = True -# Register the persistent view for listening -# Note that this does not send the view to any message. -# In order to do this you need to first send a message with the View, which is shown below. -# If you have the message_id you can also pass it as a keyword argument, but for this example -# we don't have one. -bot.add_view(PersistentView()) + print(f'Logged in as {self.user} (ID: {self.user.id})') + print('------') + + +bot = PersistentViewBot() @bot.command()