Skip to content

Instantly share code, notes, and snippets.

@jasonwhite
Created December 1, 2021 05:57
Show Gist options
  • Save jasonwhite/d679dcd948eaecf7035c6e3a5c487f2e to your computer and use it in GitHub Desktop.
Save jasonwhite/d679dcd948eaecf7035c6e3a5c487f2e to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Uses the Reddit API to get the top wallpaper from a specified subreddit.
"""
import urllib.request
import json
import subprocess
import shutil
import argparse
from pathlib import Path
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:67.0) Gecko/20100101 Firefox/67.0"
def find_top_wallpaper(min_width, min_height, min_aspect=1.2, subreddits=None):
if subreddits is None:
subreddits = ["earthporn"]
reddit_api = "https://api.reddit.com/r/{}/top".format("+".join(subreddits))
headers = {"User-Agent": USER_AGENT}
request = urllib.request.Request(reddit_api, headers=headers)
with urllib.request.urlopen(request) as response:
data = json.load(response)
for child in data["data"]["children"]:
# Skip posts that are not pictures
if child["kind"] != "t3":
continue
image = child["data"]["preview"]["images"][0]["source"]
aspect_ratio = image["width"] / image["height"]
if (
image["width"] >= min_width
and image["height"] >= min_height
and aspect_ratio >= min_aspect
):
return {
"width": image["width"],
"height": image["height"],
"title": child["data"]["title"],
"url": child["data"]["url"],
}
def set_wallpaper(url, path="wallpaper.jpg"):
with urllib.request.urlopen(url) as response:
with open(path, "wb") as f:
shutil.copyfileobj(response, f)
subprocess.check_call(["feh", "--bg-fill", path])
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"subreddit", nargs="+", help="The subreddit to download the top images from."
)
parser.add_argument(
"--min-width", default="1920", help="Minimum height of the image.", type=int
)
parser.add_argument(
"--min-height", default="1080", help="Minimum width of the image.", type=int
)
parser.add_argument(
"--image-path", default=Path.home() / ".background-image", help="Path to save wallpaper at."
)
return parser.parse_args()
args = parse_args()
image = find_top_wallpaper(args.min_width, args.min_height, subreddits=args.subreddit)
print('Downloading "{}"...'.format(image["title"]))
set_wallpaper(image["url"], args.image_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment