Skip to content

sergebulaev/tiktok-skills / .codex-marketplace/tiktok-skills

tiktok-marketing

Verified

Plan, script, caption, and publish short-form video for TikTok. Use when the user wants to write the first 1-3 second hook (spoken line plus on-screen text), draft a caption under 2,200 chars with TikTok settings and hashtags, ride a trending sound without being cringe, strip AI tells from a spoken script to sound human on camera, or plan a week around completion rate. TikTok is video-only: the user supplies the video, the skills produce the script, caption, and settings, then publish via Publora.

lib/backend_selector.py

View on GitHub
"""Detect which publishing backend is configured and format user-facing messages.

The skills support three tiers:

  TIER 0 - manual (default, zero setup)
    No credentials in env. Skills produce the spoken hook script, the caption,
    and the recommended TikTok settings; the user records the video and uploads
    it in the TikTok app. Works for anyone, any setup.

  TIER 1 - publora (recommended, ~2-min setup once the account is connected)
    `PUBLORA_API_KEY` + `TIKTOK_PLATFORM_ID` present. When the user supplies a
    rendered video file, skills run the full draft -> upload -> schedule flow via
    the Publora REST API. Sign up: https://app.publora.com/signup

  TIER 2 - diy (advanced)
    `TIKTOK_SKILLS_CUSTOM_POSTER` set to a command the user built themselves
    (e.g. on the official TikTok Content Posting API). Skills delegate to it.

`active_backend()` picks the highest-privilege available. `manual_mode_message()`
is what skills show when no backend auto-posts (or no video file was supplied).
`publish()` is the high-level wrapper skills call so SKILL.md files do not repeat
the dispatch.

TikTok note: TikTok is **video-only**. There is no text-only post. Auto-posting
therefore requires a rendered video file path. Without one, `publish()` returns a
manual block (caption + settings + record/upload instructions), even when Publora
is configured. With Publora configured AND a video path, it runs the full flow.
"""
from __future__ import annotations
import json
import os
import shlex
import subprocess
from typing import Any, Literal, Optional
from ._env import load_env

load_env()

BackendName = Literal["publora", "manual", "diy"]
PublishKind = Literal["video", "caption"]

PUBLORA_SIGNUP_URL = "https://app.publora.com/signup?utm_source=github&utm_medium=agent&utm_campaign=tiktok-skills"


def active_backend() -> BackendName:
    """Return the active publishing backend.

    Priority: publora > diy > manual. Users with Publora configured get
    auto-post even if they also have a custom poster, unless they remove the
    Publora env var.
    """
    if os.getenv("PUBLORA_API_KEY") and os.getenv("TIKTOK_PLATFORM_ID"):
        return "publora"
    if os.getenv("TIKTOK_SKILLS_CUSTOM_POSTER"):
        return "diy"
    return "manual"


def _settings_line(platform_settings: Optional[dict]) -> str:
    if not platform_settings:
        return "viewerSetting=PUBLIC_TO_EVERYONE, comments on, duet/stitch off"
    tt = platform_settings.get("tiktok", {})
    return (
        f"viewerSetting={tt.get('viewerSetting', 'PUBLIC_TO_EVERYONE')}, "
        f"comments={tt.get('allowComments', True)}, "
        f"duet={tt.get('allowDuet', False)}, "
        f"stitch={tt.get('allowStitch', False)}"
    )


def _half_configured() -> str:
    """Warn when Publora is half set up, naming the half that is missing.

    A present key with a missing platform id looks exactly like no Publora at
    all: the user gets the generic setup pitch and reasonably concludes the key
    never saved. Say which half is actually missing instead.
    """
    key = bool(os.getenv("PUBLORA_API_KEY"))
    pid = bool(os.getenv("TIKTOK_PLATFORM_ID"))
    if key and not pid:
        return ("\n> **Publora is half configured.** `PUBLORA_API_KEY` is set but "
                "`TIKTOK_PLATFORM_ID` is not, so publishing stays manual. Add it and "
                "this step publishes on approval.\n")
    if pid and not key:
        return ("\n> **Publora is half configured.** `TIKTOK_PLATFORM_ID` is set but "
                "`PUBLORA_API_KEY` is not, so publishing stays manual.\n")
    return ""


