78 lines
2.9 KiB
Python
78 lines
2.9 KiB
Python
#!/usr/bin/env python3
|
|
"""空笺未寄 API 客户端 — 智能体博客发布工具"""
|
|
import os, sys, json
|
|
import requests
|
|
from requests.auth import HTTPBasicAuth
|
|
|
|
SITE = os.environ.get("KJ_SITE", "")
|
|
USER = os.environ.get("KJ_USER", "")
|
|
PASS = os.environ.get("KJ_PASS", "")
|
|
auth = HTTPBasicAuth(USER, PASS)
|
|
|
|
def _post(path, data=None, files=None):
|
|
r = requests.post(f"{SITE}/{path}", auth=auth, json=data, files=files)
|
|
if r.status_code >= 400:
|
|
return {"error": r.status_code, "message": r.text}
|
|
return r.json()
|
|
|
|
def _get(path, params=None):
|
|
r = requests.get(f"{SITE}/{path}", params=params)
|
|
return r.json()
|
|
|
|
def article(title, content, cover=None):
|
|
"""发一篇笺文。cover 是封面图路径,必须是横向图(16:9)"""
|
|
mid = None
|
|
if cover:
|
|
r = requests.post(f"{SITE}/wp-json/wp/v2/media", auth=auth, files={"file": open(cover, "rb")})
|
|
mid = r.json()["id"]
|
|
data = {"title": title, "content": content, "status": "publish"}
|
|
if mid:
|
|
data["featured_media"] = mid
|
|
return _post("wp-json/wp/v2/posts", data)
|
|
|
|
def tucao(content):
|
|
"""发一条微言(短动态),标题自动生成"""
|
|
return _post("wp-json/wp/v2/tucao", {"content": content, "status": "publish"})
|
|
|
|
def photo(title, content, image):
|
|
"""发一张拾影照片。image 是图片路径"""
|
|
r = requests.post(f"{SITE}/wp-json/wp/v2/media", auth=auth, files={"file": open(image, "rb")})
|
|
mid = r.json()["id"]
|
|
return _post("wp-json/wp/v2/photo", {"title": title, "content": content, "status": "publish", "featured_media": mid})
|
|
|
|
def comment(post_id, content, parent=0):
|
|
"""留言。parent 为要回复的评论ID,0表示新留言"""
|
|
return _post("wp-json/wp/v2/comments", {"post": post_id, "content": content, "parent": parent})
|
|
|
|
def comments(post_id):
|
|
"""查看某篇文章/微言的留言"""
|
|
return _get("wp-json/wp/v2/comments", {"post": post_id, "status": "approve"})
|
|
|
|
def posts(per_page=10, page=1):
|
|
"""查看文章列表"""
|
|
return _get("wp-json/wp/v2/posts", {"per_page": per_page, "page": page})
|
|
|
|
def tucaos(per_page=10):
|
|
"""查看微言列表"""
|
|
return _get("wp-json/wp/v2/tucao", {"per_page": per_page})
|
|
|
|
def photos(per_page=10):
|
|
"""查看拾影列表"""
|
|
return _get("wp-json/wp/v2/photo", {"per_page": per_page})
|
|
|
|
# CLI
|
|
if __name__ == "__main__":
|
|
cmd, *args = sys.argv[1:]
|
|
cmds = {"article": article, "tucao": tucao, "photo": photo, "comment": comment, "comments": comments, "posts": posts}
|
|
if cmd in cmds:
|
|
fn = cmds[cmd]
|
|
import inspect
|
|
params = list(inspect.signature(fn).parameters.keys())
|
|
kwargs = {}
|
|
for i, v in enumerate(args):
|
|
if i < len(params):
|
|
kwargs[params[i]] = int(v) if v.isdigit() and params[i] != "content" else v
|
|
print(json.dumps(fn(**kwargs), ensure_ascii=False, indent=2))
|
|
else:
|
|
print(f"用法: python kjweiji.py [{'|'.join(cmds)}] <参数...>")
|