Skip to content

Commit be402ca

Browse files
refactor: cache guild info and guild channels
this lowers the amount of requests we make and reduces the chance of ratelimiting
1 parent 7c2a089 commit be402ca

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

botstrap.py

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -75,11 +75,30 @@ def __init__(self, guild_id: int | str):
7575
)
7676
self.guild_id = guild_id
7777
self._app_info: dict[str, Any] | None = None
78+
self._guild_info: dict[str, Any] | None = None
79+
self._guild_channels: list[dict[str, Any]] | None = None
7880

7981
@staticmethod
8082
def _raise_for_status(response: Response) -> None:
8183
response.raise_for_status()
8284

85+
@property
86+
def guild_info(self) -> dict[str, Any]:
87+
"""Fetches the guild's information."""
88+
if self._guild_info is None:
89+
response = self.get(f"/guilds/{self.guild_id}")
90+
self._guild_info = cast("dict[str, Any]", response.json())
91+
return self._guild_info
92+
93+
@property
94+
def guild_channels(self) -> list[dict[str, Any]]:
95+
"""Fetches the guild's channels."""
96+
if self._guild_channels is None:
97+
response = self.get(f"/guilds/{self.guild_id}/channels")
98+
self._guild_channels = cast("list[dict[str, Any]]", response.json())
99+
return self._guild_channels
100+
101+
83102
@property
84103
def app_info(self) -> dict[str, Any]:
85104
"""Fetches the application's information."""
@@ -108,26 +127,25 @@ def upgrade_application_flags_if_necessary(self) -> bool:
108127
def check_if_in_guild(self) -> bool:
109128
"""Check if the bot is a member of the guild."""
110129
try:
111-
response = self.get(f"/guilds/{self.guild_id}")
130+
_ = self.guild_info
112131
except Exception:
113132
return False
114-
return response.status_code == 200
133+
return True
115134

116135
def upgrade_server_to_community_if_necessary(
117136
self,
118137
rules_channel_id_: int | str,
119138
announcements_channel_id_: int | str,
120139
) -> None:
121140
"""Fetches server info & upgrades to COMMUNITY if necessary."""
122-
response = self.get(f"/guilds/{self.guild_id}")
123-
payload = response.json()
141+
payload = self.guild_info
124142

125143
if COMMUNITY_FEATURE not in payload["features"]:
126144
log.warning("This server is currently not a community, upgrading.")
127145
payload["features"].append(COMMUNITY_FEATURE)
128146
payload["rules_channel_id"] = rules_channel_id_
129147
payload["public_updates_channel_id"] = announcements_channel_id_
130-
self.patch(f"/guilds/{self.guild_id}", json=payload)
148+
self._guild_info = self.patch(f"/guilds/{self.guild_id}", json=payload).json()
131149
log.info(f"Server {self.guild_id} has been successfully updated to a community.")
132150

133151
def create_forum_channel(
@@ -147,10 +165,9 @@ def create_forum_channel(
147165

148166
def is_forum_channel(self, channel_id_: str) -> bool:
149167
"""A boolean that indicates if a channel is of type GUILD_FORUM."""
150-
response = self.get(f"/channels/{channel_id_}")
151-
return response.json()["type"] == GUILD_FORUM_TYPE
168+
return next(filter(lambda c: c["id"] == channel_id_, self.guild_channels)).get("type", None) == GUILD_FORUM_TYPE
152169

153-
def delete_channel(self, channel_id_: id) -> None:
170+
def delete_channel(self, channel_id_: int | str) -> None:
154171
"""Delete a channel."""
155172
log.info(f"Channel python-help: {channel_id_} is not a forum channel and will be replaced with one.")
156173
self.delete(f"/channels/{channel_id_}")
@@ -159,8 +176,7 @@ def get_all_roles(self) -> dict:
159176
"""Fetches all the roles in a guild."""
160177
result = SilencedDict(name="Roles dictionary")
161178

162-
response = self.get(f"guilds/{self.guild_id}/roles")
163-
roles = response.json()
179+
roles = self.guild_info["roles"]
164180

165181
for role in roles:
166182
name = "_".join(part.lower() for part in role["name"].split(" ")).replace("-", "_")
@@ -175,8 +191,7 @@ def get_all_channels_and_categories(self) -> tuple[dict[str, str], dict[str, str
175191
channels = SilencedDict(name="Channels dictionary")
176192
categories = SilencedDict(name="Categories dictionary")
177193

178-
response = self.get(f"guilds/{self.guild_id}/channels")
179-
server_channels = response.json()
194+
server_channels = self.guild_channels
180195

181196
for channel in server_channels:
182197
channel_type = channel["type"]

0 commit comments

Comments
 (0)