Implement new logic depending on Discord's rate limit information coded in headers instead of arbitrary sleep time

This commit is contained in:
Frisk 2020-08-01 03:02:58 +02:00
parent f8293b6255
commit 6731eea33d
No known key found for this signature in database
GPG key ID: 213F7C15068AF8AC
2 changed files with 11 additions and 5 deletions

View file

@ -129,16 +129,20 @@ async def send_to_discord_webhook_monitoring(data: DiscordMessage):
return 3 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 = settings["header"]
header['Content-Type'] = 'application/json' header['Content-Type'] = 'application/json'
async with aiohttp.ClientSession(headers=header, timeout=aiohttp.ClientTimeout(5.0)) as session: async with aiohttp.ClientSession(headers=header, timeout=aiohttp.ClientTimeout(5.0)) as session:
try: try:
result = await session.post("https://discord.com/api/webhooks/"+webhook_url, data=repr(data)) 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): except (aiohttp.ClientConnectionError, aiohttp.ServerConnectionError, TimeoutError):
logger.exception("Could not send the message to Discord") logger.exception("Could not send the message to Discord")
return 3 return 3, None
return await handle_discord_http(result.status, repr(data), await result.text(), data) 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): async def handle_discord_http(code, formatted_embed, result, dmsg):

View file

@ -43,10 +43,12 @@ class MessageQueue:
async def send_msg_set(self, msg_set: tuple): async def send_msg_set(self, msg_set: tuple):
webhook_url, messages = msg_set webhook_url, messages = msg_set
for msg in messages: 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") logger.debug("Sending message succeeded")
self._queue.remove(msg) self._queue.remove(msg)
await asyncio.sleep(1.9) if status[1] is not None:
await asyncio.sleep(float(status[1]))
else: else:
logger.debug("Sending message failed") logger.debug("Sending message failed")
break break