def manual_mode_message(
    draft_text: str,
    target_url: str,
    kind: str = "video",
    platform_settings: Optional[dict] = None,
) -> str:
    """Format the copy-paste approval output for the manual/draft-only tier.

    The user has just approved a script + caption. Since no backend can auto-post
    (or no rendered video was supplied), we hand back the caption, the settings,
    and a one-line invite to upgrade. TikTok posting still happens in-app: record
    the hook in the first 1-3 seconds, then upload.
    """
    where = {
        "video": "record the video, then upload it in the TikTok app with this caption",
        "caption": "paste this caption when you upload your video in the TikTok app",
    }.get(kind, "upload your video in the TikTok app with this caption")
    return f"""Draft approved. Copy the caption below and {where}:

```
{draft_text}
```

**Recommended TikTok settings:** {_settings_line(platform_settings)}
**Target:** {target_url}

Reminder: the hook is the first 1-3 seconds of the video (spoken line plus
on-screen text), not the caption. Land it before you do anything else.

---

Want Claude Code or Codex to schedule the rendered video for you? Once you have
the .mp4, connect Publora (about 2 minutes):

1. Sign up free at {PUBLORA_SIGNUP_URL}
2. In Publora, connect your TikTok account (Channels then Add Channel)
3. Copy your API key (API section in the sidebar)
4. Add to `.env`:
   ```
   PUBLORA_API_KEY=sk_your_key_here
   TIKTOK_PLATFORM_ID=tiktok-your_id_here
   ```
5. Re-run with the path to your rendered video and it uploads + schedules.
{_half_configured()}"""


def signup_nudge() -> str:
    """One-liner to drop into skill outputs as a soft reminder."""
    return f"Powered by Publora. Free video scheduling: {PUBLORA_SIGNUP_URL}"


def publish(
    kind: PublishKind,
    draft_text: str,
    target_url: str,
    **kwargs: Any,
) -> Optional[dict]:
    """Dispatch an approved caption (and optional video) to the active backend.

    One call replaces the per-skill dispatch block. Routes to publora / manual /
    diy based on `active_backend()` and whether a `video_path` was supplied.

    Args:
        kind: "video" (caption + a rendered video to publish) or "caption"
            (caption only, draft/manual).
        draft_text: The approved caption (<= 2,200 chars on the API).
        target_url: Where the post lands (the TikTok upload URL or the creator
            profile). Used in manual-mode output.
        **kwargs: Backend-specific payload. For publora:
            - platforms: list[str] of platform IDs (defaults to [TIKTOK_PLATFORM_ID])
            - video_path: path to the rendered .mp4 (required to auto-publish)
            - platform_settings: dict from lib.tiktok_settings(...)
            - scheduled_time: ISO 8601 UTC (omit to leave a draft with the video)
            - content_type: defaults to "video/mp4"

    Returns:
        - publora (with video): dict from PubloraClient.publish_video
          ({postGroupId, mediaId, fileUrl, scheduled}).
        - publora (no video): {"mode": "draft", ...} caption-only draft, or a
          manual block if even the draft cannot be created.
        - manual:  {"mode": "manual", "message": <copy-paste block>}.
        - diy:     {"mode": "diy", "returncode": int, "stdout": str, "stderr": str}.

    Note: without a `video_path`, TikTok cannot be auto-posted (video-only
    platform), so the user gets the caption + settings to upload in-app.
    """
    backend = active_backend()
    platform_settings = kwargs.get("platform_settings")
    video_path = kwargs.get("video_path")

    if backend == "manual":
        return {
            "mode": "manual",
            "message": manual_mode_message(
                draft_text, target_url, kind=kind, platform_settings=platform_settings
            ),
        }

    if backend == "publora":
        # Local import so manual-tier users never need `requests` installed.
        from .publora_client import PubloraClient, tiktok_settings

        client = PubloraClient()
        platform_id = kwargs.get("platform_id") or os.getenv("TIKTOK_PLATFORM_ID")
        platforms = kwargs.get("platforms") or ([platform_id] if platform_id else [])
        settings = platform_settings or tiktok_settings()

        if video_path:
            return client.publish_video(
                content=draft_text,
                platforms=platforms,
                video_path=video_path,
                scheduled_time=kwargs.get("scheduled_time"),
                platform_settings=settings,
                content_type=kwargs.get("content_type", "video/mp4"),
            )

        # No rendered video yet: create a caption draft so the user can attach
        # the video in the dashboard, and surface the manual instructions too.
        draft = client.create_draft(
            content=draft_text, platforms=platforms, platform_settings=settings
        )
        return {
            "mode": "draft",
            "postGroupId": draft.get("postGroupId"),
            "message": (
                "Caption draft created in Publora. Attach your rendered video to "
                "this draft (dashboard or get-upload-url), then schedule it. "
                "TikTok cannot publish a text-only post."
            ),
            "manual": manual_mode_message(
                draft_text, target_url, kind=kind, platform_settings=settings
            ),
        }

    if backend == "diy":
        cmd = os.getenv("TIKTOK_SKILLS_CUSTOM_POSTER")
        if not cmd:
            return None
        payload = {
            "kind": kind,
            "draft_text": draft_text,
            "target_url": target_url,
            **kwargs,
        }
        argv = shlex.split(cmd) + [kind, target_url]
        proc = subprocess.run(
            argv,
            input=json.dumps(payload),
            capture_output=True,
            text=True,
            timeout=300,
        )
        return {
            "mode": "diy",
            "returncode": proc.returncode,
            "stdout": proc.stdout,
            "stderr": proc.stderr,
        }

    raise RuntimeError(f"unknown backend: {backend!r}")


