Communitygithub.com

ericrisco/rsc-harness

用於將真實 TikTok 帳號連接到程式碼,透過內容發布 API、Display API 和商業帳號 API 執行 OAuth 驗證、分段影片發布及狀態輪詢,並擷取觀看次數、觀看時間和曝光來源等數據,最後將這些效能記錄寫入 Wiki 作為有日期的回饋記錄。涵蓋短期 token 導致 cron 中斷、未經驗證的 URL 所有權以及速率限制等問題。不負責決定發布內容或包裝方式(這些由 `shortform-strategy` 和 `shortform-packaging` 負責)。

rsc-harness 是什麼?

此技能提供一個完整的傳輸和資料擷取管道,讓開發人員能透過程式碼與真實的 TikTok 帳號進行互動。它整合了三個獨立的 TikTok API:用於發布影片的內容發布 API、用於讀取基本計數器的 Display API,以及用於獲取觀看時間和曝光來源等深入數據的商業帳號 API。技能會處理使用者 OAuth v2 驗證流程,並管理短生命週期的存取 token,確保在 cron 任務中能可靠運作。此外,它還會將取得的效能數據(如觀看次數、按讚數、觀看時間和完成率)格式化並寫入專案的 Wiki 中,建立一個可供查詢的歷史記錄,讓共同負責策略和包裝的其他技能可以讀取這些數據。此技能的核心價值在於提供一個輕量、無 SDK 的 RESTful 整合方案,並以清晰的指南處理常見的 TikTok 開發陷阱,例如審核閘門、速率限制和 URL 所有權驗證。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

TikTok API — 真實帳號的傳輸與資料擷取

你擁有連線:通過驗證連接到 TikTok 帳號、發布影片、拉取數據,並將這些數據寫入 Wiki 作為持久的回饋記錄。你不決定要製作什麼內容、何時發布或如何寫標題——這些屬於短影音策略/包裝系列。提供乾淨的傳輸和可查詢的記錄;讓其他技能來解讀。

TikTok 分為三個獨立的 API,一個真實帳號會用到全部三個:

  • 內容發布 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 API for Business — 豐富讀取端:觀看時間、完成率、曝光來源。需透過獨立的商業入口網站啟用,而非標準的開發者應用。

驗證方式是透過 Login Kit 的使用者 OAuth v2,絕不使用服務 token。帳號由真人擁有;你以他們的代理人身份行動,並使用刷新 token。沒有官方的 TikTok SDK——你直接使用任何 HTTP 用戶端呼叫 REST 端點。將存取 token 視為一個短生命週期、可刷新的憑證物件,永遠不要將其硬編碼為字串。

何時使用 / 何時不使用

在以下情況使用:

  • 將腳本或代理程式連接到帳號進行發布:透過 /v2/post/publish/video/init/(或 /inbox/ 用於草稿)進行 Direct Post 或上傳至草稿,然後進行 FILE_UPLOAD 分段 PUT 或 PULL_FROM_URL,再輪詢 /v2/post/publish/status/fetch/。
  • 拉取帳號自己的影片統計數據:透過 Display POST /v2/video/query/(或 /v2/video/list/)取得計數器;透過商業帳號 API 取得觀看時間、完成率、曝光來源。
  • 建立一個循環流程:「獲取效能 → 寫入 02-DOCS/wiki/shortform/」將 API 回應轉換為其他技能可讀取的帳號回饋記錄。
  • 除錯特定 TikTok 錯誤:scope_not_authorized、url_ownership_unverified、rate_limit_exceeded(每分鐘 6 次請求)、24 小時存取 token 過期、video.publish 未通過審核、未審核應用僅能私密發布。

在以下情況不要使用(請轉交給負責該項目的技能):

你實際上想要的是請前往
發布內容/節奏/利基/鉤子策略shortform-strategy (目錄 ID)
片段靈感、鉤子、主題待辦事項shortform-ideation (目錄 ID)
標題/封面/影片包裝、A/B 測試框架shortform-packaging (目錄 ID)
剪輯/加字幕/渲染實際影片檔案shortform-editing (目錄 ID)
以程式方式渲染影片檔案../remotion-video/SKILL.md
同時發布一個資產到 TikTok + IG + YouTube../social-publisher/SKILL.md
Instagram 的 Graph / Content Publishing API../instagram-api/SKILL.md
YouTube 的兩個 API(同系列,其他平台)../youtube-api/SKILL.md
為任意 REST 提供者包裝 OAuth + 重試機制api-connector-builder (目錄 ID)
跨工具鏈接發布 → Notion 行 → Slackautomation-flows (目錄 ID)

