Repository navigation
Expand file tree
/
Copy path_pushshift_api.py
More file actions
130 lines (119 loc) · 4.55 KB
/
Copy path_pushshift_api.py
File metadata and controls
130 lines (119 loc) · 4.55 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import csv
import json
import time
from dataclasses import dataclass
import pandas as pd
import requests
@dataclass
class api_agent:
"""
Class object for making various reddit API requests.
----------
paramaters
----------
api_credentials: dictionary containing your api application credentials...
{
"user_agent" : "user_agent",
"user_pass" : "user_pass",
"client_id" : "client_id",
"client_secret" : "client_secret",
"application_name" : "application_name"
}
"""
def __init__(self, api_credentials):
self.user_agent = api_credentials["user_agent"]
self.user_pass = api_credentials["user_pass"]
self.client_id = api_credentials["client_id"]
self.client_secret = api_credentials["client_secret"]
self.application_name = api_credentials["application_name"]
def renew_auth_token(self):
"""
Renew Reddit API O-Auth
"""
auth = requests.auth.HTTPBasicAuth(self.client_id, self.client_secret)
data = {
"grant_type": "password",
"username": self.user_agent,
"password": self.user_pass,
}
self.headers = {"User-Agent": f"{self.application_name}/0.0.0"}
request = requests.post(
"https://www.reddit.com/api/v1/access_token",
auth=auth,
data=data,
headers=self.headers,
)
TOKEN = request.json()["access_token"]
self.headers["Authorization"] = f"bearer {TOKEN}"
def get_top_subreddits(self, payload):
def hit():
try:
r = requests.get(
"https://oauth.reddit.com/subreddits/new",
headers=self.headers,
params=payload,
)
status = r.status_code
print("> http response is:", status)
except Exception:
r = ""
status = " NO HANDSHAKE "
print("> http response is:", status)
return r, status
retry = 0
while True:
retry += 1
r, status = hit()
if status == 200:
break
time.sleep(5 * retry)
print(f" >> rety_#: {retry}")
if retry % 3 == 0:
self.renew_auth_token()
print("\nAUTH_RENEWED\n")
subreddits = json.loads(r.text, strict=False)
return subreddits
def make_subreddits(self, path="subreddit_list.csv"):
self.renew_auth_token()
self.subreddits_path = path
with open(self.subreddits_path, "w", newline="", encoding="utf-8") as _red_list:
_red_writer = csv.writer(_red_list, delimiter=",")
_headers = ["subreddit", "num_subscribers", "creation_utc", "nsfw_bool"]
_red_writer.writerow(_headers)
_payload = {"limit": "100"}
_subreddits = self.get_top_subreddits(_payload)
_before = ""
while len(_subreddits) > 0:
for key in _subreddits["data"]["children"]:
try:
_title = str(key["data"]["title"])
except Exception:
_title = "NA"
try:
_subscribers = str(key["data"]["subscribers"])
except Exception:
_subscribers = "NA"
try:
_created_utc = str(key["data"]["created_utc"])
except Exception:
_created_utc = "NA"
try:
_over18 = str(key["data"]["over18"])
except Exception:
_over18 = "NA"
_after = key["data"]["name"]
_rho = [_title, _subscribers, _created_utc, _over18]
_red_writer.writerow(_rho)
_payload = {"limit": "100", "after": _after}
if _before == _after:
break
else:
print(f" >>> after : {_after}")
_subreddits = self.get_top_subreddits(_payload)
_before = _after
self.subreddits_df = pd.read_csv(self.subreddits_path, low_memory=False)
self.subreddits_df = self.subreddits_df.sort_values(by="num_subscribers", ascending=False)
self.subreddits_df.to_csv(
path_or_buf=self.subreddits_path, sep=",", na_rep="nan", index="subreddit"
)
__all__ = ["api_agent"]