diff options
author | 2022-03-31 19:35:41 +0100 | |
---|---|---|
committer | 2022-04-18 17:44:34 +0100 | |
commit | 2b6deb85a67dd1c7ac70524f8c4ac5557d1e4bee (patch) | |
tree | 4f3f59804f81e36486ee11ccad3e55dfe6707f5b | |
parent | Don't use discord.NoMoreItems as it's removed (diff) |
Move to async cog loading
61 files changed, 158 insertions, 223 deletions
diff --git a/bot/exts/backend/branding/__init__.py b/bot/exts/backend/branding/__init__.py index 20a747b7f..8460465cb 100644 --- a/bot/exts/backend/branding/__init__.py +++ b/bot/exts/backend/branding/__init__.py @@ -2,6 +2,6 @@ from bot.bot import Bot from bot.exts.backend.branding._cog import Branding -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load Branding cog.""" - bot.add_cog(Branding(bot)) + await bot.add_cog(Branding(bot)) diff --git a/bot/exts/backend/branding/_cog.py b/bot/exts/backend/branding/_cog.py index 0c5839a7a..e55aa1995 100644 --- a/bot/exts/backend/branding/_cog.py +++ b/bot/exts/backend/branding/_cog.py @@ -17,7 +17,6 @@ from bot.constants import Branding as BrandingConfig, Channels, Colours, Guild, from bot.decorators import mock_in_debug from bot.exts.backend.branding._repository import BrandingRepository, Event, RemoteObject from bot.log import get_logger -from bot.utils import scheduling log = get_logger(__name__) @@ -127,7 +126,9 @@ class Branding(commands.Cog): self.bot = bot self.repository = BrandingRepository(bot) - scheduling.create_task(self.maybe_start_daemon(), event_loop=self.bot.loop) # Start depending on cache. + async def cog_load(self) -> None: + """Carry out cog asynchronous initialisation.""" + await self.maybe_start_daemon() # Start depending on cache. # region: Internal logic & state management @@ -413,7 +414,7 @@ class Branding(commands.Cog): if should_begin: self.daemon_loop.start() - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """ Cancel the daemon in case of cog unload. diff --git a/bot/exts/backend/config_verifier.py b/bot/exts/backend/config_verifier.py index dc85a65a2..97c8869a1 100644 --- a/bot/exts/backend/config_verifier.py +++ b/bot/exts/backend/config_verifier.py @@ -3,7 +3,6 @@ from discord.ext.commands import Cog from bot import constants from bot.bot import Bot from bot.log import get_logger -from bot.utils import scheduling log = get_logger(__name__) @@ -13,9 +12,8 @@ class ConfigVerifier(Cog): def __init__(self, bot: Bot): self.bot = bot - self.channel_verify_task = scheduling.create_task(self.verify_channels(), event_loop=self.bot.loop) - async def verify_channels(self) -> None: + async def cog_load(self) -> None: """ Verify channels. @@ -34,6 +32,6 @@ class ConfigVerifier(Cog): log.warning(f"Configured channels do not exist in server: {', '.join(invalid_channels)}.") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ConfigVerifier cog.""" - bot.add_cog(ConfigVerifier(bot)) + await bot.add_cog(ConfigVerifier(bot)) diff --git a/bot/exts/backend/error_handler.py b/bot/exts/backend/error_handler.py index c79c7b2a7..fabb2dbb5 100644 --- a/bot/exts/backend/error_handler.py +++ b/bot/exts/backend/error_handler.py @@ -328,6 +328,6 @@ class ErrorHandler(Cog): log.error(f"Error executing command invoked by {ctx.message.author}: {ctx.message.content}", exc_info=e) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ErrorHandler cog.""" - bot.add_cog(ErrorHandler(bot)) + await bot.add_cog(ErrorHandler(bot)) diff --git a/bot/exts/backend/logging.py b/bot/exts/backend/logging.py index 469331ae5..b9504c2eb 100644 --- a/bot/exts/backend/logging.py +++ b/bot/exts/backend/logging.py @@ -36,6 +36,6 @@ class Logging(Cog): await self.bot.get_channel(Channels.dev_log).send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Logging cog.""" - bot.add_cog(Logging(bot)) + await bot.add_cog(Logging(bot)) diff --git a/bot/exts/backend/sync/__init__.py b/bot/exts/backend/sync/__init__.py index 829098f79..1978917e6 100644 --- a/bot/exts/backend/sync/__init__.py +++ b/bot/exts/backend/sync/__init__.py @@ -1,8 +1,8 @@ from bot.bot import Bot -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Sync cog.""" # Defer import to reduce side effects from importing the sync package. from bot.exts.backend.sync._cog import Sync - bot.add_cog(Sync(bot)) + await bot.add_cog(Sync(bot)) diff --git a/bot/exts/backend/sync/_cog.py b/bot/exts/backend/sync/_cog.py index 80f5750bc..58aabc141 100644 --- a/bot/exts/backend/sync/_cog.py +++ b/bot/exts/backend/sync/_cog.py @@ -9,7 +9,6 @@ from bot.api import ResponseCodeError from bot.bot import Bot from bot.exts.backend.sync import _syncers from bot.log import get_logger -from bot.utils import scheduling log = get_logger(__name__) @@ -19,9 +18,8 @@ class Sync(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot - scheduling.create_task(self.sync_guild(), event_loop=self.bot.loop) - async def sync_guild(self) -> None: + async def cog_load(self) -> None: """Syncs the roles/users of the guild with the database.""" await self.bot.wait_until_guild_available() diff --git a/bot/exts/events/code_jams/__init__.py b/bot/exts/events/code_jams/__init__.py index 16e81e365..2f858d1f9 100644 --- a/bot/exts/events/code_jams/__init__.py +++ b/bot/exts/events/code_jams/__init__.py @@ -1,8 +1,8 @@ from bot.bot import Bot -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the CodeJams cog.""" from bot.exts.events.code_jams._cog import CodeJams - bot.add_cog(CodeJams(bot)) + await bot.add_cog(CodeJams(bot)) diff --git a/bot/exts/filters/antimalware.py b/bot/exts/filters/antimalware.py index 6cccf3680..ff39700a6 100644 --- a/bot/exts/filters/antimalware.py +++ b/bot/exts/filters/antimalware.py @@ -101,6 +101,6 @@ class AntiMalware(Cog): log.info(f"Tried to delete message `{message.id}`, but message could not be found.") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the AntiMalware cog.""" - bot.add_cog(AntiMalware(bot)) + await bot.add_cog(AntiMalware(bot)) diff --git a/bot/exts/filters/antispam.py b/bot/exts/filters/antispam.py index d9e23b25e..9ebf0268d 100644 --- a/bot/exts/filters/antispam.py +++ b/bot/exts/filters/antispam.py @@ -135,18 +135,12 @@ class AntiSpam(Cog): self.max_interval = max_interval_config['interval'] self.cache = MessageCache(AntiSpamConfig.cache_size, newest_first=True) - scheduling.create_task( - self.alert_on_validation_error(), - name="AntiSpam.alert_on_validation_error", - event_loop=self.bot.loop, - ) - @property def mod_log(self) -> ModLog: """Allows for easy access of the ModLog cog.""" return self.bot.get_cog("ModLog") - async def alert_on_validation_error(self) -> None: + async def cog_load(self) -> None: """Unloads the cog and alerts admins if configuration validation failed.""" await self.bot.wait_until_guild_available() if self.validation_errors: @@ -323,7 +317,7 @@ def validate_config(rules_: Mapping = AntiSpamConfig.rules) -> Dict[str, str]: return validation_errors -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Validate the AntiSpam configs and load the AntiSpam cog.""" validation_errors = validate_config() - bot.add_cog(AntiSpam(bot, validation_errors)) + await bot.add_cog(AntiSpam(bot, validation_errors)) diff --git a/bot/exts/filters/filter_lists.py b/bot/exts/filters/filter_lists.py index a883ddf54..3e3f5c562 100644 --- a/bot/exts/filters/filter_lists.py +++ b/bot/exts/filters/filter_lists.py @@ -11,7 +11,6 @@ from bot.constants import Channels from bot.converters import ValidDiscordServerInvite, ValidFilterListType from bot.log import get_logger from bot.pagination import LinePaginator -from bot.utils import scheduling log = get_logger(__name__) @@ -30,9 +29,8 @@ class FilterLists(Cog): def __init__(self, bot: Bot) -> None: self.bot = bot - scheduling.create_task(self._amend_docstrings(), event_loop=self.bot.loop) - async def _amend_docstrings(self) -> None: + async def cog_load(self) -> None: """Add the valid FilterList types to the docstrings, so they'll appear in !help invocations.""" await self.bot.wait_until_guild_available() @@ -288,6 +286,6 @@ class FilterLists(Cog): return await has_any_role(*constants.MODERATION_ROLES).predicate(ctx) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the FilterLists cog.""" - bot.add_cog(FilterLists(bot)) + await bot.add_cog(FilterLists(bot)) diff --git a/bot/exts/filters/filtering.py b/bot/exts/filters/filtering.py index 32efcc307..cabb7f0b6 100644 --- a/bot/exts/filters/filtering.py +++ b/bot/exts/filters/filtering.py @@ -149,9 +149,7 @@ class Filtering(Cog): }, } - scheduling.create_task(self.reschedule_offensive_msg_deletion(), event_loop=self.bot.loop) - - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel scheduled tasks.""" self.scheduler.cancel_all() @@ -675,7 +673,7 @@ class Filtering(Cog): delete_at = dateutil.parser.isoparse(msg['delete_date']) self.scheduler.schedule_at(delete_at, msg['id'], self.delete_offensive_msg(msg)) - async def reschedule_offensive_msg_deletion(self) -> None: + async def cog_load(self) -> None: """Get all the pending message deletion from the API and reschedule them.""" await self.bot.wait_until_ready() response = await self.bot.api_client.get('bot/offensive-messages',) @@ -718,6 +716,6 @@ class Filtering(Cog): return INVISIBLE_RE.sub("", no_zalgo) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Filtering cog.""" - bot.add_cog(Filtering(bot)) + await bot.add_cog(Filtering(bot)) diff --git a/bot/exts/filters/security.py b/bot/exts/filters/security.py index fe3918423..27e4d9752 100644 --- a/bot/exts/filters/security.py +++ b/bot/exts/filters/security.py @@ -25,6 +25,6 @@ class Security(Cog): return True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Security cog.""" - bot.add_cog(Security(bot)) + await bot.add_cog(Security(bot)) diff --git a/bot/exts/filters/token_remover.py b/bot/exts/filters/token_remover.py index 436e6dc19..a0d5aa7b6 100644 --- a/bot/exts/filters/token_remover.py +++ b/bot/exts/filters/token_remover.py @@ -228,6 +228,6 @@ class TokenRemover(Cog): return True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the TokenRemover cog.""" - bot.add_cog(TokenRemover(bot)) + await bot.add_cog(TokenRemover(bot)) diff --git a/bot/exts/filters/webhook_remover.py b/bot/exts/filters/webhook_remover.py index 96334317c..b42613804 100644 --- a/bot/exts/filters/webhook_remover.py +++ b/bot/exts/filters/webhook_remover.py @@ -89,6 +89,6 @@ class WebhookRemover(Cog): await self.on_message(after) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load `WebhookRemover` cog.""" - bot.add_cog(WebhookRemover(bot)) + await bot.add_cog(WebhookRemover(bot)) diff --git a/bot/exts/fun/duck_pond.py b/bot/exts/fun/duck_pond.py index 8a41a3116..1815e54f2 100644 --- a/bot/exts/fun/duck_pond.py +++ b/bot/exts/fun/duck_pond.py @@ -9,7 +9,6 @@ from bot import constants from bot.bot import Bot from bot.converters import MemberOrUser from bot.log import get_logger -from bot.utils import scheduling from bot.utils.checks import has_any_role from bot.utils.messages import count_unique_users_reaction, send_attachments from bot.utils.webhooks import send_webhook @@ -25,10 +24,9 @@ class DuckPond(Cog): self.webhook_id = constants.Webhooks.duck_pond self.webhook = None self.ducked_messages = [] - scheduling.create_task(self.fetch_webhook(), event_loop=self.bot.loop) self.relay_lock = None - async def fetch_webhook(self) -> None: + async def cog_load(self) -> None: """Fetches the webhook object, so we can post to it.""" await self.bot.wait_until_guild_available() @@ -218,6 +216,6 @@ class DuckPond(Cog): await ctx.message.add_reaction("❌") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the DuckPond cog.""" - bot.add_cog(DuckPond(bot)) + await bot.add_cog(DuckPond(bot)) diff --git a/bot/exts/fun/off_topic_names.py b/bot/exts/fun/off_topic_names.py index 33f43f2a8..ac172f2a8 100644 --- a/bot/exts/fun/off_topic_names.py +++ b/bot/exts/fun/off_topic_names.py @@ -52,14 +52,12 @@ class OffTopicNames(Cog): self.bot = bot self.updater_task = None - scheduling.create_task(self.init_offtopic_updater(), event_loop=self.bot.loop) - - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel any running updater tasks on cog unload.""" if self.updater_task is not None: self.updater_task.cancel() - async def init_offtopic_updater(self) -> None: + async def cog_load(self) -> None: """Start off-topic channel updating event loop if it hasn't already started.""" await self.bot.wait_until_guild_available() if self.updater_task is None: @@ -167,6 +165,6 @@ class OffTopicNames(Cog): await ctx.send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the OffTopicNames cog.""" - bot.add_cog(OffTopicNames(bot)) + await bot.add_cog(OffTopicNames(bot)) diff --git a/bot/exts/help_channels/__init__.py b/bot/exts/help_channels/__init__.py index beba18aa6..b9c940183 100644 --- a/bot/exts/help_channels/__init__.py +++ b/bot/exts/help_channels/__init__.py @@ -28,7 +28,7 @@ def validate_config() -> None: ) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the HelpChannels cog.""" # Defer import to reduce side effects from importing the help_channels package. from bot.exts.help_channels._cog import HelpChannels @@ -37,4 +37,4 @@ def setup(bot: Bot) -> None: except ValueError as e: log.error(f"HelpChannels cog will not be loaded due to misconfiguration: {e}") else: - bot.add_cog(HelpChannels(bot)) + await bot.add_cog(HelpChannels(bot)) diff --git a/bot/exts/help_channels/_cog.py b/bot/exts/help_channels/_cog.py index fc80c968c..2b2a5831f 100644 --- a/bot/exts/help_channels/_cog.py +++ b/bot/exts/help_channels/_cog.py @@ -89,12 +89,11 @@ class HelpChannels(commands.Cog): # Asyncio stuff self.queue_tasks: t.List[asyncio.Task] = [] - self.init_task = scheduling.create_task(self.init_cog(), event_loop=self.bot.loop) + self.init_done = False - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel the init task and scheduled tasks when the cog unloads.""" log.trace("Cog unload: cancelling the init_cog task") - self.init_task.cancel() log.trace("Cog unload: cancelling the channel queue tasks") for task in self.queue_tasks: @@ -318,7 +317,7 @@ class HelpChannels(commands.Cog): log.exception("Failed to get a category; cog will be removed") self.bot.remove_cog(self.qualified_name) - async def init_cog(self) -> None: + async def cog_load(self) -> None: """Initialise the help channel system.""" log.trace("Waiting for the guild to be available before initialisation.") await self.bot.wait_until_guild_available() @@ -354,6 +353,7 @@ class HelpChannels(commands.Cog): await self.init_available() _stats.report_counts() + self.init_done = True log.info("Cog is ready!") async def move_idle_channel(self, channel: discord.TextChannel, has_task: bool = True) -> None: @@ -365,7 +365,7 @@ class HelpChannels(commands.Cog): """ log.trace(f"Handling in-use channel #{channel} ({channel.id}).") - closing_time, closed_on = await _channel.get_closing_time(channel, self.init_task.done()) + closing_time, closed_on = await _channel.get_closing_time(channel, self.init_done) # Closing time is in the past. # Add 1 second due to POSIX timestamps being lower resolution than datetime objects. @@ -510,8 +510,6 @@ class HelpChannels(commands.Cog): if message.author.bot: return # Ignore messages sent by bots. - await self.init_task - if channel_utils.is_in_category(message.channel, constants.Categories.help_available): if not _channel.is_excluded_channel(message.channel): await self.claim_channel(message) @@ -527,8 +525,6 @@ class HelpChannels(commands.Cog): The new time for the dormant task is configured with `HelpChannels.deleted_idle_minutes`. """ - await self.init_task - if not channel_utils.is_in_category(msg.channel, constants.Categories.help_in_use): return diff --git a/bot/exts/info/code_snippets.py b/bot/exts/info/code_snippets.py index f2f29020f..bfe32459e 100644 --- a/bot/exts/info/code_snippets.py +++ b/bot/exts/info/code_snippets.py @@ -275,6 +275,6 @@ class CodeSnippets(Cog): ) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the CodeSnippets cog.""" - bot.add_cog(CodeSnippets(bot)) + await bot.add_cog(CodeSnippets(bot)) diff --git a/bot/exts/info/codeblock/__init__.py b/bot/exts/info/codeblock/__init__.py index 5c55bc5e3..dde45bd59 100644 --- a/bot/exts/info/codeblock/__init__.py +++ b/bot/exts/info/codeblock/__init__.py @@ -1,8 +1,8 @@ from bot.bot import Bot -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the CodeBlockCog cog.""" # Defer import to reduce side effects from importing the codeblock package. from bot.exts.info.codeblock._cog import CodeBlockCog - bot.add_cog(CodeBlockCog(bot)) + await bot.add_cog(CodeBlockCog(bot)) diff --git a/bot/exts/info/doc/__init__.py b/bot/exts/info/doc/__init__.py index facdf4d0b..4cfec33d3 100644 --- a/bot/exts/info/doc/__init__.py +++ b/bot/exts/info/doc/__init__.py @@ -11,7 +11,7 @@ NAMESPACE = "doc" doc_cache = DocRedisCache(namespace=NAMESPACE) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Doc cog.""" from ._cog import DocCog - bot.add_cog(DocCog(bot)) + await bot.add_cog(DocCog(bot)) diff --git a/bot/exts/info/doc/_cog.py b/bot/exts/info/doc/_cog.py index 3789fdbe3..8c3038c5b 100644 --- a/bot/exts/info/doc/_cog.py +++ b/bot/exts/info/doc/_cog.py @@ -469,8 +469,8 @@ class DocCog(commands.Cog): else: await ctx.send("No keys matching the package found.") - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Clear scheduled inventories, queued symbols and cleanup task on cog unload.""" self.inventory_scheduler.cancel_all() self.init_refresh_task.cancel() - scheduling.create_task(self.item_fetcher.clear(), name="DocCog.item_fetcher unload clear") + await self.item_fetcher.clear() diff --git a/bot/exts/info/help.py b/bot/exts/info/help.py index 864e7edd2..34480db57 100644 --- a/bot/exts/info/help.py +++ b/bot/exts/info/help.py @@ -489,12 +489,12 @@ class Help(Cog): bot.help_command = CustomHelpCommand() bot.help_command.cog = self - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Reset the help command when the cog is unloaded.""" self.bot.help_command = self.old_help_command -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Help cog.""" - bot.add_cog(Help(bot)) + await bot.add_cog(Help(bot)) log.info("Cog loaded: Help") diff --git a/bot/exts/info/information.py b/bot/exts/info/information.py index e616b9208..b56fd171a 100644 --- a/bot/exts/info/information.py +++ b/bot/exts/info/information.py @@ -552,6 +552,6 @@ class Information(Cog): await LinePaginator.paginate(final_rules, ctx, rules_embed, max_lines=3) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Information cog.""" - bot.add_cog(Information(bot)) + await bot.add_cog(Information(bot)) diff --git a/bot/exts/info/pep.py b/bot/exts/info/pep.py index 50c137d0f..d4df5d932 100644 --- a/bot/exts/info/pep.py +++ b/bot/exts/info/pep.py @@ -9,7 +9,6 @@ from discord.ext.commands import Cog, Context, command from bot.bot import Bot from bot.constants import Keys from bot.log import get_logger -from bot.utils import scheduling from bot.utils.caching import AsyncCache log = get_logger(__name__) @@ -33,7 +32,10 @@ class PythonEnhancementProposals(Cog): self.peps: Dict[int, str] = {} # To avoid situations where we don't have last datetime, set this to now. self.last_refreshed_peps: datetime = datetime.now() - scheduling.create_task(self.refresh_peps_urls(), event_loop=self.bot.loop) + + async def cog_load(self) -> None: + """Carry out cog asynchronous initialisation.""" + await self.refresh_peps_urls() async def refresh_peps_urls(self) -> None: """Refresh PEP URLs listing in every 3 hours.""" @@ -163,6 +165,6 @@ class PythonEnhancementProposals(Cog): log.trace(f"Getting PEP {pep_number} failed. Error embed sent.") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the PEP cog.""" - bot.add_cog(PythonEnhancementProposals(bot)) + await bot.add_cog(PythonEnhancementProposals(bot)) diff --git a/bot/exts/info/pypi.py b/bot/exts/info/pypi.py index dacf7bc12..2d387df3d 100644 --- a/bot/exts/info/pypi.py +++ b/bot/exts/info/pypi.py @@ -82,6 +82,6 @@ class PyPi(Cog): await ctx.send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the PyPi cog.""" - bot.add_cog(PyPi(bot)) + await bot.add_cog(PyPi(bot)) diff --git a/bot/exts/info/python_news.py b/bot/exts/info/python_news.py index c5b7183ce..111b2dcaf 100644 --- a/bot/exts/info/python_news.py +++ b/bot/exts/info/python_news.py @@ -11,7 +11,6 @@ from discord.ext.tasks import loop from bot import constants from bot.bot import Bot from bot.log import get_logger -from bot.utils import scheduling from bot.utils.webhooks import send_webhook PEPS_RSS_URL = "https://peps.python.org/peps.rss" @@ -42,8 +41,10 @@ class PythonNews(Cog): self.webhook_names = {} self.webhook: t.Optional[discord.Webhook] = None - scheduling.create_task(self.get_webhook_names(), event_loop=self.bot.loop) - scheduling.create_task(self.get_webhook_and_channel(), event_loop=self.bot.loop) + async def cog_load(self) -> None: + """Carry out cog asynchronous initialisation.""" + await self.get_webhook_names() + await self.get_webhook_and_channel() async def start_tasks(self) -> None: """Start the tasks for fetching new PEPs and mailing list messages.""" @@ -240,11 +241,11 @@ class PythonNews(Cog): await self.start_tasks() - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Stop news posting tasks on cog unload.""" self.fetch_new_media.cancel() -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Add `News` cog.""" - bot.add_cog(PythonNews(bot)) + await bot.add_cog(PythonNews(bot)) diff --git a/bot/exts/info/resources.py b/bot/exts/info/resources.py index e27357484..eeb9dd757 100644 --- a/bot/exts/info/resources.py +++ b/bot/exts/info/resources.py @@ -65,6 +65,6 @@ class Resources(commands.Cog): await ctx.send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Resources cog.""" - bot.add_cog(Resources(bot)) + await bot.add_cog(Resources(bot)) diff --git a/bot/exts/info/source.py b/bot/exts/info/source.py index e3e7029ca..f735cc744 100644 --- a/bot/exts/info/source.py +++ b/bot/exts/info/source.py @@ -98,6 +98,6 @@ class BotSource(commands.Cog): return embed -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the BotSource cog.""" - bot.add_cog(BotSource(bot)) + await bot.add_cog(BotSource(bot)) diff --git a/bot/exts/info/stats.py b/bot/exts/info/stats.py index 4d8bb645e..d4001a7bb 100644 --- a/bot/exts/info/stats.py +++ b/bot/exts/info/stats.py @@ -85,11 +85,11 @@ class Stats(Cog): self.bot.stats.gauge("boost.amount", g.premium_subscription_count) self.bot.stats.gauge("boost.tier", g.premium_tier) - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Stop the boost statistic task on unload of the Cog.""" self.update_guild_boost.stop() -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the stats cog.""" - bot.add_cog(Stats(bot)) + await bot.add_cog(Stats(bot)) diff --git a/bot/exts/info/subscribe.py b/bot/exts/info/subscribe.py index ed134ff78..d37c97281 100644 --- a/bot/exts/info/subscribe.py +++ b/bot/exts/info/subscribe.py @@ -5,7 +5,7 @@ from dataclasses import dataclass import arrow import discord -from botcore.utils import members, scheduling +from botcore.utils import members from discord.ext import commands from discord.interactions import Interaction @@ -26,7 +26,7 @@ class AssignableRole: role_id: int months_available: t.Optional[tuple[int]] - name: t.Optional[str] = None # This gets populated within Subscribe.init_cog() + name: t.Optional[str] = None # This gets populated within Subscribe.cog_load() def is_currently_available(self) -> bool: """Check if the role is available for the current month.""" @@ -143,11 +143,10 @@ class Subscribe(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - self.init_task = scheduling.create_task(self.init_cog(), event_loop=self.bot.loop) self.assignable_roles: list[AssignableRole] = [] self.guild: discord.Guild = None - async def init_cog(self) -> None: + async def cog_load(self) -> None: """Initialise the cog by resolving the role IDs in ASSIGNABLE_ROLES to role names.""" await self.bot.wait_until_guild_available() @@ -178,8 +177,6 @@ class Subscribe(commands.Cog): ) async def subscribe_command(self, ctx: commands.Context, *_) -> None: # We don't actually care about the args """Display the member's current state for each role, and allow them to add/remove the roles.""" - await self.init_task - button_view = RoleButtonView(ctx.author) author_roles = [role.id for role in ctx.author.roles] for index, role in enumerate(self.assignable_roles): @@ -193,9 +190,9 @@ class Subscribe(commands.Cog): ) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Subscribe cog.""" if len(ASSIGNABLE_ROLES) > ITEMS_PER_ROW*5: # Discord limits views to 5 rows of buttons. log.error("Too many roles for 5 rows, not loading the Subscribe cog.") else: - bot.add_cog(Subscribe(bot)) + await bot.add_cog(Subscribe(bot)) diff --git a/bot/exts/info/tags.py b/bot/exts/info/tags.py index f66237c8e..e89ffafb1 100644 --- a/bot/exts/info/tags.py +++ b/bot/exts/info/tags.py @@ -395,6 +395,6 @@ class Tags(Cog): return True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Tags cog.""" - bot.add_cog(Tags(bot)) + await bot.add_cog(Tags(bot)) diff --git a/bot/exts/moderation/clean.py b/bot/exts/moderation/clean.py index cb6836258..32e485996 100644 --- a/bot/exts/moderation/clean.py +++ b/bot/exts/moderation/clean.py @@ -602,6 +602,6 @@ class Clean(Cog): self.cleaning = False -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Clean cog.""" - bot.add_cog(Clean(bot)) + await bot.add_cog(Clean(bot)) diff --git a/bot/exts/moderation/defcon.py b/bot/exts/moderation/defcon.py index a8640cb1b..4d0488fab 100644 --- a/bot/exts/moderation/defcon.py +++ b/bot/exts/moderation/defcon.py @@ -319,13 +319,13 @@ class Defcon(Cog): """Routinely notify moderators that DEFCON is active.""" await self.channel.send(f"Defcon is on and is set to {time.humanize_delta(self.threshold)}.") - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel the notifer and threshold removal tasks when the cog unloads.""" log.trace("Cog unload: canceling defcon notifier task.") self.defcon_notifier.cancel() self.scheduler.cancel_all() -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Defcon cog.""" - bot.add_cog(Defcon(bot)) + await bot.add_cog(Defcon(bot)) diff --git a/bot/exts/moderation/dm_relay.py b/bot/exts/moderation/dm_relay.py index 566422e29..a86c9e409 100644 --- a/bot/exts/moderation/dm_relay.py +++ b/bot/exts/moderation/dm_relay.py @@ -68,6 +68,6 @@ class DMRelay(Cog): and is_mod_channel(ctx.channel)) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the DMRelay cog.""" - bot.add_cog(DMRelay(bot)) + await bot.add_cog(DMRelay(bot)) diff --git a/bot/exts/moderation/incidents.py b/bot/exts/moderation/incidents.py index d34c1c7fa..c0bd09b72 100644 --- a/bot/exts/moderation/incidents.py +++ b/bot/exts/moderation/incidents.py @@ -658,6 +658,6 @@ class Incidents(Cog): log.trace("Successfully deleted discord links webhook message.") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Incidents cog.""" - bot.add_cog(Incidents(bot)) + await bot.add_cog(Incidents(bot)) diff --git a/bot/exts/moderation/infraction/_scheduler.py b/bot/exts/moderation/infraction/_scheduler.py index 9f5800e2a..137358ec3 100644 --- a/bot/exts/moderation/infraction/_scheduler.py +++ b/bot/exts/moderation/infraction/_scheduler.py @@ -29,10 +29,9 @@ class InfractionScheduler: def __init__(self, bot: Bot, supported_infractions: t.Container[str]): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) + self.supported_infractions = supported_infractions - scheduling.create_task(self.reschedule_infractions(supported_infractions), event_loop=self.bot.loop) - - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel scheduled tasks.""" self.scheduler.cancel_all() @@ -41,9 +40,10 @@ class InfractionScheduler: """Get the currently loaded ModLog cog instance.""" return self.bot.get_cog("ModLog") - async def reschedule_infractions(self, supported_infractions: t.Container[str]) -> None: + async def cog_load(self) -> None: """Schedule expiration for previous infractions.""" await self.bot.wait_until_guild_available() + supported_infractions = self.supported_infractions log.trace(f"Rescheduling infractions for {self.__class__.__name__}.") @@ -72,7 +72,7 @@ class InfractionScheduler: ) log.trace("Will reschedule remaining infractions at %s", next_reschedule_point) - self.scheduler.schedule_at(next_reschedule_point, -1, self.reschedule_infractions(supported_infractions)) + self.scheduler.schedule_at(next_reschedule_point, -1, self.cog_load(supported_infractions)) log.trace("Done rescheduling") diff --git a/bot/exts/moderation/infraction/infractions.py b/bot/exts/moderation/infraction/infractions.py index 18bed5080..7aea4d207 100644 --- a/bot/exts/moderation/infraction/infractions.py +++ b/bot/exts/moderation/infraction/infractions.py @@ -609,6 +609,6 @@ class Infractions(InfractionScheduler, commands.Cog): error.handled = True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Infractions cog.""" - bot.add_cog(Infractions(bot)) + await bot.add_cog(Infractions(bot)) diff --git a/bot/exts/moderation/infraction/management.py b/bot/exts/moderation/infraction/management.py index 81f623688..6653c77f9 100644 --- a/bot/exts/moderation/infraction/management.py +++ b/bot/exts/moderation/infraction/management.py @@ -453,6 +453,6 @@ class ModManagement(commands.Cog): error.handled = True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ModManagement cog.""" - bot.add_cog(ModManagement(bot)) + await bot.add_cog(ModManagement(bot)) diff --git a/bot/exts/moderation/infraction/superstarify.py b/bot/exts/moderation/infraction/superstarify.py index c4a7e5081..0e6aaa1e7 100644 --- a/bot/exts/moderation/infraction/superstarify.py +++ b/bot/exts/moderation/infraction/superstarify.py @@ -239,6 +239,6 @@ class Superstarify(InfractionScheduler, Cog): return await has_any_role(*constants.MODERATION_ROLES).predicate(ctx) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Superstarify cog.""" - bot.add_cog(Superstarify(bot)) + await bot.add_cog(Superstarify(bot)) diff --git a/bot/exts/moderation/metabase.py b/bot/exts/moderation/metabase.py index d68726faf..b407a0ea9 100644 --- a/bot/exts/moderation/metabase.py +++ b/bot/exts/moderation/metabase.py @@ -8,7 +8,6 @@ import arrow from aiohttp.client_exceptions import ClientResponseError from arrow import Arrow from async_rediscache import RedisCache -from botcore.utils import scheduling from botcore.utils.scheduling import Scheduler from discord.ext.commands import Cog, Context, group, has_any_role @@ -41,8 +40,6 @@ class Metabase(Cog): self.exports: Dict[int, List[Dict]] = {} # Saves the output of each question, so internal eval can access it - self.init_task = scheduling.create_task(self.init_cog(), event_loop=self.bot.loop) - async def cog_command_error(self, ctx: Context, error: Exception) -> None: """Handle ClientResponseError errors locally to invalidate token if needed.""" if not isinstance(error.original, ClientResponseError): @@ -62,7 +59,7 @@ class Metabase(Cog): await ctx.send(f":x: {ctx.author.mention} Session token is invalid or refresh failed.") error.handled = True - async def init_cog(self) -> None: + async def cog_load(self) -> None: """Initialise the metabase session.""" expiry_time = await self.session_info.get("session_expiry") if expiry_time: @@ -128,9 +125,6 @@ class Metabase(Cog): """ await ctx.trigger_typing() - # Make sure we have a session token before running anything - await self.init_task - url = f"{MetabaseConfig.base_url}/api/card/{question_id}/query/{extension}" async with self.bot.http_session.post(url, headers=self.headers, raise_for_status=True) as resp: @@ -161,8 +155,6 @@ class Metabase(Cog): async def metabase_publish(self, ctx: Context, question_id: int) -> None: """Publically shares the given question and posts the link.""" await ctx.trigger_typing() - # Make sure we have a session token before running anything - await self.init_task url = f"{MetabaseConfig.base_url}/api/card/{question_id}/public_link" @@ -180,22 +172,10 @@ class Metabase(Cog): ] return all(checks) - def cog_unload(self) -> None: - """ - Cancel the init task and scheduled tasks. - - It's important to wait for init_task to be cancelled before cancelling scheduled - tasks. Otherwise, it's possible for _session_scheduler to schedule another task - after cancel_all has finished, despite _init_task.cancel being called first. - This is cause cancel() on its own doesn't block until the task is cancelled. - """ - self.init_task.cancel() - self.init_task.add_done_callback(lambda _: self._session_scheduler.cancel_all()) - -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Metabase cog.""" if not all((MetabaseConfig.username, MetabaseConfig.password)): log.error("Credentials not provided, cog not loaded.") return - bot.add_cog(Metabase(bot)) + await bot.add_cog(Metabase(bot)) diff --git a/bot/exts/moderation/modlog.py b/bot/exts/moderation/modlog.py index 796c1f021..843d56b57 100644 --- a/bot/exts/moderation/modlog.py +++ b/bot/exts/moderation/modlog.py @@ -936,6 +936,6 @@ class ModLog(Cog, name="ModLog"): ) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ModLog cog.""" - bot.add_cog(ModLog(bot)) + await bot.add_cog(ModLog(bot)) diff --git a/bot/exts/moderation/modpings.py b/bot/exts/moderation/modpings.py index cb1e4fd05..0030ae542 100644 --- a/bot/exts/moderation/modpings.py +++ b/bot/exts/moderation/modpings.py @@ -244,7 +244,7 @@ class ModPings(Cog): await self.modpings_schedule.delete(ctx.author.id) await ctx.send(f"{Emojis.ok_hand} {ctx.author.mention} Deleted your modpings schedule!") - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel role tasks when the cog unloads.""" log.trace("Cog unload: canceling role tasks.") self.reschedule_task.cancel() @@ -254,6 +254,6 @@ class ModPings(Cog): self._modpings_scheduler.cancel_all() -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ModPings cog.""" - bot.add_cog(ModPings(bot)) + await bot.add_cog(ModPings(bot)) diff --git a/bot/exts/moderation/silence.py b/bot/exts/moderation/silence.py index 307729181..6173b4492 100644 --- a/bot/exts/moderation/silence.py +++ b/bot/exts/moderation/silence.py @@ -5,7 +5,6 @@ from datetime import datetime, timedelta, timezone from typing import Optional, OrderedDict, Union from async_rediscache import RedisCache -from botcore.utils import scheduling from botcore.utils.scheduling import Scheduler from discord import Guild, PermissionOverwrite, TextChannel, Thread, VoiceChannel from discord.ext import commands, tasks @@ -115,9 +114,7 @@ class Silence(commands.Cog): self.bot = bot self.scheduler = Scheduler(self.__class__.__name__) - self._init_task = scheduling.create_task(self._async_init(), event_loop=self.bot.loop) - - async def _async_init(self) -> None: + async def cog_load(self) -> None: """Set instance attributes once the guild is available and reschedule unsilences.""" await self.bot.wait_until_guild_available() @@ -177,7 +174,6 @@ class Silence(commands.Cog): Passing a voice channel will attempt to move members out of the channel and back to force sync permissions. If `kick` is True, members will not be added back to the voice channel, and members will be unable to rejoin. """ - await self._init_task channel, duration = self.parse_silence_args(ctx, duration_or_channel, duration) channel_info = f"#{channel} ({channel.id})" @@ -281,7 +277,6 @@ class Silence(commands.Cog): If the channel was silenced indefinitely, notifications for the channel will stop. """ - await self._init_task if channel is None: channel = ctx.channel log.debug(f"Unsilencing channel #{channel} from {ctx.author}'s command.") @@ -467,21 +462,12 @@ class Silence(commands.Cog): log.info(f"Rescheduling silence for #{channel} ({channel.id}).") self.scheduler.schedule_later(delta, channel_id, self._unsilence_wrapper(channel)) - def cog_unload(self) -> None: - """Cancel the init task and scheduled tasks.""" - # It's important to wait for _init_task (specifically for _reschedule) to be cancelled - # before cancelling scheduled tasks. Otherwise, it's possible for _reschedule to schedule - # more tasks after cancel_all has finished, despite _init_task.cancel being called first. - # This is cause cancel() on its own doesn't block until the task is cancelled. - self._init_task.cancel() - self._init_task.add_done_callback(lambda _: self.scheduler.cancel_all()) - # This cannot be static (must have a __func__ attribute). async def cog_check(self, ctx: Context) -> bool: """Only allow moderators to invoke the commands in this cog.""" return await commands.has_any_role(*constants.MODERATION_ROLES).predicate(ctx) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Silence cog.""" - bot.add_cog(Silence(bot)) + await bot.add_cog(Silence(bot)) diff --git a/bot/exts/moderation/slowmode.py b/bot/exts/moderation/slowmode.py index b6a771441..1be568a56 100644 --- a/bot/exts/moderation/slowmode.py +++ b/bot/exts/moderation/slowmode.py @@ -89,6 +89,6 @@ class Slowmode(Cog): return await has_any_role(*MODERATION_ROLES).predicate(ctx) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Slowmode cog.""" - bot.add_cog(Slowmode(bot)) + await bot.add_cog(Slowmode(bot)) diff --git a/bot/exts/moderation/stream.py b/bot/exts/moderation/stream.py index 17d24eb89..ecdef630e 100644 --- a/bot/exts/moderation/stream.py +++ b/bot/exts/moderation/stream.py @@ -31,19 +31,13 @@ class Stream(commands.Cog): def __init__(self, bot: Bot): self.bot = bot self.scheduler = scheduling.Scheduler(self.__class__.__name__) - self.reload_task = scheduling.create_task(self._reload_tasks_from_redis(), event_loop=self.bot.loop) - - def cog_unload(self) -> None: - """Cancel all scheduled tasks.""" - self.reload_task.cancel() - self.reload_task.add_done_callback(lambda _: self.scheduler.cancel_all()) async def _revoke_streaming_permission(self, member: discord.Member) -> None: """Remove the streaming permission from the given Member.""" await self.task_cache.delete(member.id) await member.remove_roles(discord.Object(Roles.video), reason="Streaming access revoked") - async def _reload_tasks_from_redis(self) -> None: + async def cog_load(self) -> None: """Reload outstanding tasks from redis on startup, delete the task if the member has since left the server.""" await self.bot.wait_until_guild_available() items = await self.task_cache.items() @@ -232,6 +226,6 @@ class Stream(commands.Cog): await ctx.send("No members with stream permissions found.") -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Loads the Stream cog.""" - bot.add_cog(Stream(bot)) + await bot.add_cog(Stream(bot)) diff --git a/bot/exts/moderation/verification.py b/bot/exts/moderation/verification.py index 37338d19c..306c27e06 100644 --- a/bot/exts/moderation/verification.py +++ b/bot/exts/moderation/verification.py @@ -127,6 +127,6 @@ class Verification(Cog): # endregion -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Verification cog.""" - bot.add_cog(Verification(bot)) + await bot.add_cog(Verification(bot)) diff --git a/bot/exts/moderation/voice_gate.py b/bot/exts/moderation/voice_gate.py index d6b8f1239..33096e7e0 100644 --- a/bot/exts/moderation/voice_gate.py +++ b/bot/exts/moderation/voice_gate.py @@ -272,6 +272,6 @@ class VoiceGate(Cog): error.handled = True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Loads the VoiceGate cog.""" - bot.add_cog(VoiceGate(bot)) + await bot.add_cog(VoiceGate(bot)) diff --git a/bot/exts/moderation/watchchannels/_watchchannel.py b/bot/exts/moderation/watchchannels/_watchchannel.py index bae7ecd02..ab5ce62f9 100644 --- a/bot/exts/moderation/watchchannels/_watchchannel.py +++ b/bot/exts/moderation/watchchannels/_watchchannel.py @@ -375,7 +375,7 @@ class WatchChannel(metaclass=CogABCMeta): self.message_queue.pop(user_id, None) self.consumption_queue.pop(user_id, None) - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Takes care of unloading the cog and canceling the consumption task.""" self.log.trace("Unloading the cog") if self._consume_task and not self._consume_task.done(): diff --git a/bot/exts/moderation/watchchannels/bigbrother.py b/bot/exts/moderation/watchchannels/bigbrother.py index 31b106a20..4a746edff 100644 --- a/bot/exts/moderation/watchchannels/bigbrother.py +++ b/bot/exts/moderation/watchchannels/bigbrother.py @@ -169,6 +169,6 @@ class BigBrother(WatchChannel, Cog, name="Big Brother"): await ctx.send(message) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the BigBrother cog.""" - bot.add_cog(BigBrother(bot)) + await bot.add_cog(BigBrother(bot)) diff --git a/bot/exts/recruitment/talentpool/__init__.py b/bot/exts/recruitment/talentpool/__init__.py index 52d27eb99..aa09a1ee2 100644 --- a/bot/exts/recruitment/talentpool/__init__.py +++ b/bot/exts/recruitment/talentpool/__init__.py @@ -1,8 +1,8 @@ from bot.bot import Bot -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the TalentPool cog.""" from bot.exts.recruitment.talentpool._cog import TalentPool - bot.add_cog(TalentPool(bot)) + await bot.add_cog(TalentPool(bot)) diff --git a/bot/exts/recruitment/talentpool/_cog.py b/bot/exts/recruitment/talentpool/_cog.py index 0d51af2ca..8aa124536 100644 --- a/bot/exts/recruitment/talentpool/_cog.py +++ b/bot/exts/recruitment/talentpool/_cog.py @@ -603,7 +603,6 @@ class TalentPool(Cog, name="Talentpool"): return lines.strip() - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancels all review tasks on cog unload.""" - super().cog_unload() self.reviewer.cancel_all() diff --git a/bot/exts/utils/bot.py b/bot/exts/utils/bot.py index 8f0094bc9..721ae9dcb 100644 --- a/bot/exts/utils/bot.py +++ b/bot/exts/utils/bot.py @@ -61,6 +61,6 @@ class BotCog(Cog, name="Bot"): await channel.send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Bot cog.""" - bot.add_cog(BotCog(bot)) + await bot.add_cog(BotCog(bot)) diff --git a/bot/exts/utils/extensions.py b/bot/exts/utils/extensions.py index fda1e49e2..95ce94c2c 100644 --- a/bot/exts/utils/extensions.py +++ b/bot/exts/utils/extensions.py @@ -222,6 +222,6 @@ class Extensions(commands.Cog): error.handled = True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Extensions cog.""" - bot.add_cog(Extensions(bot)) + await bot.add_cog(Extensions(bot)) diff --git a/bot/exts/utils/internal.py b/bot/exts/utils/internal.py index e7113c09c..2148a3676 100644 --- a/bot/exts/utils/internal.py +++ b/bot/exts/utils/internal.py @@ -252,6 +252,6 @@ async def func(): # (None,) -> Any await ctx.send(embed=stats_embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Internal cog.""" - bot.add_cog(Internal(bot)) + await bot.add_cog(Internal(bot)) diff --git a/bot/exts/utils/ping.py b/bot/exts/utils/ping.py index 9fb5b7b8f..67a960365 100644 --- a/bot/exts/utils/ping.py +++ b/bot/exts/utils/ping.py @@ -60,6 +60,6 @@ class Latency(commands.Cog): await ctx.send(embed=embed) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Latency cog.""" - bot.add_cog(Latency(bot)) + await bot.add_cog(Latency(bot)) diff --git a/bot/exts/utils/reminders.py b/bot/exts/utils/reminders.py index 62603697c..45cddd7a2 100644 --- a/bot/exts/utils/reminders.py +++ b/bot/exts/utils/reminders.py @@ -38,13 +38,11 @@ class Reminders(Cog): self.bot = bot self.scheduler = Scheduler(self.__class__.__name__) - scheduling.create_task(self.reschedule_reminders(), event_loop=self.bot.loop) - - def cog_unload(self) -> None: + async def cog_unload(self) -> None: """Cancel scheduled tasks.""" self.scheduler.cancel_all() - async def reschedule_reminders(self) -> None: + async def cog_load(self) -> None: """Get all current reminders from the API and reschedule them.""" await self.bot.wait_until_guild_available() response = await self.bot.api_client.get( @@ -487,6 +485,6 @@ class Reminders(Cog): return True -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Reminders cog.""" - bot.add_cog(Reminders(bot)) + await bot.add_cog(Reminders(bot)) diff --git a/bot/exts/utils/snekbox.py b/bot/exts/utils/snekbox.py index 2b073ed72..32b7c8761 100644 --- a/bot/exts/utils/snekbox.py +++ b/bot/exts/utils/snekbox.py @@ -458,6 +458,6 @@ def predicate_emoji_reaction(ctx: Context, reaction: Reaction, user: User) -> bo return reaction.message.id == ctx.message.id and user.id == ctx.author.id and str(reaction) == REDO_EMOJI -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Snekbox cog.""" - bot.add_cog(Snekbox(bot)) + await bot.add_cog(Snekbox(bot)) diff --git a/bot/exts/utils/thread_bumper.py b/bot/exts/utils/thread_bumper.py index 35057f1fe..c65664b52 100644 --- a/bot/exts/utils/thread_bumper.py +++ b/bot/exts/utils/thread_bumper.py @@ -8,7 +8,7 @@ from bot import constants from bot.bot import Bot from bot.log import get_logger from bot.pagination import LinePaginator -from bot.utils import channel, scheduling +from bot.utils import channel log = get_logger(__name__) @@ -21,7 +21,6 @@ class ThreadBumper(commands.Cog): def __init__(self, bot: Bot): self.bot = bot - self.init_task = scheduling.create_task(self.ensure_bumped_threads_are_active(), event_loop=self.bot.loop) async def unarchive_threads_not_manually_archived(self, threads: list[discord.Thread]) -> None: """ @@ -50,7 +49,7 @@ class ThreadBumper(commands.Cog): else: await thread.edit(archived=False) - async def ensure_bumped_threads_are_active(self) -> None: + async def cog_load(self) -> None: """Ensure bumped threads are active, since threads could have been archived while the bot was down.""" await self.bot.wait_until_guild_available() @@ -142,6 +141,6 @@ class ThreadBumper(commands.Cog): ).predicate(ctx) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the ThreadBumper cog.""" - bot.add_cog(ThreadBumper(bot)) + await bot.add_cog(ThreadBumper(bot)) diff --git a/bot/exts/utils/utils.py b/bot/exts/utils/utils.py index 2a074788e..975e0f56d 100644 --- a/bot/exts/utils/utils.py +++ b/bot/exts/utils/utils.py @@ -206,6 +206,6 @@ class Utils(Cog): await message.add_reaction(reaction) -def setup(bot: Bot) -> None: +async def setup(bot: Bot) -> None: """Load the Utils cog.""" - bot.add_cog(Utils(bot)) + await bot.add_cog(Utils(bot)) |