一句話總結:這個技能負責驗證、呼叫 TikTok 的內容發布 + 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)發布,且僅限於有限的測試使用者。這是「在我機器上可以,正式環境就壞掉」的頭號意外——請參閱下方規則。
  5. 如果你透過 URL(PULL_FROM_URL)發布,請在入口網站驗證網域/URL 前綴(DNS TXT 或 URL 前綴),否則每次初始化都會回傳 url_ownership_unverified。

這三個閘門是獨立的。不要假設一個批准涵蓋全部:

錯誤:「我的應用程式已獲批准,所以發布和深入分析都能用。」
正確:內容發布 *審核* 閘門控制公開發布;
      Display *範圍*(video.list)控制自己的影片計數;
      Business *入口網站* 存取控制觀看時間/完成率/曝光來源。
      三個獨立的閘門——請逐一檢查。

範圍表——只請求工作需要的:

範圍授予用於
video.publish直接發布到公開動態/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. 取得已驗證的用戶端並保持 token 有效

OAuth v2:將使用者導向 https://www.tiktok.com/v2/auth/authorize/,在重新導向 URI 收到 code,在 https://open.tiktokapis.com/v2/oauth/token/ 交換它,並儲存 refresh token。

生命週期是關鍵事實:access token 在 24 小時後過期(expires_in: 86400);refresh token 持續 365 天(refresh_expires_in: 31536000)且無需使用者重新同意即可更新。因此,每日執行的 cron 必須在每次執行時刷新 access token,而長時間閒置的帳號會在 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"   # 已加入 gitignore — 保存滾動的 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;
}

規則:儲存 refresh token 並在每次執行時重新讀取,永遠不要使用裸的 access_token。硬編碼的 access_token=... 字串保證在 24 小時內失敗——而這正是 verify.sh 會標記的問題。

完整的 token 交換流程(授權 URL 參數、PKCE、code 交換)位於 references/oauth-setup.md。

3. 發布影片(初始化 → 傳輸 → 輪詢)

發布總是三個步驟:初始化發布、傳輸位元組、輪詢直到處理完成(這是非同步的)。首先選擇傳輸模式:

情況來源端點
檔案在本機/在你的控制下FILE_UPLOAD/post/publish/video/init/
檔案在一個已驗證的 HTTPS URL 上PULL_FROM_URL/post/publish/video/init/
應以草稿形式儲存,由使用者最終完成FILE_UPLOAD/post/publish/inbox/video/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"]

傳輸——依序 PUT 區塊到 upload_url,並附帶 Content-Range 標頭。區塊最小 5 MB,最大 64 MB(最後一個區塊最多 128 MB),1–1000 個區塊;小於 5 MB 的檔案是一個區塊,大小等於檔案大小。每個 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 = 完成

輪詢——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 次限制 — 睡眠,永不空轉

速率限制:每個使用者存取 token 每分鐘 6 次請求 → rate_limit_exceeded。限制初始化/狀態呼叫的頻率並進行退避;緊密的狀態輪詢迴圈會在幾秒鐘內耗盡配額。

PULL_FROM_URL 要求網域/URL 前綴已在入口網站中驗證(僅限 HTTPS,無重新導向,1 小時下載超時),否則初始化會回傳 url_ownership_unverified。完整的 PULL_FROM_URL 初始化主體和驗證步驟位於 references/metrics-and-publish.md。

4. 拉取效能(兩個 API,一條規則)

關鍵區別: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 / 跟蹤 / 個人檔案 /
# 搜尋)、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   # 帶日期的帳號快照(每次拉取一個)
  videos/tiktok-<video_id>.md    # 每個影片的運行記錄,最新條目在最上方

檔案名稱帶有 tiktok- 前綴,因為同一個 shortform/ Wiki 可能也包含 Instagram 和 YouTube 的拉取記錄——命名空間可防止平台衝突。

每次拉取的條目模板。前置資料是符合 OKF v0.1 規範的——非空的 type 是唯一的硬性要求;title/tags/timestamp

……

[翻譯因長度截斷]

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`).

相關技能