Werkzeuge: Python-Client für Feed, Benachrichtigungen und Beiträge
Zum schnellen Lesen und Schreiben von der Kommandozeile aus, etwa für Tests gegen DEV oder kleine Automatisierungen. Nur Standardbibliothek, damit nichts installiert werden muss. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
"""Kleiner Kommandozeilen-Client für die kver-API (nur Standardbibliothek).
|
||||
|
||||
export KVER_URL=http://127.0.0.1:8081 # Default
|
||||
export KVER_USER=handle KVER_PASS=...
|
||||
|
||||
python3 tools/kver-client.py feed [SEITE]
|
||||
python3 tools/kver-client.py notifications # markiert sie als gesehen
|
||||
python3 tools/kver-client.py unread
|
||||
python3 tools/kver-client.py post 'Text'
|
||||
python3 tools/kver-client.py reply PID 'Text'
|
||||
|
||||
Text "-" liest von stdin. Jeder Aufruf meldet sich neu an (Session 5 min).
|
||||
"""
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
BASE = os.environ.get("KVER_URL", "http://127.0.0.1:8081").rstrip("/")
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
jar = http.cookiejar.CookieJar()
|
||||
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
|
||||
def call(self, method, path, form=None):
|
||||
data = urllib.parse.urlencode(form).encode() if form is not None else None
|
||||
req = urllib.request.Request(BASE + "/api" + path, data=data, method=method)
|
||||
try:
|
||||
with self.opener.open(req) as resp:
|
||||
return json.load(resp)
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
err = json.load(e)["error"]
|
||||
msg = f"{err['code']}: {err['message']}"
|
||||
except (ValueError, KeyError):
|
||||
msg = e.reason
|
||||
sys.exit(f"{method} {path}: {e.code} {msg}")
|
||||
|
||||
def login(self):
|
||||
user, pw = os.environ.get("KVER_USER"), os.environ.get("KVER_PASS")
|
||||
if not user or not pw:
|
||||
sys.exit("KVER_USER und KVER_PASS setzen")
|
||||
self.call("POST", "/auth/login", {"user": user, "pass": pw, "timeout": 300})
|
||||
|
||||
|
||||
def when(ts):
|
||||
return datetime.fromtimestamp(ts).strftime("%d.%m.%Y %H:%M")
|
||||
|
||||
|
||||
def show_entry(e, indent=""):
|
||||
name = e.get("display_name") or e["handle"]
|
||||
print(f"{indent}[{e['pid']}] {name} (@{e['handle']}) · {when(e['created_at'])}"
|
||||
f" · {e['reply_count']} Antworten")
|
||||
for line in e["content"].splitlines() or [""]:
|
||||
print(f"{indent} {line}")
|
||||
|
||||
|
||||
def text_arg(s):
|
||||
return sys.stdin.read() if s == "-" else s
|
||||
|
||||
|
||||
def main(args):
|
||||
if not args:
|
||||
sys.exit(__doc__)
|
||||
c, cmd = Client(), args[0]
|
||||
if cmd == "feed":
|
||||
page = int(args[1]) if len(args) > 1 else 0
|
||||
for e in c.call("GET", f"/entry/feed/{page}"):
|
||||
show_entry(e)
|
||||
if latest := e.get("latest"):
|
||||
show_entry(latest["entry"], indent=" ↳ ")
|
||||
print()
|
||||
elif cmd == "notifications":
|
||||
c.login()
|
||||
for n in c.call("GET", "/notifications")["notifications"]:
|
||||
new = "" if n["seen"] else " · neu"
|
||||
print(f"{when(n['created_at'])}{new} {n['message']}")
|
||||
print(f" {n['excerpt']} ({BASE}{n['link']})")
|
||||
elif cmd == "unread":
|
||||
c.login()
|
||||
print(c.call("GET", "/notifications/unread")["unread"])
|
||||
elif cmd == "post" and len(args) == 2:
|
||||
c.login()
|
||||
print(c.call("POST", "/entry/create", {"content": text_arg(args[1])})["pid"])
|
||||
elif cmd == "reply" and len(args) == 3:
|
||||
c.login()
|
||||
r = c.call("POST", "/entry/create", {"content": text_arg(args[2]), "reply_to": args[1]})
|
||||
print(r["pid"])
|
||||
else:
|
||||
sys.exit(__doc__)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv[1:])
|
||||
Reference in New Issue
Block a user