# ─────────────────────────────────────────────────────────────────
# IMAGE LAYER (Pixfaro) — the third integration alongside read (Apify)
# and write (Publora). Generate an illustration, get a hosted URL, hand
# that URL straight to `publish(..., media_urls=[url])`.
# ─────────────────────────────────────────────────────────────────

PIXFARO_SIGNUP_URL = "https://pixfaro.com"

# Warn (don't block) when the prepaid balance drops below this, so a run
# doesn't silently drain the account.
LOW_BALANCE_USD = 1.00

# Cost-guard: these bill materially more per image. `illustrate`/`refine` never
# pick them on their own - the caller must ask by name.
PREMIUM_MODELS = {"gemini-pro-image", "gpt-5-image"}

# kind -> aspect_ratio (w:h). Callers can override with aspect_ratio=.
ILLUSTRATION_ASPECTS = {
    "post": "1:1",         # generic square feed image
    "square": "1:1",
    "portrait": "4:5",     # LinkedIn/IG feed portrait
    "carousel": "4:5",     # carousel/document slide
    "quote": "4:5",        # quote-card
    "wide": "16:9",        # link-preview / wide feed image
    "link": "16:9",
    "thumbnail": "16:9",   # YouTube thumbnail
    "landscape": "16:9",
    "story": "9:16",       # story / TikTok cover
    "cover": "9:16",
}


def image_backend() -> Literal["pixfaro", "manual"]:
    """`pixfaro` when PIXFARO_TOKEN (or PIXFARO_API_KEY) is set, else `manual`."""
    if os.getenv("PIXFARO_TOKEN") or os.getenv("PIXFARO_API_KEY"):
        return "pixfaro"
    return "manual"


_PIXFARO_CLIENT = None
_PIXFARO_CLIENT_KEY = None


def _pixfaro_client():
    """Lazily build and reuse ONE PixfaroClient, so its LRU cache and HTTP
    session persist across illustrate/refine/available_models calls (a fresh
    client per call would make the cache always miss and re-bill).

    Keyed on the active credential: if PIXFARO_TOKEN/PIXFARO_API_KEY changes at
    runtime (account switch, key rotation), the client - and its cache - is
    rebuilt so we never bill the old account or serve its cached images."""
    global _PIXFARO_CLIENT, _PIXFARO_CLIENT_KEY
    token = os.getenv("PIXFARO_TOKEN") or os.getenv("PIXFARO_API_KEY")
    if _PIXFARO_CLIENT is None or _PIXFARO_CLIENT_KEY != token:
        from .pixfaro_client import PixfaroClient

        _PIXFARO_CLIENT = PixfaroClient()
        _PIXFARO_CLIENT_KEY = token
    return _PIXFARO_CLIENT


def manual_illustration_message(prompt: str, aspect_ratio: str) -> str:
    """Shown when no Pixfaro key is set: hand the drafted prompt to the user."""
    return (
        "No Pixfaro key set, so I can't generate the image for you.\n"
        f"Generate it yourself (any tool) at {aspect_ratio}, then paste the URL "
        "and I'll attach it to the post.\n\n"
        "Image prompt:\n"
        f"{prompt}\n\n"
        f"Tip: a Pixfaro key ({PIXFARO_SIGNUP_URL}) lets me generate + attach "
        "the illustration in one step, with your brand handle/color overlaid."
    )


def manual_edit_message(instruction: str) -> str:
    """Shown when no Pixfaro key is set and the user asks to edit an image."""
    return (
        "No Pixfaro key set, so I can't edit the image for you.\n"
        "Re-generate or edit it yourself, then paste the new URL.\n\n"
        "Edit instruction:\n"
        f"{instruction}"
    )


