Communitygithub.com

ericrisco/rsc-harness

TikTok API — 実際のアカウント接続とデータ取り込みを行います。OAuth認証、チャンク分割動画公開、ステータスポーリング、視聴数・視聴時間・インプレッションソースの取得、結果のWikiへのフィードバック記録をカバーします。

rsc-harness とは?

このスキルは、TikTokのContent Posting API、Display API、Business Account APIを介して実際のTikTokアカウントをコードに接続するためのトランスポート層とデータ取り込みを提供します。OAuth v2(Login Kit)によるユーザー認証を管理し、短命なアクセストークンの定期的なリフレッシュを行います。動画の公開は、init(初期化)→ transfer(チャンク分割アップロードまたはURLからのプル)→ poll(ステータスポーリング)の3ステップで非同期実行されます。また、Display APIから基本的なカウンター(視聴数、いいね数など)を、Business APIから高度なエンゲージメント指標(平均視聴時間、完了率、インプレッションソース)を取得し、結果を日付付きのWikiエントリとして`02-DOCS/wiki/shortform/`に保存します。これにより、短期戦略やパッケージング担当のスキルが履歴データを参照できるようになります。このスキルは「何を投稿するか」や「どのようにパッケージングするか」は扱わず、それらは`shortform-strategy`や`shortform-packaging`などの兄弟スキルに委ねます。

対応✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ericrisco/rsc-harness/tree/HEAD/skills/tiktok-api

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

TikTok API — 実アカウントのトランスポート+データ取り込み

あなたが回線を掌握します:TikTokアカウントに認証し、動画を公開し、数値を取得し、それらの数値をWikiに耐久性のあるフィードバックログとして書き込みます。何を作るか、いつ投稿するか、キャプションをどうするかは決めません — それはショートフォーム戦略/パッケージングファミリーの仕事です。クリーンなトランスポートとクエリ可能なログを提供し、解釈は兄弟スキルに委ねましょう。

TikTokは3つの独立したAPIに分かれており、実際のアカウントはすべてを扱います:

  • Content Posting API — https://open.tiktokapis.com/v2/post/publish/... — 書き込み側:公開の初期化、ファイル転送、ステータスポーリング。監査が必要です。
  • Display API — https://open.tiktokapis.com/v2/video/... — 安価な読み取り側:自分のプロフィールと基本的な動画ごとのカウンター(view_count, like_count, comment_count, share_count)。
  • TikTok for Business API — リッチな読み取り側:視聴時間、完了率、インプレッションソース。標準の開発者アプリではなく、別のビジネスポータルで有効にします。

認証はLogin Kit経由のユーザーOAuth v2であり、サービストークンは使用しません。人間がアカウントを所有し、あなたはリフレッシュトークンを使ってその代理として行動します。公式のTikTok SDKはありません — 任意のHTTPクライアントでRESTエンドポイントを直接呼び出します。アクセストークンは短命でリフレッシュ可能な資格情報オブジェクトとして扱い、ハードコードされたリテラルにしてはいけません。

いつ使用するか / 使用しない場合

以下の場合に使用します:

  • スクリプトやエージェントをアカウントに接続して公開する場合:Direct Postまたは下書きへのアップロードは/v2/post/publish/video/init/(または下書きの場合は/inbox/)、次にFILE_UPLOADのチャンク分割PUTまたはPULL_FROM_URL、その後/v2/post/publish/status/fetch/をポーリングします。
  • アカウント自身の動画統計を取得する場合:カウンターはDisplay APIのPOST /v2/video/query/(または/v2/video/list/)で取得;視聴時間/完了率/インプレッションソースはBusiness Account APIで取得します。
  • 「パフォーマンス取得 → 02-DOCS/wiki/shortform/に書き込み」という定期ループを構築し、APIレスポンスを兄弟スキルが読み取り可能なアカウントフィードバックログに変換する場合。
  • TikTok固有の障害をデバッグする場合:scope_not_authorized、url_ownership_unverified、rate_limit_exceeded(6 req/min)、24時間のアクセストークン期限切れ、監査/video.publish未承認、未監査アプリのプライベートのみ投稿など。

以下の場合は使用しないでください(該当する兄弟スキルにルーティング):

