Skip to content

Commit

Permalink
fix(Randimals): send a browser user-agent to make Imgur happy
Browse files Browse the repository at this point in the history
  • Loading branch information
tmercswims committed Jun 17, 2024
1 parent d9f3cbd commit 8948fc8
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion randimals/randimals.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,26 @@ async def fetcher() -> str:
await ctx.send("I was unable to get a bird picture.")

async def __get_image_carefully(self, fetcher: Callable[[], Awaitable[str]]) -> discord.File:
# We need to send a user agent pretending to be a normal browser so that Imgur works. Without this, it assumes
# that we _aren't_ a normal browser (it's correct) and automatically returns a 429 (too many requests), which is
# really just Imgur trying to get us to use their actual REST API. We won't, because it requires authentication
# tokens, and you have to pay Imgur for any real amount of usage. So at least for now, this workaround works.
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/75.0.3770.100 Safari/537.36"
}

for x in range(Randimals.RETRY_LIMIT):
try:
img_url = await fetcher()
filename = os.path.basename(img_url)
async with self.__session.head(img_url) as size_check:
if size_check.content_length is None or size_check.content_length > Randimals.SIZE_LIMIT:
continue
async with self.__session.get(img_url) as image:
async with self.__session.get(
img_url,
headers=headers,
) as image:
return discord.File(io.BytesIO(await image.read()), filename=filename)
except aiohttp.ClientError:
continue
Expand Down

0 comments on commit 8948fc8

Please sign in to comment.