Skip to content

Commit 1bf3c7c

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 2163904 commit 1bf3c7c

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
@@ -218,13 +218,10 @@ def get_all_channels_and_categories(self) -> tuple[dict[str, str], dict[str, str
218218

219219
return channels, categories
220220

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

229226
def create_webhook(self, name: str, channel_id_: int) -> str:
230227
"""Creates a new webhook for a particular channel."""
@@ -306,14 +303,24 @@ def create_webhook(self, name: str, channel_id_: int) -> str:
306303
env_file_path.write_text(config_str)
307304

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

0 commit comments

Comments
 (0)