Skip to content

Commit ad00345

Browse files
committed
first features
1 parent 760629c commit ad00345

5 files changed

Lines changed: 240 additions & 21 deletions

File tree

‎examples/publish_post.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import os
2+
3+
from dotenv import load_dotenv
4+
5+
from substack import Api
6+
7+
load_dotenv()
8+
9+
content = ""
10+
title = ""
11+
subtitle = ""
12+
13+
api = Api(
14+
email=os.getenv("EMAIL"),
15+
password=os.getenv("PASSWORD"),
16+
publication_url=os.getenv("PUBLICATION_URL"),
17+
)
18+
19+
body = f'{{"type":"doc","content": {content}}}'
20+
21+
draft = api.post_draft(
22+
[{"id": os.getenv("USER_ID"), "is_guest": False}],
23+
title=title,
24+
subtitle=subtitle,
25+
body=body,
26+
)
27+
28+
api.prepublish_draft(draft.get("id"))
29+
30+
api.publish_draft(draft.get("id"))

‎substack/__init__.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""A library that provides a Python interface to the Substack API."""
22

3-
__author__ = 'Paolo Mazza'
4-
__email__ = 'mazzapaolo2019@gmail.com'
5-
__license__ = 'MIT License'
6-
__version__ = '1.0'
7-
__url__ = 'https://github.com/hogier/python-substack'
8-
__download_url__ = 'https://pypi.python.org/pypi/python-substack'
9-
__description__ = 'A Python wrapper around the Substack API'
3+
__author__ = "Paolo Mazza"
4+
__email__ = "mazzapaolo2019@gmail.com"
5+
__license__ = "MIT License"
6+
__version__ = "1.0"
7+
__url__ = "https://github.com/hogier/python-substack"
8+
__download_url__ = "https://pypi.python.org/pypi/python-substack"
9+
__description__ = "A Python wrapper around the Substack API"
1010

1111
from .api import Api

‎substack/api.py‎

Lines changed: 141 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,14 @@ class Api:
1414
1515
"""
1616

17-
def __init__(self, email: str, password: str, base_url: str | None = None, debug: bool = False):
17+
def __init__(
18+
self,
19+
email: str,
20+
password: str,
21+
base_url: str | None = None,
22+
publication_url: str | None = None,
23+
debug: bool = False,
24+
):
1825
"""
1926
2027
To create an instance of the substack.Api class:
@@ -29,26 +36,32 @@ def __init__(self, email: str, password: str, base_url: str | None = None, debug
2936
Defaults to https://substack.com/api/v1.
3037
"""
3138
self.base_url = base_url or "https://substack.com/api/v1"
39+
self.publication_url = publication_url
3240

3341
if debug:
3442
logging.basicConfig()
3543
logging.getLogger().setLevel(logging.DEBUG)
3644

3745
self._init_session(email, password)
3846

39-
def login(self, email: str, password: str):
47+
def login(self, email: str, password: str) -> dict:
4048
"""
4149
4250
Args:
4351
email:
4452
password:
4553
"""
4654

47-
response = self._session.post(f"{self.base_url}/login", json={"captcha_response": None,
48-
"email": email,
49-
"for_pub": "",
50-
"password": password,
51-
"redirect": "/"})
55+
response = self._session.post(
56+
f"{self.base_url}/login",
57+
json={
58+
"captcha_response": None,
59+
"email": email,
60+
"for_pub": "",
61+
"password": password,
62+
"redirect": "/",
63+
},
64+
)
5265
return Api._handle_response(response=response)
5366

5467
def _init_session(self, email, password):
@@ -71,4 +84,124 @@ def _handle_response(response: requests.Response):
7184
try:
7285
return response.json()
7386
except ValueError:
74-
raise SubstackRequestException('Invalid Response: %s' % response.text)
87+
raise SubstackRequestException("Invalid Response: %s" % response.text)
88+
89+
def get_publication_users(self):
90+
"""
91+
92+
:return:
93+
"""
94+
response = self._session.get(f"{self.publication_url}/publication/users")
95+
96+
return Api._handle_response(response=response)
97+
98+
def get_posts(self) -> dict:
99+
"""
100+
101+
:return:
102+
"""
103+
response = self._session.get(f"{self.base_url}/reader/posts")
104+
105+
return Api._handle_response(response=response)
106+
107+
def get_drafts(self, filter: str = None, offset: int = None, limit: int = None):
108+
response = self._session.get(
109+
f"{self.publication_url}/drafts",
110+
params={"filter": filter, "offset": offset, "limit": limit},
111+
)
112+
return Api._handle_response(response=response)
113+
114+
def post_draft(
115+
self,
116+
draft_bylines: list,
117+
title: str = None,
118+
subtitle: str = None,
119+
body: str = None,
120+
) -> dict:
121+
"""
122+
123+
Args:
124+
draft_bylines:
125+
title:
126+
subtitle:
127+
body:
128+
129+
Returns:
130+
131+
"""
132+
response = self._session.post(
133+
f"{self.publication_url}/drafts",
134+
json={
135+
"draft_bylines": draft_bylines,
136+
"draft_title": title,
137+
"draft_subtitle": subtitle,
138+
"draft_body": body,
139+
},
140+
)
141+
return Api._handle_response(response=response)
142+
143+
def put_draft(
144+
self,
145+
draft: str,
146+
title: str = None,
147+
subtitle: str = None,
148+
body: str = None,
149+
cover_image: str = None,
150+
) -> dict:
151+
"""
152+
153+
Args:
154+
draft:
155+
title:
156+
subtitle:
157+
body:
158+
cover_image:
159+
160+
Returns:
161+
162+
"""
163+
164+
response = self._session.put(
165+
f"{self.publication_url}/drafts/{draft}",
166+
json={
167+
"draft_title": title,
168+
"draft_subtitle": subtitle,
169+
"draft_body": body,
170+
"cover_image": cover_image,
171+
},
172+
)
173+
return Api._handle_response(response=response)
174+
175+
def prepublish_draft(self, draft: str) -> dict:
176+
"""
177+
178+
Args:
179+
draft:
180+
181+
Returns:
182+
183+
"""
184+
185+
response = self._session.get(
186+
f"{self.publication_url}/drafts/{draft}/prepublish"
187+
)
188+
return Api._handle_response(response=response)
189+
190+
def publish_draft(
191+
self, draft: str, send: bool = True, share_automatically: bool = False
192+
) -> dict:
193+
"""
194+
195+
Args:
196+
draft:
197+
send:
198+
share_automatically:
199+
200+
Returns:
201+
202+
"""
203+
response = requests.post(
204+
f"{self.publication_url}/drafts/{draft}/publish",
205+
json={"send": send, "share_automatically": share_automatically},
206+
)
207+
return Api._handle_response(response=response)

