diff options
author | 2019-10-01 15:40:53 -0600 | |
---|---|---|
committer | 2019-10-01 15:40:53 -0600 | |
commit | 83f890ec79167b047b73a93aacbb070111453196 (patch) | |
tree | 093390539585bca0b236374846668f092b5ca22b | |
parent | Adjust development workflow inline with new `site` changes. (#464) (diff) |
Add checks for valid response and retries to fetch_posts()
-rw-r--r-- | bot/cogs/reddit.py | 22 |
1 files changed, 13 insertions, 9 deletions
diff --git a/bot/cogs/reddit.py b/bot/cogs/reddit.py index 63a57c5c6..c626ad48c 100644 --- a/bot/cogs/reddit.py +++ b/bot/cogs/reddit.py @@ -21,6 +21,7 @@ class Reddit(Cog): HEADERS = {"User-Agent": "Discord Bot: PythonDiscord (https://pythondiscord.com/)"} URL = "https://www.reddit.com" + MAX_FETCH_RETRIES = 3 def __init__(self, bot: Bot): self.bot = bot @@ -42,16 +43,19 @@ class Reddit(Cog): if params is None: params = {} - response = await self.bot.http_session.get( - url=f"{self.URL}/{route}.json", - headers=self.HEADERS, - params=params - ) - - content = await response.json() - posts = content["data"]["children"] + for _ in range(self.MAX_FETCH_RETRIES): + response = await self.bot.http_session.get( + url=f"{self.URL}/{route}.json", + headers=self.HEADERS, + params=params + ) + if response.status == 200 and response.content_type == 'application/json': + # Got appropriate response - process and return. + content = await response.json() + posts = content["data"]["children"] + return posts[:amount] - return posts[:amount] + return list() # Failed to get appropriate response within allowed number of retries. async def send_top_posts( self, channel: TextChannel, subreddit: Subreddit, content: str = None, time: str = "all" |