Skip to content

Commit 44a7088

Browse files
authored
Merge pull request #47 from CSSS/dev-issue-42
Add rate limiting to Discord api requests
2 parents 69db25b + 945897c commit 44a7088

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/discord/discord.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import os
22
from dataclasses import dataclass
3+
from time import sleep
34

45
import requests
56
from constants import guild_id
@@ -47,6 +48,16 @@ async def _discord_request(
4748
"User-Agent" : "DiscordBot (https://github.com/CSSS/csss-site-backend, 1.0)"
4849
}
4950
)
51+
rate_limit_reset = float(result.headers["x-ratelimit-reset-after"])
52+
rate_limit_remaining_requests = int(result.headers["x-ratelimit-remaining"])
53+
54+
if rate_limit_remaining_requests <= 2:
55+
# this rate limits the current thread from doing too many requests, however it won't
56+
# limit other threads.
57+
# TODO: in the future, we'll want to create a singleton that thread locks
58+
# usage of the same api key to N at a time, and waits if there are no requests remaining
59+
sleep(rate_limit_reset)
60+
5061
return result
5162

5263
async def get_channel_members(
@@ -330,6 +341,7 @@ async def search_user(
330341
url = f"https://discord.com/api/v10/guilds/{gid}/members/search?query={user}"
331342
result = await _discord_request(url, token)
332343
json = result.json()
344+
333345
if len(json) == 0:
334346
return None
335347
json = json[0]["user"]

0 commit comments

Comments
 (0)