-
Notifications
You must be signed in to change notification settings - Fork 0
/
reddit.py
52 lines (40 loc) · 1.13 KB
/
reddit.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from urllib.error import HTTPError
from urllib.request import urlopen
from dotenv import load_dotenv
import praw
import enum
import os
load_dotenv('.env')
class Category(enum.Enum):
HOT = "hot"
TOP = "top"
NEW = "new"
class RedditClientManager:
def __init__(self):
self.client_id = os.getenv("REDDIT_CLIENT_ID")
self.client_secret = os.getenv("REDDIT_CLIENT_SECRET")
self.user_agent = os.getenv("REDDIT_USER_AGENT")
@property
def reddit_client(self):
'''
Return reddit client
'''
return praw.Reddit(
client_id=self.client_id,
client_secret=self.client_secret,
user_agent=self.user_agent
)
def download_post(post_url: str, img_name: str) -> None:
'''
Downloads the image from the given url
'''
extension = os.path.splitext(post_url)[-1]
if not extension:
return False
try:
img_data = urlopen(post_url).read()
with open(f'{img_name}{extension}', 'wb') as img:
img.write(img_data)
return True
except (HTTPError, WindowsError):
return False