forked from ma2za/python-substack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
484 lines (364 loc) · 13.1 KB
/
api.py
File metadata and controls
484 lines (364 loc) · 13.1 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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
import base64
import logging
import os
from datetime import datetime
from urllib.parse import urljoin
import requests
from substack.exceptions import SubstackAPIException, SubstackRequestException
logger = logging.getLogger(__name__)
__all__ = ["Api"]
class Api:
"""
A python interface into the Substack API
"""
def __init__(
self,
email=None,
password=None,
base_url=None,
publication_url=None,
debug=False,
):
"""
To create an instance of the substack.Api class:
>>> import substack
>>> api = substack.Api(email="substack email", password="substack password")
Args:
email:
password:
base_url:
The base URL to use to contact the Substack API.
Defaults to https://substack.com/api/v1.
"""
self.base_url = base_url or "https://substack.com/api/v1"
if debug:
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
self._session = requests.Session()
if email is not None and password is not None:
self.login(email, password)
# if the user provided a publication url, then use that
if publication_url:
import re
# Regular expression to extract subdomain name
match = re.search(r"https://(.*).substack.com", publication_url.lower())
subdomain = match.group(1) if match else None
user_publications = self.get_user_publications()
# search through publications to find the publication with the matching subdomain
for publication in user_publications:
if publication['subdomain'] == subdomain:
# set the current publication to the users publication
user_publication = publication
break
else:
# get the users primary publication
user_publication = self.get_user_primary_publication()
# set the current publication to the users primary publication
self.change_publication(user_publication)
def login(self, email, password) -> dict:
"""
Login to the substack account.
Args:
email: substack account email
password: substack account password
"""
response = self._session.post(
f"{self.base_url}/login",
json={
"captcha_response": None,
"email": email,
"for_pub": "",
"password": password,
"redirect": "/",
},
)
return Api._handle_response(response=response)
def signin_for_pub(self, publication):
"""
Complete the signin process
"""
response = self._session.get(
f"https://substack.com/sign-in?redirect=%2F&for_pub={publication['subdomain']}",
)
def change_publication(self, publication):
"""
Change the publication URL
"""
self.publication_url = urljoin(publication['publication_url'], "api/v1")
# sign-in to the publication
self.signin_for_pub(publication)
@staticmethod
def _handle_response(response: requests.Response):
"""
Internal helper for handling API responses from the Substack server.
Raises the appropriate exceptions when necessary; otherwise, returns the
response.
"""
if not (200 <= response.status_code < 300):
raise SubstackAPIException(response.status_code, response.text)
try:
return response.json()
except ValueError:
raise SubstackRequestException("Invalid Response: %s" % response.text)
def get_user_id(self):
profile = self.get_user_profile()
user_id = profile['id']
return user_id
def get_publication_url(self, publication):
"""
Gets the publication url
"""
custom_domain = publication['custom_domain']
if not custom_domain:
publication_url = f"https://{publication['subdomain']}.substack.com"
else:
publication_url = f"https://{custom_domain}"
return publication_url
def get_user_primary_publication(self):
"""
Gets the users primary publication
"""
profile = self.get_user_profile()
primary_publication = profile['primaryPublication']
primary_publication['publication_url'] = self.get_publication_url(primary_publication)
return primary_publication
def get_user_publications(self):
"""
Gets the users publications
"""
profile = self.get_user_profile()
# Loop through users "publicationUsers" list, and return a list of dictionaries of "name", and "subdomain", and "id"
user_publications = []
for publication in profile['publicationUsers']:
pub = publication['publication']
pub['publication_url'] = self.get_publication_url(pub)
user_publications.append(pub)
return user_publications
def get_user_profile(self):
"""
Gets the users profile
"""
response = self._session.get(f"{self.base_url}/user/profile/self")
return Api._handle_response(response=response)
def get_user_settings(self):
"""
Get list of users.
Returns:
"""
response = self._session.get(f"{self.base_url}/settings")
return Api._handle_response(response=response)
def get_publication_users(self):
"""
Get list of users.
Returns:
"""
response = self._session.get(f"{self.publication_url}/publication/users")
return Api._handle_response(response=response)
def get_publication_subscriber_count(self):
"""
Get subscriber count.
Returns:
"""
response = self._session.get(f"{self.publication_url}/publication_launch_checklist")
return Api._handle_response(response=response)['subscriberCount']
def get_published_posts(self, offset=0, limit=25, order_by="post_date", order_direction="desc"):
"""
Get list of published posts for the publication.
"""
response = self._session.get(
f"{self.publication_url}/post_management/published",
params={"offset": offset, "limit": limit, "order_by": order_by, "order_direction": order_direction},
)
return Api._handle_response(response=response)
def get_posts(self) -> dict:
"""
Returns:
"""
response = self._session.get(f"{self.base_url}/reader/posts")
return Api._handle_response(response=response)
def get_drafts(self, filter=None, offset=None, limit=None):
"""
Args:
filter:
offset:
limit:
Returns:
"""
response = self._session.get(
f"{self.publication_url}/drafts",
params={"filter": filter, "offset": offset, "limit": limit},
)
return Api._handle_response(response=response)
def get_draft(self, draft_id):
"""
Gets a draft given it's id.
"""
response = self._session.get(f"{self.publication_url}/drafts/{draft_id}")
return Api._handle_response(response=response)
def delete_draft(self, draft_id):
"""
Args:
draft_id:
Returns:
"""
response = self._session.delete(f"{self.publication_url}/drafts/{draft_id}")
return Api._handle_response(response=response)
def post_draft(self, body) -> dict:
"""
Args:
body:
Returns:
"""
response = self._session.post(f"{self.publication_url}/drafts", json=body)
return Api._handle_response(response=response)
def put_draft(
self,
draft,
**kwargs
) -> dict:
"""
Args:
draft:
**kwargs:
Returns:
"""
response = self._session.put(
f"{self.publication_url}/drafts/{draft}",
json=kwargs,
)
return Api._handle_response(response=response)
def prepublish_draft(self, draft) -> dict:
"""
Args:
draft: draft id
Returns:
"""
response = self._session.get(
f"{self.publication_url}/drafts/{draft}/prepublish"
)
return Api._handle_response(response=response)
def publish_draft(
self, draft, send: bool = True, share_automatically: bool = False
) -> dict:
"""
Args:
draft: draft id
send:
share_automatically:
Returns:
"""
response = self._session.post(
f"{self.publication_url}/drafts/{draft}/publish",
json={"send": send, "share_automatically": share_automatically},
)
return Api._handle_response(response=response)
def schedule_draft(self, draft, draft_datetime: datetime) -> dict:
"""
Args:
draft: draft id
draft_datetime: datetime to schedule the draft
Returns:
"""
response = self._session.post(
f"{self.publication_url}/drafts/{draft}/schedule",
json={"post_date": draft_datetime.isoformat()},
)
return Api._handle_response(response=response)
def unschedule_draft(self, draft) -> dict:
"""
Args:
draft: draft id
Returns:
"""
response = self._session.post(
f"{self.publication_url}/drafts/{draft}/schedule", json={"post_date": None}
)
return Api._handle_response(response=response)
def get_image(self, image: str):
"""
This method generates a new substack link that contains the image.
Args:
image: filepath or original url of image.
Returns:
"""
if os.path.exists(image):
with open(image, "rb") as file:
image = b"data:image/jpeg;base64," + base64.b64encode(file.read())
response = self._session.post(
f"{self.publication_url}/image",
data={"image": image},
)
return Api._handle_response(response=response)
def get_categories(self):
"""
Retrieve list of all available categories.
Returns:
"""
response = self._session.get(f"{self.base_url}/categories")
return Api._handle_response(response=response)
def get_category(self, category_id, category_type, page):
"""
Args:
category_id:
category_type:
page:
Returns:
"""
response = self._session.get(
f"{self.base_url}/category/public/{category_id}/{category_type}",
params={"page": page},
)
return Api._handle_response(response=response)
def get_single_category(self, category_id, category_type, page=None, limit=None):
"""
Args:
category_id:
category_type: paid or all
page: by default substack retrieves only the first 25 publications in the category. If this is left None,
then all pages will be retrieved. The page size is 25 publications.
limit:
Returns:
"""
if page is not None:
output = self.get_category(category_id, category_type, page)
else:
publications = []
page = 0
while True:
page_output = self.get_category(category_id, category_type, page)
publications.extend(page_output.get("publications", []))
if (
limit is not None and limit <= len(publications)
) or not page_output.get("more", False):
publications = publications[:limit]
break
page += 1
output = {
"publications": publications,
"more": page_output.get("more", False),
}
return output
def delete_all_drafts(self):
"""
Returns:
"""
response = None
while True:
drafts = self.get_drafts(filter="draft", limit=10, offset=0)
if len(drafts) == 0:
break
for draft in drafts:
response = self.delete_draft(draft.get("id"))
return response
def get_sections(self):
"""
Get a list of the sections of your publication.
TODO: this is hacky but I cannot find another place where to get the sections.
Returns:
"""
response = self._session.get(
f"{self.publication_url}/subscriptions",
)
content = Api._handle_response(response=response)
sections = [p.get("sections") for p in content.get("publications") if p.get("hostname") in self.publication_url]
return sections[0]