‎substack/exceptions.py‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,27 @@
22

33

44
class SubstackAPIException(Exception):
5-
65
def __init__(self, status_code, text):
76
try:
87
json_res = json.loads(text)
98
except ValueError:
10-
self.message = f'Invalid JSON error message from Substack: {text}'
9+
self.message = f"Invalid JSON error message from Substack: {text}"
1110
else:
12-
self.message = ", ".join(list(map(lambda error: error.get("msg", ""), json_res.get("errors", []))))
11+
self.message = ", ".join(
12+
list(
13+
map(lambda error: error.get("msg", ""), json_res.get("errors", []))
14+
)
15+
)
1316
self.message = self.message or json_res.get("error", "")
1417
self.status_code = status_code
1518

1619
def __str__(self):
17-
return f'APIError(code={self.status_code}): {self.message}'
20+
return f"APIError(code={self.status_code}): {self.message}"
1821

1922

2023
class SubstackRequestException(Exception):
2124
def __init__(self, message):
2225
self.message = message
2326

2427
def __str__(self):
25-
return f'SubstackRequestException: {self.message}'
28+
return f"SubstackRequestException: {self.message}"

‎tests/substack/test_api.py‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,64 @@
1+
import os
12
import unittest
23

4+
from dotenv import load_dotenv
5+
36
from substack import Api
47
from substack.exceptions import SubstackAPIException
58

9+
load_dotenv()
610

7-
class ApiTest(unittest.TestCase):
811

12+
class ApiTest(unittest.TestCase):
913
def test_api_exception(self):
1014
with self.assertRaises(SubstackAPIException):
1115
Api(email="", password="")
16+
17+
def test_login(self):
18+
api = Api(
19+
email=os.getenv("EMAIL"),
20+
password=os.getenv("PASSWORD"),
21+
publication_url=os.getenv("PUBLICATION_URL"),
22+
)
23+
self.assertIsNotNone(api)
24+
25+
def test_get_posts(self):
26+
api = Api(email=os.getenv("EMAIL"), password=os.getenv("PASSWORD"))
27+
posts = api.get_posts()
28+
self.assertIsNotNone(posts)
29+
30+
def test_get_drafts(self):
31+
api = Api(
32+
email=os.getenv("EMAIL"),
33+
password=os.getenv("PASSWORD"),
34+
publication_url=os.getenv("PUBLICATION_URL"),
35+
)
36+
drafts = api.get_drafts()
37+
self.assertIsNotNone(drafts)
38+
39+
def test_post_draft(self):
40+
api = Api(
41+
email=os.getenv("EMAIL"),
42+
password=os.getenv("PASSWORD"),
43+
publication_url=os.getenv("PUBLICATION_URL"),
44+
)
45+
posted_draft = api.post_draft([{"id": os.getenv("USER_ID"), "is_guest": False}])
46+
self.assertIsNotNone(posted_draft)
47+
48+
def test_publication_users(self):
49+
api = Api(
50+
email=os.getenv("EMAIL"),
51+
password=os.getenv("PASSWORD"),
52+
publication_url=os.getenv("PUBLICATION_URL"),
53+
)
54+
users = api.get_publication_users()
55+
self.assertIsNotNone(users)
56+
57+
def test_put_draft(self):
58+
api = Api(
59+
email=os.getenv("EMAIL"),
60+
password=os.getenv("PASSWORD"),
61+
publication_url=os.getenv("PUBLICATION_URL"),
62+
)
63+
posted_draft = api.put_draft("62667935")
64+
self.assertIsNotNone(posted_draft)

0 commit comments

Comments
 (0)