-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathredditbackground.py
38 lines (31 loc) · 1.19 KB
/
redditbackground.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import requests
import urllib.request
import os
import time
from random import shuffle
from config import subreddits, pictures_path
headers = {"User-Agent": "backgroundbyreddit:v1.0.0 (by /u/wormywormm)"}
# Download new pictures
the_children = []
for subreddit in subreddits:
resp = requests.get(f"https://www.reddit.com{subreddit}/new.json?raw_json=1")
resp.raise_for_status()
the_children += resp.json()["data"]["children"]
time.sleep(2)
shuffle(the_children) # mix up the order of the links
# Remove existing pictures except default.
pics = os.listdir(pictures_path)
pics_to_delete = [pic for pic in pics if pic[0] != "."]
pics_to_delete.pop() # keep one picture so the directory is never empty
for filename in pics_to_delete:
os.remove(f"{pictures_path}/{filename}")
for child in the_children:
link = child["data"]["url"]
extention = link.split(".")[-1]
pid = child["data"]["id"]
name_of_local_file = f"{pictures_path}/{pid}.{extention}"
try:
if not "com" in extention and len(extention) <= 4:
urllib.request.urlretrieve(link, name_of_local_file)
except Exception as e: # sometimes the extention is not present, wrong, or wack
print(e)