実際に欲しいもの移動先
何を投稿するか / 投稿頻度 / ニッチ / フック戦略shortform-strategy (カタログID)
クリップアイデア、フック、トピックバックログshortform-ideation (カタログID)
キャプション / カバー / タイトルのパッケージング、ABフレーミングshortform-packaging (カタログID)
クリップのカット/キャプション/レンダリングshortform-editing (カタログID)
プログラムによる動画ファイルのレンダリング../remotion-video/SKILL.md
1つのアセットをTikTok + IG + YouTubeに同時投稿../social-publisher/SKILL.md
InstagramのGraph / Content Publishing API../instagram-api/SKILL.md
YouTubeの2つのAPI(同じファミリー、別プラットフォーム)../youtube-api/SKILL.md
任意のRESTプロバイダをOAuth + リトライでラップapi-connector-builder (カタログID)
公開 → Notion行 → Slackをツール間でチェーンautomation-flows (カタログID)

一行で:このスキルはTikTokのContent Posting + Display + Business APIを認証、呼び出し、Wikiに取り込みます。何を投稿するか、どうパッケージングするかはshortform-strategy / shortform-ideation / shortform-packaging兄弟スキルの担当であり、マルチネットワーク投稿はsocial-publisherの担当です。

1. 初期設定(コードの前に実施)

チェックリスト — 各ステップをスキップすると、後で明確で異なる障害が発生します:

  1. 開発者ポータルでTikTok開発者アプリを登録します。
  2. 必要な製品を追加します:Login Kit(OAuth)、Content Posting API(公開)、Display API(カウント読み取り)。インサイトは別のTikTok for Businessポータルにあります — 視聴時間/完了率も必要な場合は、そのアカウントアクセスも有効にします。
  3. OAuthフロー用の正確なリダイレクトURIを設定します。
  4. 公開コンテンツを投稿する前に、監査のためにアプリを提出します。 監査されていないアプリは、プライベート(SELF_ONLY)でのみ、限られたテストユーザーにしか投稿できません。これが「自分のマシンでは動くのに、本番で壊れる」という驚きの第1位です — 以下のルールを参照してください。
  5. URLで公開する場合(PULL_FROM_URL)、ポータルでドメイン / URLプレフィックスを検証します(DNS TXTまたはURLプレフィックス)。そうしないと、すべてのinitがurl_ownership_unverifiedを返します。

3つのゲートは独立しています。1つの承認がすべてをカバーすると想定しないでください:

悪い例:「アプリが承認されたから、公開もインサイトも両方動く」
良い例:Content Posting *監査* が公開を制御;
      Display *スコープ*(video.list)が自分の動画カウントを制御;
      Business *ポータル* アクセスが視聴時間 / 完了率 / インプレッションソースを制御。
      3つの独立したゲート — それぞれ確認。

スコープテーブル — ジョブに必要なものだけをリクエスト:

スコープ許可する内容使用用途
video.publish公開フィードへのDirect Post/post/publish/video/init/(監査必須)
video.uploadユーザーが仕上げる下書き/インボックスへのアップロード/post/publish/inbox/video/init/
video.list自分の動画と基本カウンターの読み取りDisplay POST /v2/video/query/
user.info.basicプロフィールの読み取り(open_id、表示名、アバター)POST /v2/user/info/

アプリ登録 + 製品有効化の完全な手順、監査ゲート、scope_not_authorizedのトラブルシューティングは references/oauth-setup.md にあります。

2. 認証済みクライアントを取得し、トークンを維持する

OAuth v2:ユーザーを https://www.tiktok.com/v2/auth/authorize/ に送り、リダイレクトURIで code を受け取り、https://open.tiktokapis.com/v2/oauth/token/ で交換し、リフレッシュトークンを保存します。

ライフサイクルが重要な事実です:アクセストークンは24時間で期限切れ(expires_in: 86400);リフレッシュトークンは365日間有効(refresh_expires_in: 31536000)で、ユーザーの再同意なしで更新されます。つまり、日次プルcronは毎回アクセストークンをリフレッシュする必要があり、長期間アイドル状態のアカウントは365日目のリフレッシュ境界で静かに利用不能になります。

# python: 生のREST、公式TikTok SDKなし。requests/httpxどちらでも可。
import time, json, os, requests

