-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
reddit.py
341 lines (269 loc) · 8.79 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
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import datetime
import enum
import html
import logging
from abc import ABC, ABCMeta, abstractmethod, abstractproperty
from typing import Annotated, List, Literal, Optional, Tuple, Union
import aiohttp
from pydantic import BaseModel, Field
ACCESS_TOKEN_URL = "https://www.reddit.com/api/v1/access_token"
OAUTH_BASE_URL = "https://oauth.reddit.com"
USER_AGENT = "ModOverseer by /u/Galarzaa"
log = logging.getLogger("overseer")
def token_request(func):
"""Makes sure the current token is valid before performing a request.
If the token is expired or there's no saved token yet, a new access token is requested."""
async def wrapper(*args):
# If token is expired, get new token before
if args[0].token is None or datetime.datetime.now() >= args[0].expire_time:
await args[0].get_access_token()
return await func(*args)
return wrapper
class RedditClient:
"""Reddit API client
It does not handle refresh token generation, it requires a previously acquire refresh token.
It can handle acesss token generation, every time a request is used, the expire time of the token is checked first.
"""
def __init__(self, refresh_token, client, secret, loop=None):
"""Creates an instance of the client.
:param refresh_token: The refresh token used to get new access tokens.
:param client: The application's client ID.
:param secret: The application's client secret.
:param loop: The event loop used by the client.
"""
self.refresh_token = refresh_token
self.auth = aiohttp.BasicAuth(client, secret)
self.client = client
self.secret = secret
self.auth_session: aiohttp.ClientSession = None
self.api_session: aiohttp.ClientSession = None
self.expire_time = None
self.token = None
async def start(self):
self.auth_session = aiohttp.ClientSession(auth=self.auth, headers={'User-Agent': USER_AGENT})
async def stop(self):
await self.auth_session.close()
if self.api_session:
await self.api_session.close()
async def get_access_token(self):
"""Gets a new access token using the current refresh token."""
log.info(f"[{self.__class__.__name__}] Getting access token")
try:
params = {
'grant_type': 'refresh_token',
'refresh_token': self.refresh_token
}
async with self.auth_session.post(ACCESS_TOKEN_URL, data=params) as resp:
data = await resp.json()
self.token = data['access_token']
self.expire_time = datetime.datetime.now() + datetime.timedelta(seconds=data['expires_in'] - 10)
self.api_session = aiohttp.ClientSession(headers={
'User-Agent': USER_AGENT,
'Authorization': f'bearer {self.token}'
})
log.info(f"[{self.__class__.__name__}] Access token obtained.")
return True
except Exception as e:
log.exception(f"[{self.__class__.__name__}] Exception while getting access token.")
return False
@token_request
async def get_mod_queue(self, subreddit) -> List[Union['QueueCommentEntry', 'QueueLinkEntry']]:
"""Gets the current ModQueue contents."""
log.info(f"[{self.__class__.__name__}] Getting modqueue")
async with self.api_session.get(f"{OAUTH_BASE_URL}/r/{subreddit}/about/modqueue") as resp:
resp.raise_for_status()
js = await resp.json()
try:
listing = RedditListing.model_validate(js)
log.info(f"[{self.__class__.__name__}] {len(listing.data.children)} queue entries found.")
return listing.data.children
except Exception:
log.exception(f"[{self.__class__.__name__}] Exception while getting mod queue.")
raise
@token_request
async def get_subreddit_about(self, subreddit):
"""Gets the general info of a subreddit."""
log.info(f"[{self.__class__.__name__}] Getting subreddit info")
async with self.api_session.get(f"{OAUTH_BASE_URL}/r/{subreddit}/about") as resp:
js = await resp.json()
if "error" in js:
return None
try:
return AboutSubreddit(**js["data"])
except Exception as e:
log.exception(f"[{self.__class__.__name__}] Exception while getting subreddit's information.")
raise
@staticmethod
def get_user_url(username: str) -> str:
return f"https://www.reddit.com/u/{username}"
class EntryKind(enum.Enum):
LINK = "t3"
COMMENT = "t1"
class AboutSubreddit:
def __init__(self, **kwargs):
self.subscribers = kwargs.get("subscribers")
self.active_users = kwargs.get("accounts_active")
class CommonQueueEntry(metaclass=ABCMeta):
@property
@abstractmethod
def id(self):
...
@property
@abstractmethod
def post_title(self):
...
@property
@abstractmethod
def post_author(self):
...
@property
@abstractmethod
def post_url(self):
...
@property
@abstractmethod
def created(self):
...
@property
@abstractmethod
def user_reports(self):
...
@property
@abstractmethod
def mod_reports(self):
...
@property
@abstractmethod
def score(self):
...
class CommonData(BaseModel):
user_reports: List[Tuple[str, int, bool, bool]]
mod_reports: List[Tuple[str, str]]
ups: int
score: int
approved_by: Optional[str]
approved: bool
created_utc: datetime.datetime
permalink: str
num_reports: int
mod_reason_by: Optional[str]
removed: bool
id: str
class CommentData(CommonData):
approved_at_utc: Optional[datetime.datetime]
author_is_blocked: bool
edited: Union[bool | float]
banned_by: Optional[Union[bool, str]] = None
author_flair_type: str
total_awards_received: int
author: str
link_author: str
likes: Optional[int]
ban_note: Optional[str] = None
banned_at_utc: Optional[datetime.datetime]
mod_reason_title: Optional[str]
num_comments: int
parent_id: str
author_fullname: str
body: str
link_title: str
name: str
downs: int
is_submitter: bool
link_id: str
score_hidden: bool
link_permalink: str
report_reasons: List
created: datetime.datetime
link_url: str
locked: bool
class QueueCommentEntry(BaseModel, CommonQueueEntry):
kind: Literal['t1']
data: CommentData
@property
def id(self):
return self.data.id
@property
def post_title(self):
return html.unescape(self.data.link_title)
@property
def post_author(self):
return self.data.link_author
@property
def post_url(self):
return self.data.link_permalink
@property
def created(self):
return self.data.created_utc
@property
def user_reports(self):
return self.data.user_reports
@property
def mod_reports(self):
return self.data.mod_reports
@property
def score(self):
return self.data.score
@property
def comment_body(self):
return self.data.body
@property
def comment_author(self):
return self.data.author
@property
def comment_url(self):
return f"https://reddit.com{self.data.permalink}"
class LinkData(CommonData):
approved_at_utc: Optional[datetime.datetime]
selftext: str
title: str
upvote_ratio: float
ignore_reports: bool
is_original_content: bool
author_is_blocked: bool
author: str
url: str
is_self: bool
thumbnail: str
class QueueLinkEntry(BaseModel, CommonQueueEntry):
kind: Literal['t3']
data: LinkData
@property
def id(self):
return self.data.id
@property
def post_title(self):
return html.unescape(self.data.title)
@property
def post_author(self):
return self.data.author
@property
def created(self):
return self.data.created_utc
@property
def user_reports(self):
return self.data.user_reports
@property
def mod_reports(self):
return self.data.mod_reports
@property
def score(self):
return self.data.score
@property
def post_text(self):
return self.data.selftext
@property
def post_url(self):
return self.data.url
@property
def thumbnail(self):
return self.data.thumbnail
ListingDataChildren = Annotated[
Union[QueueCommentEntry, QueueLinkEntry],
Field(discriminator="kind")
]
class ListingData(BaseModel):
children: List[ListingDataChildren]
class RedditListing(BaseModel):
kind: Literal["Listing"]
data: ListingData