· 4 years ago · Sep 06, 2021, 03:00 PM
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 response = requests.post('https://www.reddit.com/api/v1/access_token', auth=auth, data=data, headers=self.headers)
25
26
27 TOKEN = response.json()['access_token']
28
29 self.headers['Authorization'] = f'bearer {TOKEN}'
30
31
32 def get_headers(self):
33
34 headers = {
35 'User-Agent': 'MyAPI/0.0.1',
36 'Authorization': '',
37 }
38 return headers
39
40
41 def user_information(self, headers):
42 mydata = requests.get('https://oauth.reddit.com/api/v1/me', headers=headers)
43
44 user_data = {
45 'total_karma': mydata.json()['total_karma'],
46 'banner_img': mydata.json()['subreddit']['banner_img'],
47 'display_name': mydata.json()['name'],
48 'icon_img': mydata.json()['icon_img'],
49 'inbox_count': mydata.json()['inbox_count']
50 }
51 return user_data
52
53 def user_inbox(self, headers):
54 mydata = requests.get('https://oauth.reddit.com/message/unread', headers=headers)
55 mail_data = []
56 inboxdata = mydata.json()['data']['children']
57 #print(json.dumps(inboxdata, indent = 2))
58 for i in range(len(inboxdata)):
59 author = inboxdata[i]['data']['author']
60 subreddit = inboxdata[i]['data']['subreddit']
61 message = inboxdata[i]['data']['body']
62 id = inboxdata[i]['data']['name']
63 parent = inboxdata[i]['data']['parent_id']
64 mail_data.append({
65 'author': author,
66 'subreddit': subreddit,
67 'message': message,
68 'id': id,
69 'parent_id': parent})
70 return mail_data
71
72 def mark_read(self, headers, id):
73 mydata = requests.post('https://oauth.reddit.com/api/read_message/', data={'id': id},headers=headers)
74
75 def comment_reply(self, headers, comment_id, user_comment):
76 mydata = requests.post('https://oauth.reddit.com/api/comment/', data={'thing_id': comment_id, 'text': user_comment},headers=headers)