aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar MarkKoz <[email protected]>2019-12-20 20:55:03 -0800
committerGravatar MarkKoz <[email protected]>2020-02-12 10:07:40 -0800
commit7806638ffc9b634012f809d1e764ac38c3f58f8e (patch)
tree9f59451ac2ddceb19bf461b7b8d08f0f6e1b4049
parentMerge pull request #747 from mosguinz/pagniation-fix (diff)
Bot: add wait_until_guild_available
This coroutine waits until the configured guild is available and ensures the cache is present. The on_ready event is inadequate because it only waits 2 seconds for a GUILD_CREATE gateway event before giving up and thus not populating the cache for unavailable guilds.
-rw-r--r--bot/bot.py39
1 files changed, 39 insertions, 0 deletions
diff --git a/bot/bot.py b/bot/bot.py
index 8f808272f..c0f31911c 100644
--- a/bot/bot.py
+++ b/bot/bot.py
@@ -1,11 +1,14 @@
+import asyncio
import logging
import socket
from typing import Optional
import aiohttp
+import discord
from discord.ext import commands
from bot import api
+from bot import constants
log = logging.getLogger('bot')
@@ -24,6 +27,8 @@ class Bot(commands.Bot):
super().__init__(*args, connector=self.connector, **kwargs)
+ self._guild_available = asyncio.Event()
+
self.http_session: Optional[aiohttp.ClientSession] = None
self.api_client = api.APIClient(loop=self.loop, connector=self.connector)
@@ -51,3 +56,37 @@ class Bot(commands.Bot):
self.http_session = aiohttp.ClientSession(connector=self.connector)
await super().start(*args, **kwargs)
+
+ async def on_guild_available(self, guild: discord.Guild) -> None:
+ """
+ Set the internal guild available event when constants.Guild.id becomes available.
+
+ If the cache appears to still be empty (no members, no channels, or no roles), the event
+ will not be set.
+ """
+ if guild.id != constants.Guild.id:
+ return
+
+ if not guild.roles or not guild.members or not guild.channels:
+ log.warning(
+ "Guild available event was dispatched but the cache appears to still be empty!"
+ )
+ return
+
+ self._guild_available.set()
+
+ async def on_guild_unavailable(self, guild: discord.Guild) -> None:
+ """Clear the internal guild available event when constants.Guild.id becomes unavailable."""
+ if guild.id != constants.Guild.id:
+ return
+
+ self._guild_available.clear()
+
+ async def wait_until_guild_available(self) -> None:
+ """
+ Wait until the constants.Guild.id guild is available (and the cache is ready).
+
+ The on_ready event is inadequate because it only waits 2 seconds for a GUILD_CREATE
+ gateway event before giving up and thus not populating the cache for unavailable guilds.
+ """
+ await self._guild_available.wait()