Skip to content

Commit 268963e

Browse files
refactor: request all webhooks at once, match by name
* request all webhooks in a single call rather than per configured webhook * Enable support for multiple identical test bots sharing the same webhook This should prevent the limit of 10 webhooks per channel from being reached without needing to share a specific guild configuration for the PyDis staff test guild
1 parent b600dbb commit 268963e

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

botstrap.py

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -217,13 +217,10 @@ def get_all_channels_and_categories(self) -> tuple[dict[str, str], dict[str, str
217217

218218
return channels, categories
219219

220-
def webhook_exists(self, webhook_id_: int) -> bool:
221-
"""A predicate that indicates whether a webhook exists already or not."""
222-
try:
223-
self.get(f"/webhooks/{webhook_id_}")
224-
return True
225-
except HTTPStatusError:
226-
return False
220+
def get_all_guild_webhooks(self) -> list[dict[str, Any]]:
221+
"""Lists all the webhooks for the guild."""
222+
response = self.get(f"/guilds/{self.guild_id}/webhooks")
223+
return response.json()
227224

228225
def create_webhook(self, name: str, channel_id_: int) -> str:
229226
"""Creates a new webhook for a particular channel."""
@@ -303,14 +300,24 @@ def create_webhook(self, name: str, channel_id_: int) -> str:
303300
env_file_path.write_text(config_str)
304301

305302
config_str += "\n#Webhooks\n"
306-
303+
existing_webhooks = discord_client.get_all_guild_webhooks()
307304
for webhook_name, webhook_model in Webhooks:
308-
webhook = discord_client.webhook_exists(webhook_model.id)
309-
if not webhook:
310-
webhook_channel_id = int(all_channels[webhook_name])
311-
webhook_id = discord_client.create_webhook(webhook_name, webhook_channel_id)
305+
formatted_webhook_name = webhook_name.replace("_", " ").title()
306+
for existing_hook in existing_webhooks:
307+
if (
308+
# check the existing ID matches the configured one
309+
existing_hook["id"] == str(webhook_model.id)
310+
or (
311+
# check if the name and the channel ID match the configured ones
312+
existing_hook["name"] == formatted_webhook_name
313+
and existing_hook["channel_id"] == str(all_channels[webhook_name])
314+
)
315+
):
316+
webhook_id = existing_hook["id"]
317+
break
312318
else:
313-
webhook_id = webhook_model.id
319+
webhook_channel_id = int(all_channels[webhook_name])
320+
webhook_id = discord_client.create_webhook(formatted_webhook_name, webhook_channel_id)
314321
config_str += f"webhooks_{webhook_name}__id={webhook_id}\n"
315322
config_str += f"webhooks_{webhook_name}__channel={all_channels[webhook_name]}\n"
316323

0 commit comments

Comments
 (0)