· 4 years ago · Sep 06, 2021, 05:04 AM
1import requests
2import json
3
4
5class Reddit(object):
6
7 def __init__(self, client_id, secret_key, username, password, headers = None, user_info = None):
8 self.client_id = client_id
9 self.secret_key = secret_key
10 self.username = username
11 self.password = password
12 self.headers = self.get_headers()
13
14
15 def connect(self):
16 auth = requests.auth.HTTPBasicAuth(self.client_id, self.secret_key)
17
18 data = {
19 'grant_type': 'password',
20 'username': self.username,
21 'password': self.password
22 }
23
24
25
26 response = requests.post('https://www.reddit.com/api/v1/access_token', auth=auth, data=data, headers=self.headers)
27
28
29 TOKEN = response.json()['access_token']
30
31 self.headers['Authorization'] = f'bearer {TOKEN}'
32
33
34 def get_headers(self):
35
36 headers = {
37 'User-Agent': 'MyAPI/0.0.1',
38 'Authorization': '',
39 }
40 return headers
41
42
43 def user_information(self, headers):
44 mydata = requests.get('https://oauth.reddit.com/api/v1/me', headers=headers)
45
46 user_data = {
47 'total_karma': mydata.json()['total_karma'],
48 'banner_img': mydata.json()['subreddit']['banner_img'],
49 'display_name': mydata.json()['name'],
50 'icon_img': mydata.json()['icon_img'],
51 'inbox_count': mydata.json()['inbox_count']
52 }
53 return user_data
54
55 def user_inbox(self, headers):
56 mydata = requests.get('https://oauth.reddit.com/message/unread', headers=headers)
57 mail_data = []
58 inboxdata = mydata.json()['data']['children']
59 for i in range(len(inboxdata)):
60 author = inboxdata[i]['data']['author']
61 subreddit = inboxdata[i]['data']['subreddit']
62 message = inboxdata[i]['data']['body']
63 mail_data.append({
64 'author': author,
65 'subreddit': subreddit,
66 'message': message})
67 return mail_data