dragon-bot/app/get_from_reddit.py
2024-12-10 10:13:02 -08:00

42 lines
1.1 KiB
Python
Executable File

import random
import string
import requests
def get_image(boards, nsfw=False):
"""
get_image(boards, nsfw=False)
Returns a URL to an image on reddit from a random board in the boards list
as long as it is hosted on one of the domains in the domains list
"""
# Spoof our user agent with each request so we dont get rate limited
random_user_agent = "".join(
random.SystemRandom().choice(string.ascii_uppercase + string.digits)
for _ in range(5)
)
if isinstance(boards, list):
boards = random.choice(boards)
request_string = f"https://www.reddit.com/r/{boards}/hot.json?raw_json=1"
response = requests.get(
request_string, headers={"User-agent": random_user_agent}
).json()["data"]["children"]
response = random.choice(response)["data"]
if response.get("url_overridden_by_dest"):
image_url = response["url_overridden_by_dest"]
else:
image_url = response["url"]
# image_url = "https://rxddit.com" + response["permalink"]
if "youtu.be" in response["url"]:
image_url = response["url"]
return image_url