Files
by-agent-for-agent/skills/save-post/scripts/save_post.py
T

155 lines
4.8 KiB
Python

#!/usr/bin/env python3
"""
Save a post to the links application via REST API.
Usage:
python3 save_post.py --title "Post Title" --content "Post content" --summary "Brief summary" --tags "tag1,tag2"
OR
python3 save_post.py -t "Post Title" -c "Post content" -s "Brief summary" --tags "tag1,tag2"
OR (from stdin)
echo '{"title": "Title", "content": "Content"}' | python3 save_post.py
"""
import argparse
import json
import sys
import os
from typing import Optional, Dict, Any, List
import urllib.request
import urllib.parse
import urllib.error
# Default API endpoint
DEFAULT_API_URL = "http://links.apps.svc.cluster.local/api/posts"
def save_post(
title: str,
content: str,
summary: Optional[str] = None,
tags: Optional[List[str]] = None,
api_url: str = DEFAULT_API_URL
) -> Dict[str, Any]:
"""
Save a post to the links application via REST API.
Args:
title: Post title (required)
content: Post content (required)
summary: Post summary (optional)
tags: List of tag slugs (optional)
api_url: API endpoint URL
Returns:
Response JSON from API
"""
# Prepare data
data = {
"title": title,
"content": content,
"summary": summary or "",
"tags": tags or []
}
# Create request
headers = {
"Content-Type": "application/json",
"User-Agent": "save-post-skill/1.0"
}
req = urllib.request.Request(
api_url,
data=json.dumps(data).encode('utf-8'),
headers=headers,
method="POST"
)
try:
with urllib.request.urlopen(req) as response:
response_data = json.loads(response.read().decode('utf-8'))
return {
"success": True,
"status": response.status,
"data": response_data
}
except urllib.error.HTTPError as e:
error_body = e.read().decode('utf-8') if e.readable() else str(e)
try:
error_data = json.loads(error_body)
except:
error_data = {"error": error_body}
return {
"success": False,
"status": e.code,
"error": error_data
}
except Exception as e:
return {
"success": False,
"status": 0,
"error": {"error": str(e)}
}
def main():
parser = argparse.ArgumentParser(description="Save a post to the links application")
parser.add_argument("--title", "-t", help="Post title (required)", required=False)
parser.add_argument("--content", "-c", help="Post content (required)", required=False)
parser.add_argument("--summary", "-s", help="Post summary (optional)", default="")
parser.add_argument("--tags", help="Comma-separated list of tags (optional)")
parser.add_argument("--api-url", help=f"API URL (default: {DEFAULT_API_URL})", default=DEFAULT_API_URL)
parser.add_argument("--json", help="Read JSON from stdin", action="store_true")
args = parser.parse_args()
# Check if reading from stdin
if args.json or (not args.title and not args.content and not sys.stdin.isatty()):
try:
stdin_data = json.load(sys.stdin)
# Validate required fields
if "title" not in stdin_data:
print("Error: 'title' is required in JSON input", file=sys.stderr)
sys.exit(1)
if "content" not in stdin_data:
print("Error: 'content' is required in JSON input", file=sys.stderr)
sys.exit(1)
title = stdin_data["title"]
content = stdin_data["content"]
summary = stdin_data.get("summary", "")
tags = stdin_data.get("tags", [])
if isinstance(tags, str):
tags = [tag.strip() for tag in tags.split(",") if tag.strip()]
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
else:
# Check required arguments
if not args.title:
parser.error("--title is required unless using --json")
if not args.content:
parser.error("--content is required unless using --json")
title = args.title
content = args.content
summary = args.summary
tags = [tag.strip() for tag in args.tags.split(",")] if args.tags else []
# Call API
result = save_post(
title=title,
content=content,
summary=summary if summary else None,
tags=tags if tags else None,
api_url=args.api_url
)
# Output result
if result["success"]:
print(json.dumps(result["data"], indent=2))
else:
print(json.dumps(result, indent=2), file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()