TOKEN_URL = "https://open.tiktokapis.com/v2/oauth/token/"
STORE = "tiktok_token.json"   # gitignored — ローテーションするrefresh_tokenを保持

def load(): return json.load(open(STORE)) if os.path.exists(STORE) else {}
def save(t): t["obtained_at"] = int(time.time()); json.dump(t, open(STORE, "w"))

def access_token():
    t = load()
    fresh = t.get("access_token") and time.time() < t.get("obtained_at", 0) + t["expires_in"] - 60
    if fresh:
        return t["access_token"]
    r = requests.post(TOKEN_URL, data={                 # 毎回リフレッシュ、24時間期限
        "client_key": os.environ["TIKTOK_CLIENT_KEY"],
        "client_secret": os.environ["TIKTOK_CLIENT_SECRET"],
        "grant_type": "refresh_token",
        "refresh_token": t["refresh_token"],            # 365日間有効、ローテーション
    }, headers={"Content-Type": "application/x-www-form-urlencoded"})
    r.raise_for_status()
    new = r.json()
    save(new)                                           # 新しいrefresh_tokenを永続化
    return new["access_token"]
// node: ビルトインfetch、SDK不要。
import fs from "node:fs";
const STORE = "tiktok_token.json";

async function accessToken() {
  const t = JSON.parse(fs.readFileSync(STORE, "utf8"));
  if (t.access_token && Date.now() / 1000 < t.obtained_at + t.expires_in - 60) return t.access_token;
  const r = await fetch("https://open.tiktokapis.com/v2/oauth/token/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      client_key: process.env.TIKTOK_CLIENT_KEY,
      client_secret: process.env.TIKTOK_CLIENT_SECRET,
      grant_type: "refresh_token",
      refresh_token: t.refresh_token,
    }),
  });
  const n = await r.json();
  n.obtained_at = Math.floor(Date.now() / 1000);
  fs.writeFileSync(STORE, JSON.stringify(n));          // ローテーションされたrefresh_tokenを永続化
  return n.access_token;
}

ルール:リフレッシュトークンを永続化し、毎回それを読み直します。生のaccess_token を決してハードコードしないでください。access_token=... リテラルは24時間以内に確実に失敗します — そしてそれはまさに verify.sh がフラグを立てるものです。

完全なトークン交換フロー(認可URLパラメータ、PKCE、コード交換)は references/oauth-setup.md にあります。

3. 動画を公開する(init → transfer → poll)

公開は常に3ステップ:公開の初期化、バイトの転送、処理が完了するまでポーリング(非同期)。最初に転送モードを選択:

状況ソースエンドポイント
ファイルがローカル / 制御下にあるFILE_UPLOAD/post/publish/video/init/
ファイルが検証済みHTTPS URLにあるPULL_FROM_URL/post/publish/video/init/
ユーザーが仕上げる下書きとして保存したいFILE_UPLOAD/post/publish/inbox/video/init/

Init(FILE_UPLOAD)— publish_id と upload_url を返します:

import math, requests

CHUNK = 10 * 1024 * 1024                      # 10 MB、5~64 MBの範囲内
size = os.path.getsize("clip.mp4")
chunk_count = 1 if size < 5 * 1024 * 1024 else math.ceil(size / CHUNK)

init = requests.post(
    "https://open.tiktokapis.com/v2/post/publish/video/init/",
    headers={"Authorization": f"Bearer {access_token()}",
             "Content-Type": "application/json; charset=UTF-8"},
    json={
        "post_info": {"title": "caption #fyp", "privacy_level": "SELF_ONLY"},  # 公開には監査が必要
        "source_info": {
            "source": "FILE_UPLOAD",
            "video_size": size,
            "chunk_size": CHUNK if size >= 5 * 1024 * 1024 else size,
            "total_chunk_count": chunk_count,
        },
    }).json()
publish_id = init["data"]["publish_id"]
upload_url = init["data"]["upload_url"]

Transfer — チャンクをupload_urlに順次PUTし、Content-Rangeヘッダーを付けます。チャンクは最小5 MB、最大64 MB(最後のチャンクは最大128 MB)、1~1000チャンク;5 MB未満のファイルはファイルサイズと同じ1チャンクです。各PUTは206(まだ送信あり)または201(最後のチャンク受付)を返します:

