python-substack 0.1.24__py3-none-any.whl → 0.1.25__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
substack/cli.py ADDED
@@ -0,0 +1,224 @@
1
+ import argparse
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import yaml
7
+ from dotenv import load_dotenv
8
+
9
+ from substack import Api
10
+ from substack.post import Post
11
+
12
+
13
+ def _api_from_env(cookies_path=None):
14
+ load_dotenv()
15
+
16
+ cookies_path = cookies_path or os.getenv("COOKIES_PATH")
17
+ cookies_string = os.getenv("COOKIES_STRING")
18
+
19
+ if cookies_path or cookies_string:
20
+ return Api(
21
+ cookies_path=cookies_path,
22
+ cookies_string=cookies_string,
23
+ publication_url=os.getenv("PUBLICATION_URL"),
24
+ )
25
+
26
+ return Api(
27
+ email=os.getenv("EMAIL"),
28
+ password=os.getenv("PASSWORD"),
29
+ publication_url=os.getenv("PUBLICATION_URL"),
30
+ )
31
+
32
+
33
+ def _auth_method(cookies_path=None):
34
+ load_dotenv()
35
+
36
+ if cookies_path:
37
+ return "cookies_path"
38
+ if os.getenv("COOKIES_PATH"):
39
+ return "cookies_path"
40
+ if os.getenv("COOKIES_STRING"):
41
+ return "cookies_string"
42
+ if os.getenv("EMAIL") and os.getenv("PASSWORD"):
43
+ return "email_password"
44
+ return "unknown"
45
+
46
+
47
+ def _title_from_markdown(markdown, fallback):
48
+ for line in markdown.splitlines():
49
+ if line.startswith("# "):
50
+ return line[2:].strip()
51
+ return fallback
52
+
53
+
54
+ def _print_result(result):
55
+ draft = result["draft"]
56
+ print(json.dumps({"draft_id": draft.get("id"), "draft": draft}, indent=2))
57
+
58
+
59
+ def publish_markdown(argv=None):
60
+ parser = argparse.ArgumentParser()
61
+ parser.add_argument("markdown", nargs="?", default="README.md")
62
+ parser.add_argument("-m", "--markdown-file", dest="markdown_file")
63
+ parser.add_argument("--title")
64
+ parser.add_argument("--subtitle", default="")
65
+ parser.add_argument("--audience", default="everyone")
66
+ parser.add_argument("--write-comment-permissions", default="everyone")
67
+ parser.add_argument("--search-engine-title")
68
+ parser.add_argument("--search-engine-description")
69
+ parser.add_argument("--slug")
70
+ parser.add_argument("--draft-section-id", type=int)
71
+ parser.add_argument("--tag", action="append", dest="tags")
72
+ parser.add_argument("--cookies")
73
+ parser.add_argument("--prepublish", action="store_true")
74
+ parser.add_argument("--publish", action="store_true")
75
+ parser.add_argument("--no-send", action="store_false", dest="send", default=True)
76
+ parser.add_argument("--share-automatically", action="store_true")
77
+ args = parser.parse_args(argv)
78
+
79
+ markdown_path = Path(args.markdown_file or args.markdown)
80
+ markdown = markdown_path.read_text(encoding="utf-8")
81
+
82
+ api = _api_from_env(args.cookies)
83
+ result = api.create_draft_from_markdown(
84
+ title=args.title or _title_from_markdown(markdown, markdown_path.stem),
85
+ markdown=markdown,
86
+ subtitle=args.subtitle,
87
+ audience=args.audience,
88
+ write_comment_permissions=args.write_comment_permissions,
89
+ search_engine_title=args.search_engine_title,
90
+ search_engine_description=args.search_engine_description,
91
+ slug=args.slug,
92
+ draft_section_id=args.draft_section_id,
93
+ tags=args.tags,
94
+ prepublish=args.prepublish or args.publish,
95
+ publish=args.publish,
96
+ send=args.send,
97
+ share_automatically=args.share_automatically,
98
+ )
99
+ _print_result(result)
100
+ return 0
101
+
102
+
103
+ def publish_yaml(argv=None):
104
+ parser = argparse.ArgumentParser()
105
+ parser.add_argument("post", nargs="?", default="draft.yaml")
106
+ parser.add_argument("-p", "--post-file", dest="post_file")
107
+ parser.add_argument("--cookies")
108
+ parser.add_argument("--prepublish", action="store_true")
109
+ parser.add_argument("--publish", action="store_true")
110
+ parser.add_argument("--no-send", action="store_false", dest="send", default=True)
111
+ parser.add_argument("--share-automatically", action="store_true")
112
+ args = parser.parse_args(argv)
113
+
114
+ post_path = Path(args.post_file or args.post)
115
+ post_data = yaml.safe_load(post_path.read_text(encoding="utf-8"))
116
+ api = _api_from_env(args.cookies)
117
+
118
+ markdown = post_data.get("markdown")
119
+ markdown_file = post_data.get("markdown_file")
120
+ if markdown_file:
121
+ markdown_path = Path(markdown_file)
122
+ if not markdown_path.is_absolute():
123
+ markdown_path = post_path.parent / markdown_path
124
+ markdown = markdown_path.read_text(encoding="utf-8")
125
+
126
+ if markdown is not None:
127
+ result = api.create_draft_from_markdown(
128
+ title=post_data.get("title"),
129
+ markdown=markdown,
130
+ subtitle=post_data.get("subtitle", ""),
131
+ audience=post_data.get("audience", "everyone"),
132
+ write_comment_permissions=post_data.get(
133
+ "write_comment_permissions", "everyone"
134
+ ),
135
+ search_engine_title=post_data.get("search_engine_title"),
136
+ search_engine_description=post_data.get("search_engine_description"),
137
+ slug=post_data.get("slug"),
138
+ draft_section_id=post_data.get("draft_section_id"),
139
+ tags=post_data.get("tags"),
140
+ prepublish=args.prepublish or args.publish,
141
+ publish=args.publish,
142
+ send=args.send,
143
+ share_automatically=args.share_automatically,
144
+ )
145
+ _print_result(result)
146
+ return 0
147
+
148
+ post = Post(
149
+ post_data.get("title"),
150
+ post_data.get("subtitle", ""),
151
+ api.get_user_id(),
152
+ audience=post_data.get("audience", "everyone"),
153
+ write_comment_permissions=post_data.get(
154
+ "write_comment_permissions", "everyone"
155
+ ),
156
+ )
157
+
158
+ section = post_data.get("section")
159
+ if section:
160
+ post.set_section(section, api.get_sections())
161
+
162
+ for item in post_data.get("body", {}).values():
163
+ if item.get("type") == "captionedImage":
164
+ src = item.get("src", "")
165
+ if not src.startswith("http"):
166
+ image = api.get_image(src)
167
+ item.update({"src": image.get("url")})
168
+ post.add(item)
169
+
170
+ draft = api.post_draft(post.get_draft())
171
+ draft_id = draft.get("id")
172
+
173
+ update_payload = {
174
+ "draft_section_id": post.draft_section_id,
175
+ "search_engine_title": post_data.get("search_engine_title"),
176
+ "search_engine_description": post_data.get("search_engine_description"),
177
+ "slug": post_data.get("slug"),
178
+ }
179
+ update_payload = {
180
+ key: value for key, value in update_payload.items() if value is not None
181
+ }
182
+ if update_payload:
183
+ draft = api.put_draft(draft_id, **update_payload)
184
+
185
+ tags = Api._normalize_tags(post_data.get("tags"))
186
+ if tags:
187
+ api.add_tags_to_post(draft_id, tags)
188
+
189
+ if args.prepublish or args.publish:
190
+ api.prepublish_draft(draft_id)
191
+ if args.publish:
192
+ api.publish_draft(
193
+ draft_id,
194
+ send=args.send,
195
+ share_automatically=args.share_automatically,
196
+ )
197
+
198
+ print(json.dumps({"draft_id": draft_id, "draft": draft}, indent=2))
199
+ return 0
200
+
201
+
202
+ def auth_check(argv=None):
203
+ parser = argparse.ArgumentParser()
204
+ parser.add_argument("--cookies")
205
+ args = parser.parse_args(argv)
206
+
207
+ api = _api_from_env(args.cookies)
208
+ profile = api.get_user_profile()
209
+ primary_publication = api.get_user_primary_publication()
210
+ publications = api.get_user_publications()
211
+
212
+ identity = (
213
+ profile.get("email")
214
+ or profile.get("name")
215
+ or profile.get("handle")
216
+ or str(profile.get("id", "unknown"))
217
+ )
218
+
219
+ print(f"Authenticated as: {identity}")
220
+ print(f"Auth method: {_auth_method(args.cookies)}")
221
+ print(f"Primary publication: {primary_publication.get('name', 'unknown')}")
222
+ print(f"Publication URL: {primary_publication.get('publication_url', 'unknown')}")
223
+ print(f"Available publications: {len(publications)}")
224
+ return 0
@@ -0,0 +1,293 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ try:
7
+ from dotenv import load_dotenv
8
+ except ImportError:
9
+ load_dotenv = None
10
+
11
+ from mcp.server.fastmcp import FastMCP
12
+
13
+ from substack.api import Api
14
+ from substack.post import Post
15
+
16
+ if load_dotenv is not None:
17
+ load_dotenv()
18
+
19
+
20
+ def get_api() -> Api:
21
+ email = os.getenv("EMAIL")
22
+ password = os.getenv("PASSWORD")
23
+ cookies_path = os.getenv("COOKIES_PATH")
24
+ cookies_string = os.getenv("COOKIES_STRING")
25
+ publication_url = os.getenv("PUBLICATION_URL")
26
+
27
+ if cookies_path or cookies_string:
28
+ return Api(
29
+ cookies_path=cookies_path,
30
+ cookies_string=cookies_string,
31
+ publication_url=publication_url,
32
+ )
33
+
34
+ if email and password:
35
+ return Api(
36
+ email=email,
37
+ password=password,
38
+ publication_url=publication_url,
39
+ )
40
+
41
+ raise ValueError(
42
+ "Missing Substack auth configuration: set EMAIL/PASSWORD or COOKIES_PATH/COOKIES_STRING"
43
+ )
44
+
45
+
46
+ def _normalize_tags(tags: Optional[Any]) -> List[str]:
47
+ if tags is None:
48
+ return []
49
+ if isinstance(tags, str):
50
+ return [tags]
51
+ if isinstance(tags, list):
52
+ return [str(tag) for tag in tags]
53
+ raise ValueError("tags must be a string or a list of strings")
54
+
55
+
56
+ mcp = FastMCP("substack")
57
+
58
+
59
+ @mcp.tool()
60
+ async def post_draft_from_markdown(
61
+ title: str,
62
+ markdown: str,
63
+ subtitle: Optional[str] = "",
64
+ audience: str = "everyone",
65
+ write_comment_permissions: str = "everyone",
66
+ search_engine_title: Optional[str] = None,
67
+ search_engine_description: Optional[str] = None,
68
+ slug: Optional[str] = None,
69
+ draft_section_id: Optional[int] = None,
70
+ tags: Optional[Any] = None,
71
+ prepublish: bool = False,
72
+ publish: bool = False,
73
+ send: bool = True,
74
+ share_automatically: bool = False,
75
+ ) -> Dict[str, Any]:
76
+ """Create or update a Substack draft from Markdown.
77
+
78
+ This tool builds a Substack `Post` from markdown content and posts a draft.
79
+ It supports optional tag assignment, prepublish (setup check), and publishing.
80
+
81
+ Args:
82
+ title: Draft title.
83
+ markdown: Markdown body content.
84
+ subtitle: Optional subtitle text.
85
+ audience: One of `everyone`, `only_paid`, `founding`, `only_free`.
86
+ write_comment_permissions: One of `none`, `only_paid`, `everyone`.
87
+ search_engine_title: Optional title for search engine optimization.
88
+ search_engine_description: Optional description for search engine optimization.
89
+ slug: Optional URL slug for the post.
90
+ draft_section_id: Optional section ID for the draft.
91
+ tags: Tag or list of tags to attach to the post.
92
+ prepublish: If true, calls `prepublish_draft` after creation.
93
+ publish: If true, calls `publish_draft` after creation (and optionally prepublish).
94
+ send: Passed to `publish_draft` for newsletter delivery.
95
+ share_automatically: Passed to `publish_draft`.
96
+
97
+ Returns:
98
+ dict containing drafted post (`draft`), optional `tags`, `prepublish`, `publish` results.
99
+
100
+ Examples:
101
+ With the YAML structure from the README, a caller can map fields like:
102
+
103
+ ```yaml
104
+ title: "My Post Title"
105
+ subtitle: "My Post Subtitle"
106
+ audience: "everyone"
107
+ write_comment_permissions: "everyone"
108
+ markdown: |
109
+ # Hello
110
+
111
+ This is the body.
112
+
113
+ tags:
114
+ - python
115
+ - substack
116
+ prepublish: true
117
+ publish: true
118
+ send: false
119
+ share_automatically: true
120
+ ```
121
+
122
+ Then invoke via MCP directly:
123
+
124
+ ```python
125
+ from substack_mcp.mcp_server import post_draft_from_markdown
126
+
127
+ result = await post_draft_from_markdown(
128
+ title='My Post Title',
129
+ markdown='# Hello\n\nThis is the body.',
130
+ subtitle='My Post Subtitle',
131
+ audience='everyone',
132
+ write_comment_permissions='everyone',
133
+ tags=['python', 'substack'],
134
+ prepublish=True,
135
+ publish=False, # set true when ready
136
+ )
137
+ print(result)
138
+ ```
139
+
140
+ A longer process with manual prepublish/publish calls:
141
+
142
+ ```python
143
+ from substack_mcp.mcp_server import (
144
+ post_draft_from_markdown,
145
+ prepublish_draft,
146
+ publish_draft,
147
+ add_tags,
148
+ )
149
+
150
+ d = await post_draft_from_markdown(
151
+ title='Long flow',
152
+ markdown='Content',
153
+ tags=['a','b'],
154
+ publish=False,
155
+ )
156
+ draft_id = d['draft']['id']
157
+
158
+ await add_tags(draft_id, ['post-tag', 'news'])
159
+ await prepublish_draft(draft_id)
160
+ await publish_draft(draft_id, send=True, share_automatically=True)
161
+ ```
162
+
163
+ This docstring example is meant to mirror the YAML-driven workflow and show how to decompose the same operations into explicit tool calls.
164
+ """
165
+ client = get_api()
166
+ user_id = client.get_user_id()
167
+
168
+ post = Post(
169
+ title=title,
170
+ subtitle=subtitle or "",
171
+ user_id=user_id,
172
+ audience=audience,
173
+ write_comment_permissions=write_comment_permissions,
174
+ )
175
+
176
+ post.from_markdown(markdown, api=client)
177
+
178
+ draft = client.post_draft(post.get_draft())
179
+
180
+ update_payload: Dict[str, Any] = {}
181
+ if search_engine_title:
182
+ update_payload["search_engine_title"] = search_engine_title
183
+ if search_engine_description:
184
+ update_payload["search_engine_description"] = search_engine_description
185
+ if slug:
186
+ update_payload["slug"] = slug
187
+ if draft_section_id is not None:
188
+ update_payload["draft_section_id"] = draft_section_id
189
+
190
+ if update_payload:
191
+ draft = client.put_draft(draft.get("id"), **update_payload)
192
+
193
+ tags_list = _normalize_tags(tags)
194
+ tags_result = None
195
+ if tags_list:
196
+ tags_result = client.add_tags_to_post(draft.get("id"), tags_list)
197
+
198
+ prepublish_result = None
199
+ if prepublish:
200
+ prepublish_result = client.prepublish_draft(draft.get("id"))
201
+
202
+ publish_result = None
203
+ if publish:
204
+ publish_result = client.publish_draft(
205
+ draft.get("id"), send=send, share_automatically=share_automatically
206
+ )
207
+
208
+ return {
209
+ "draft": draft,
210
+ "tags": tags_result,
211
+ "prepublish": prepublish_result,
212
+ "publish": publish_result,
213
+ }
214
+
215
+
216
+ @mcp.tool()
217
+ async def put_draft(
218
+ draft_id: int,
219
+ update_payload: Dict[str, Any],
220
+ ) -> Dict[str, Any]:
221
+ """Update an existing draft by draft ID.
222
+
223
+ Args:
224
+ draft_id: target draft identifier.
225
+ update_payload: dict of fields supported by Substack `put_draft` (e.g. `slug`, `draft_section_id`).
226
+
227
+ Returns:
228
+ API response dict for the updated draft.
229
+ """
230
+ client = get_api()
231
+ return client.put_draft(draft_id, **update_payload)
232
+
233
+
234
+ @mcp.tool()
235
+ async def add_tags(draft_id: int, tags: Any) -> Dict[str, Any]:
236
+ """Add tags to a specific draft/post.
237
+
238
+ Args:
239
+ draft_id: target draft identifier.
240
+ tags: string or list of tag names (e.g. `"tech"` or `["tech", "python"]`).
241
+
242
+ Returns:
243
+ Response from `add_tags_to_post` (tag IDs + names).
244
+ """
245
+ client = get_api()
246
+ tags_list = _normalize_tags(tags)
247
+ if not tags_list:
248
+ raise ValueError("tags is required and cannot be empty")
249
+ return client.add_tags_to_post(draft_id, tags_list)
250
+
251
+
252
+ @mcp.tool()
253
+ async def prepublish_draft(draft_id: int) -> Dict[str, Any]:
254
+ """Invoke prepublish checks for a draft.
255
+
256
+ Args:
257
+ draft_id: target draft identifier.
258
+
259
+ Returns:
260
+ Prepublish response dict from Substack API.
261
+ """
262
+ client = get_api()
263
+ return client.prepublish_draft(draft_id)
264
+
265
+
266
+ @mcp.tool()
267
+ async def publish_draft(
268
+ draft_id: int,
269
+ send: bool = True,
270
+ share_automatically: bool = False,
271
+ ) -> Dict[str, Any]:
272
+ """Publish a draft to live post state.
273
+
274
+ Args:
275
+ draft_id: target draft identifier.
276
+ send: if False then do not send email to subscribers.
277
+ share_automatically: whether to auto-share (e.g. social propagation).
278
+
279
+ Returns:
280
+ Response from Substack `publish_draft`.
281
+ """
282
+ client = get_api()
283
+ return client.publish_draft(
284
+ draft_id, send=send, share_automatically=share_automatically
285
+ )
286
+
287
+
288
+ def main() -> None:
289
+ mcp.run(transport="stdio")
290
+
291
+
292
+ if __name__ == "__main__":
293
+ main()