51 lines
1.4 KiB
Python
Executable File
51 lines
1.4 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
|
|
"""
|
|
|
|
if isinstance(boards, list):
|
|
boards = random.choice(boards)
|
|
|
|
domains = [
|
|
"cdn.awwni.m",
|
|
"gfycat.com",
|
|
"i.imgur.com",
|
|
"i.redd.it",
|
|
"i.reddituploads.com",
|
|
"i3.kym-cdn.com",
|
|
"imgur.com",
|
|
"media.giphy.com",
|
|
"v.redd.it",
|
|
"reddit.com",
|
|
]
|
|
request_string = "https://reddit.com/r/{}/random.json".format(boards)
|
|
|
|
if not nsfw:
|
|
# Append this header to the request. Tells the API to only return SFW results
|
|
request_string += "?obey_over18=true"
|
|
|
|
# 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)
|
|
)
|
|
|
|
response = requests.get(
|
|
request_string, headers={"User-agent": random_user_agent}
|
|
).json()[0]["data"]["children"][0]["data"]
|
|
|
|
if response["secure_media"]:
|
|
image_url = response["secure_media"]["reddit_video"]["fallback_url"]
|
|
elif response["domain"] in domains:
|
|
image_url = response["url_overridden_by_dest"]
|
|
|
|
return image_url
|