with open("clip.mp4", "rb") as f:
    for i in range(chunk_count):
        first = i * CHUNK
        data = f.read(CHUNK)
        last = first + len(data) - 1
        r = requests.put(upload_url, data=data, headers={
            "Content-Type": "video/mp4",
            "Content-Range": f"bytes {first}-{last}/{size}",  # 正確なバイト範囲
        })
        assert r.status_code in (206, 201), r.text     # 206 = 継続、201 = 完了

Poll — TikTokは非同期で処理;PUBLISH_COMPLETEになるまでステータスを確認。以下の上限を尊重 — タイトループは避けてください:

import time
while True:
    s = requests.post(
        "https://open.tiktokapis.com/v2/post/publish/status/fetch/",
        headers={"Authorization": f"Bearer {access_token()}",
                 "Content-Type": "application/json; charset=UTF-8"},
        json={"publish_id": publish_id}).json()
    status = s["data"]["status"]
    if status in ("PUBLISH_COMPLETE", "FAILED"):
        break
    time.sleep(10)                                      # 6/min 制限 — スリープ、スピンしない

レート制限:ユーザーアクセストークンあたり6リクエスト/分 → rate_limit_exceeded。init/status呼び出しをスロットルし、バックオフします。タイトなステータスポールループは数秒で予算を消費します。

PULL_FROM_URL は、ポータルでドメイン/URLプレフィックスが検証されている必要があります(HTTPSのみ、リダイレクト不可、1時間のダウンロードタイムアウト)。そうしないと、initは url_ownership_unverified を返します。完全なPULL_FROM_URL initボディと検証手順は references/metrics-and-publish.md にあります。

4. パフォーマンスを取得する(2つのAPI、1つのルール)

重要な違い:Displayはカウンターを提供します;Business APIだけが視聴時間、完了率、トラフィックを提供します。

# (a) Display API — 基本カウンターのみ。スコープ video.list、最大20 ID/リクエスト。
counts = requests.post(
    "https://open.tiktokapis.com/v2/video/query/",
    params={"fields": "id,title,view_count,like_count,comment_count,share_count,duration,create_time"},
    headers={"Authorization": f"Bearer {access_token()}",
             "Content-Type": "application/json"},
    json={"filters": {"video_ids": ["<id1>", "<id2>"]}}).json()
# 返り値:view_count, like_count, comment_count, share_count, duration, title, create_time
# (b) Business Account API — 本当のエンゲージメントシグナル。
# Displayでは取得できないメトリクスを返します:average_time_watched, total_time_watched,
# full_video_watched_rate(完了率), impression_sources(FYP / Following / profile /
# search), audience_countries。(エンドポイントの形状は references/metrics-and-publish.md にあります。)
悪い例: /v2/video/query/ から average_time_watched / full_video_watched_rate を期待する
良い例:カウンターは Display /v2/video/query/ から;
      視聴時間 + 完了率 + impression_sources は Business Account API から。

注意:Businessインサイトメトリクスは24~48時間の遅延があります。また、アプリ内の数値と異なる場合があります。新しく取得したデータは仮のものとして扱い、Wikiログ(次のセクション)で値が安定するのを観察します。APIごとの完全なメトリクスカタログは references/metrics-and-publish.md にあります。

5. Wikiに取り込む — 実際の成果物

標準出力に表示して消えるだけのプルは無駄です。すべてのプルは、02-DOCS/wiki/shortform/ 以下に日付付きエントリを追加し、プラットフォームごとに名前空間を分けます。これにより、アカウントの数値がクエリ可能な履歴となり、戦略/パッケージングの兄弟スキルが読み取れます。

02-DOCS/wiki/shortform/
  index.md                       # 最新スナップショットと未解決の質問へのローリングポインタ
  tiktok-account-2026-06-02.md   # 日付付きアカウントスナップショット(プルごとに1つ)
  videos/tiktok-<video_id>.md    # 動画ごとの実行ログ、最新エントリが上

ファイル名には tiktok- プレフィックスが付きます。これは同じ shortform/ Wiki がInstagramやYouTubeのプルも保持する可能性があるためで、名前空間によりプラットフォームの衝突を防ぎます。

