""" Parameters: see `python replish_to_postiz.py --help`. Environment: REPLISH_URL, REPLISH_KEY, POSTIZ_KEY, and POSTIZ_URL for a self-hosted Postiz (default https://api.postiz.com/public/v1). What it does: finds a clip on Replish, renders it as a vertical short with your text, uploads the MP4 to Postiz and creates a post (draft, scheduled at the channel's next free slot, or published now) on every Postiz channel you pass. Clips already posted are remembered in a small JSON file and never posted twice. Output: one line per posted clip; exit code 0 when every requested short was posted, 1 otherwise. """ from __future__ import annotations import argparse import json import os import sys import time from datetime import UTC, datetime from pathlib import Path import httpx REPLISH_URL = os.environ.get("REPLISH_URL", "").rstrip("/") POSTIZ_URL = os.environ.get("POSTIZ_URL", "https://api.postiz.com/public/v1").rstrip("/") def replish() -> httpx.Client: return httpx.Client( base_url=REPLISH_URL, timeout=60, headers={"Authorization": f"Bearer {os.environ['REPLISH_KEY']}"} ) def postiz() -> httpx.Client: return httpx.Client(base_url=POSTIZ_URL, timeout=300, headers={"Authorization": os.environ["POSTIZ_KEY"]}) def call(client: httpx.Client, method: str, url: str, **kw) -> httpx.Response: for _ in range(5): r = client.request(method, url, **kw) if r.status_code != 429: r.raise_for_status() return r wait = int(r.headers.get("Retry-After", "30")) print(f" {client.base_url.host}: rate limited, waiting {wait} s", file=sys.stderr) time.sleep(min(wait, 900)) r.raise_for_status() return r def candidates(rp: httpx.Client, args) -> list[dict]: if args.streamer: clips = call( rp, "GET", f"/v1/streamers/{args.streamer}/clips", params={"period": args.period} ).json()["clips"] elif args.game: clips = call(rp, "GET", f"/v1/games/{args.game}/clips", params={"period": args.period}).json()[ "clips" ] else: params = { "window": args.window, "cat": args.cat, "lang": args.lang, "platform": args.platform, "limit": 50, } clips = call(rp, "GET", "/v1/clips", params=params).json()["clips"] return [c for c in clips if (c.get("duration") or 0) >= args.min_seconds] def render(rp: httpx.Client, clip: dict, args, out: Path) -> Path: body = { "clip": clip["url"], "hook": args.hook or clip["title"][:120], "captions": True, "footer": args.footer or None, "watermark": args.watermark or None, } if args.duration: body["duration"] = args.duration job = call(rp, "POST", "/v1/renders", json=body).json() deadline = time.monotonic() + 600 while job["status"] not in ("done", "error"): if time.monotonic() > deadline: raise TimeoutError(f"render {job['id']} still running after 10 minutes") time.sleep(5) job = call(rp, "GET", f"/v1/renders/{job['id']}").json() if job["status"] == "error": raise RuntimeError(f"render failed: {job['error']}") path = out / f"{job['id']}.mp4" with rp.stream("GET", job["file_url"]) as r: r.raise_for_status() with path.open("wb") as f: for chunk in r.iter_bytes(): f.write(chunk) return path def settings_for(channel: dict, title: str, tiktok_method: str = "DIRECT_POST") -> dict: kind = channel["identifier"] if kind == "tiktok": return { "__type": "tiktok", "title": title[:90], "privacy_level": "PUBLIC_TO_EVERYONE", "duet": True, "stitch": True, "comment": True, "autoAddMusic": "no", "brand_content_toggle": False, "brand_organic_toggle": False, "content_posting_method": tiktok_method, } if kind == "youtube": return { "__type": "youtube", "title": title[:100], "type": "public", "selfDeclaredMadeForKids": "no", "tags": [], } if kind in ("instagram", "instagram-standalone"): return {"__type": kind, "post_type": "post"} if kind == "x": return {"__type": "x", "who_can_reply_post": "everyone"} return {"__type": kind} def publish(pz: httpx.Client, video: Path, channels: list[dict], clip: dict, args) -> None: with video.open("rb") as f: media = call(pz, "POST", "/upload", files={"file": (video.name, f, "video/mp4")}).json() broadcaster = clip["broadcaster_name"] or clip["broadcaster"] for ch in channels: # TikTok suppresses posts with external links in the caption; credit the streamer by name there. credit = ( f"Clip: {broadcaster}" if ch["identifier"] == "tiktok" else f"Clip: {broadcaster} ({clip['url']})" ) text = "\n\n".join(t for t in (args.caption or clip["title"], credit, args.tags) if t) when = datetime.now(UTC).isoformat() if args.mode == "schedule": when = call(pz, "GET", f"/find-slot/{ch['id']}").json()["date"] post = { "type": args.mode, "date": when, "shortLink": False, "tags": [], "posts": [ { "integration": {"id": ch["id"]}, "value": [{"content": text, "image": [{"id": media["id"], "path": media["path"]}]}], "settings": settings_for(ch, args.hook or clip["title"], args.tiktok_method), } ], } call(pz, "POST", "/posts", json=post) print(f" {args.mode} on {ch['identifier']} ({ch.get('profile') or ch['name']}) for {when}") def main() -> int: p = argparse.ArgumentParser(description="Replish clip -> vertical short -> Postiz post.") p.add_argument( "--channels", default="", help="Postiz integration ids, comma separated (see --list-channels)" ) p.add_argument( "--list-channels", action="store_true", help="print your connected Postiz channels and stop" ) p.add_argument("--count", type=int, default=1, help="shorts to post this run") p.add_argument("--mode", choices=("draft", "schedule", "now"), default="draft") p.add_argument( "--tiktok-method", choices=("DIRECT_POST", "UPLOAD"), default="DIRECT_POST", help="DIRECT_POST publishes directly; UPLOAD sends to the TikTok app inbox", ) p.add_argument("--cat", default="", help="Replish category slug, from /v1/categories") p.add_argument("--lang", default="", help="broadcaster language, such as en or fr") p.add_argument("--platform", default="", help="twitch or kick") p.add_argument( "--window", type=int, default=180, help="rising clips of the last 30, 60, 180, 360, 720 or 1440 minutes", ) p.add_argument("--streamer", help="use this streamer's top clips instead of the rising feed") p.add_argument("--game", help="use this game's top clips instead of the rising feed") p.add_argument("--period", default="day", help="day, week or month (with --streamer or --game)") p.add_argument("--min-seconds", type=float, default=0, help="skip clips shorter than this") p.add_argument("--duration", type=float, help="seconds of output, 5 to 90") p.add_argument("--hook", help="text at the top of the video (default: the clip title)") p.add_argument("--footer", help="bottom line, such as 'Follow for daily clips'") p.add_argument("--watermark", help="your handle, such as @myclips") p.add_argument("--caption", help="post text (default: the clip title)") p.add_argument("--tags", default="", help="hashtags appended to the post text") p.add_argument("--state", default="replish_posted.json", help="file of clips already posted") p.add_argument("--out", default="shorts", help="folder for the MP4 files") args = p.parse_args() state_path, out = Path(args.state), Path(args.out) out.mkdir(exist_ok=True) posted = set(json.loads(state_path.read_text())) if state_path.exists() else set() with replish() as rp, postiz() as pz: connected = call(pz, "GET", "/integrations").json() if args.list_channels: for c in connected: print( f"{c['id']} {c['identifier']:<20} {c.get('profile') or c['name']}{' (disabled)' if c['disabled'] else ''}" ) return 0 wanted = set(args.channels.split(",")) channels = [c for c in connected if c["id"] in wanted and not c["disabled"]] if not channels: print("None of --channels is a connected, enabled Postiz channel.", file=sys.stderr) return 1 done = 0 for clip in candidates(rp, args): if done >= args.count: break if clip["id"] in posted: continue print(f"{clip['id']}: {clip['title']!r} by {clip['broadcaster']}") try: video = render(rp, clip, args, out) publish(pz, video, channels, clip, args) except (httpx.HTTPError, RuntimeError, TimeoutError) as e: print(f" skipped: {e}", file=sys.stderr) continue posted.add(clip["id"]) state_path.write_text(json.dumps(sorted(posted))) done += 1 print(f"Posted {done} of {args.count}.") return 0 if done == args.count else 1 if __name__ == "__main__": raise SystemExit(main())