From 6731eea33d41a5c9bc2ee0b219806476474707d5 Mon Sep 17 00:00:00 2001 From: Frisk Date: Sat, 1 Aug 2020 03:02:58 +0200 Subject: [PATCH] Implement new logic depending on Discord's rate limit information coded in headers instead of arbitrary sleep time --- src/discord.py | 10 +++++++--- src/msgqueue.py | 6 ++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/discord.py b/src/discord.py index 6f75c44..401849e 100644 --- a/src/discord.py +++ b/src/discord.py @@ -129,16 +129,20 @@ async def send_to_discord_webhook_monitoring(data: DiscordMessage): return 3 -async def send_to_discord_webhook(data: DiscordMessage, webhook_url: str): +async def send_to_discord_webhook(data: DiscordMessage, webhook_url: str) -> tuple: + """Sends a message to webhook + + :return tuple(status code for request, rate limit info (None for can send more, string for amount of seconds to wait)""" header = settings["header"] header['Content-Type'] = 'application/json' async with aiohttp.ClientSession(headers=header, timeout=aiohttp.ClientTimeout(5.0)) as session: try: result = await session.post("https://discord.com/api/webhooks/"+webhook_url, data=repr(data)) + rate_limit = None if int(result.headers.get('x-ratelimit-limit')) > 0 else result.headers.get('x-ratelimit-reset-after') except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError, TimeoutError): logger.exception("Could not send the message to Discord") - return 3 - return await handle_discord_http(result.status, repr(data), await result.text(), data) + return 3, None + return await handle_discord_http(result.status, repr(data), await result.text(), data), rate_limit async def handle_discord_http(code, formatted_embed, result, dmsg): diff --git a/src/msgqueue.py b/src/msgqueue.py index d16fd5a..d545ae7 100644 --- a/src/msgqueue.py +++ b/src/msgqueue.py @@ -43,10 +43,12 @@ class MessageQueue: async def send_msg_set(self, msg_set: tuple): webhook_url, messages = msg_set for msg in messages: - if await send_to_discord_webhook(msg, webhook_url) < 2: + status = await send_to_discord_webhook(msg, webhook_url) + if status[0] < 2: logger.debug("Sending message succeeded") self._queue.remove(msg) - await asyncio.sleep(1.9) + if status[1] is not None: + await asyncio.sleep(float(status[1])) else: logger.debug("Sending message failed") break