プルごとのエントリテンプレート。フロントマターはOKF v0.1準拠 — 空でない type が唯一の必須項目です;title/tags/timestamp

…

[truncated for translation]

Individual skills in this repo

This repo contains 9 individual skills — each has its own dedicated page.

ericrisco/rsc-harness

Use when writing the words on a single conversion page — the hero headline and subhead, the offer, the proof and testimonials, and one primary CTA — or diagnosing a page that gets traffic and does not convert, as a copy problem rather than a layout one. NOT the paid ad that drives the click (that is `ads`), NOT the visual layout the words sit in (that is `design`), NOT the experiment that picks the winning variant (that is `ab-testing`).

ericrisco/rsc-harness

Use when you need to render an actual video file with Remotion — React compositions, the Composition/Sequence/TransitionSeries graph, transitions, burned-in word-by-word captions from a transcript, automatic silence removal, b-roll overlays, headless CI renders, and a final MP4 or MOV. NOT writing the script, hook, beats or caption text (that is `video-shorts`), NOT mastering audio to LUFS or building an RSS feed (that is `podcast`), NOT structuring the narrative arc (that is `course-storytelling`).

ericrisco/rsc-harness

Use when you have raw 9:16 footage and need it cut into a post-ready vertical short — dead air removed, fast jump cuts, karaoke word-by-word burned-in captions from a transcript, cuts and zooms snapped to the music beat, safe-area placement so captions clear the platform UI, and a platform-correct MP4 export. NOT writing the script, hook, beats or caption text (that is `video-shorts`), NOT building a Remotion React composition codebase (that is `remotion-video`), NOT deciding when or where to post (that is `social-publisher`).

ericrisco/rsc-harness

Use when a Reels/TikTok/Shorts account needs its next video ideas scored into a ranked backlog, grounded in its own performance log plus dated trending sounds, each bet logged so its outcome feeds the next batch. NOT scripting a chosen idea (that is `video-shorts`), NOT pillars or cadence (that is `shortform-strategy`), NOT packaging a finished cut (that is `shortform-packaging`).

ericrisco/rsc-harness

Use when a vertical short is shot or scripted and you need the upload-form copy and cover that win the feed — the hook line, the first-frame on-screen text, the search-led caption, a tight hashtag set, and the cover frame; it learns from what performed via the 02-DOCS log. NOT inventing the idea (that is `shortform-ideation`), NOT scripting or directing the cuts (that is `video-shorts`), NOT executing the edit (that is `shortform-editing`), NOT scheduling the post (that is `social-publisher`).

ericrisco/rsc-harness

Use when the unit of work is a TikTok/Reels account, not one clip: positioning, sustainable cadence and format mix, ride-or-skip on a trend or sound, recurring series, diagnosing a flat account, and the dated learning loop. NOT the single script or hook variants (that is `video-shorts`), NOT the idea backlog (that is `shortform-ideation`).

ericrisco/rsc-harness

Use when planning a posting schedule, building a multi-platform content calendar, or reshaping one source asset into channel-native posts across X, LinkedIn, Instagram, Threads, Bluesky, TikTok, Facebook or YouTube — cadence, best-time slots, per-platform format limits, API publish caps, and a dated CSV or JSON calendar a scheduler can import. NOT the brand voice the posts speak in (that is `brand-voice`), NOT the editorial strategy of what to make (that is `content-engine`).

ericrisco/rsc-harness

Use when scripting or directing the edit of a single vertical short that has to hold attention from the first frame — turning a topic, a clip or a long video into a shot-by-shot script and an edit decision sheet, fixing a hook that dies in second three, generating hook variants to test, and planning cuts and on-screen text. NOT scheduling or cross-platform cadence (that is `social-publisher`), NOT running the editorial calendar (that is `content-engine`), NOT defining the durable brand tone (that is `brand-voice`).

ericrisco/rsc-harness

Use to judge whether a short-form clip is worth publishing — scores a reel, short or podcast excerpt 0-100 on ten weighted criteria with automatic penalties, then ranks a batch and says where the cut-off falls. Run it on transcript candidates before rendering. NOT writing the hook or caption (that is `shortform-packaging`), NOT inventing the idea (that is `shortform-ideation`), NOT executing the edit (that is `shortform-editing`).

関連スキル