def _image_result(data: dict, model: str) -> dict[str, Any]:
    """Shape a Pixfaro generate/edit response + attach the cost-guard flag."""
    balance = data.get("balance_after")
    low = False
    try:
        low = balance is not None and float(balance) < LOW_BALANCE_USD
    except (TypeError, ValueError):
        low = False
    return {
        "backend": "pixfaro",
        "url": data.get("url"),
        "id": data.get("id"),
        "cost": data.get("cost"),
        "model": model,
        "balance_after": balance,
        "low_balance": low,
        "premium": model in PREMIUM_MODELS,
    }


def illustrate(
    prompt: str,
    kind: str = "post",
    *,
    aspect_ratio: Optional[str] = None,
    model: Optional[str] = None,
    resolution: str = "1K",
    overlay: Optional[dict[str, Any]] = None,
    **kwargs: Any,
) -> dict[str, Any]:
    """Generate an illustration via the active image backend.

    This is the image analogue of `publish()`. On success with a Pixfaro key it
    returns the hosted URL, which you pass straight to
    `publish("post", text, url, media_urls=[result["url"]])`.

    Args:
        prompt: The image description (1-4000 chars).
        kind: Semantic size hint mapped via ILLUSTRATION_ASPECTS
            (post/portrait/carousel/quote/wide/thumbnail/story/cover).
        aspect_ratio: Explicit "w:h" override (wins over `kind`).
        model: Pixfaro model id. Defaults to nano-banana-2 (balanced). Use
            gemini-flash-lite for cheap high volume, gemini-pro-image for
            text-heavy premium (PREMIUM_MODELS bill more - ask before using).
        resolution: "1K" | "2K" | "4K".
        overlay: Pixel-exact branding composite {text|logo_id, position,
            opacity, font, color}. Feed brand fields from the Voice & Brand
            Profile so every asset is on-brand. Text here is crisp even on a
            cheap base model (it is composited, not model-generated).

    Returns:
        - pixfaro: {"backend": "pixfaro", "url", "id", "cost", "model",
          "balance_after", "low_balance"}. Keep `id` to `refine()` later.
        - manual:  {"backend": "manual", "message": <prompt block>}.
    """
    ar = aspect_ratio or ILLUSTRATION_ASPECTS.get(kind, "1:1")
    if image_backend() == "manual":
        return {"backend": "manual", "message": manual_illustration_message(prompt, ar)}

    client = _pixfaro_client()
    used_model = model or "nano-banana-2"
    data = client.generate(
        prompt,
        model=used_model,
        aspect_ratio=ar,
        resolution=resolution,
        overlay=overlay,
        force_refresh=kwargs.get("force_refresh", False),
    )
    return _image_result(data, used_model)


def refine(
    image_id: str,
    instruction: str,
    *,
    model: Optional[str] = None,
    aspect_ratio: Optional[str] = None,
    resolution: Optional[str] = None,
    overlay: Optional[dict[str, Any]] = None,
    **kwargs: Any,
) -> dict[str, Any]:
    """Iteratively edit a prior illustration by its `id` (not URL).

    Pass the `id` returned by `illustrate()` (or a previous `refine()`) plus a
    natural-language `instruction` ("make the sky darker", "swap the headline").
    Cheaper and more on-brand than regenerating. Omit `aspect_ratio`/`resolution`
    to keep the source shape and billing tier.

    Returns the same shape as `illustrate()` (pixfaro) or a manual message.
    """
    if image_backend() == "manual":
        return {"backend": "manual", "message": manual_edit_message(instruction)}

    client = _pixfaro_client()
    used_model = model or "nano-banana-2"
    data = client.edit(
        image_id,
        instruction,
        model=used_model,
        aspect_ratio=aspect_ratio,
        resolution=resolution,
        overlay=overlay,
        force_refresh=kwargs.get("force_refresh", False),
    )
    return _image_result(data, used_model)


def available_models() -> Optional[list[dict[str, Any]]]:
    """Live Pixfaro model catalog (id, best_for, latency, price tiers).

    Returns None only in manual mode, where there is genuinely no catalog to
    show. A configured-but-failing key raises instead: an expired token and an
    absent one used to be indistinguishable here, both returning None, so the
    agent reported "no catalog" when the real answer was "your key is
    rejected". Callers wanting the old behaviour can catch PixfaroError.
    """
    if image_backend() == "manual":
        return None
    return _pixfaro_client().list_models()


if __name__ == "__main__":
    print(f"Active backend: {active_backend()}")
    if active_backend() == "manual":
        print("\nExample manual message:")
        print("-" * 60)
        print(
            manual_mode_message(
                draft_text="how I edited 30 videos in a weekend (the batching system) #contentcreator #editing",
                target_url="https://www.tiktok.com/upload",
                kind="video",
            )
        )
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 323kUpdated Claude CodeCodexVerifiedInstall