Communitygithub.com

ericrisco/rsc-harness — TikTok API 전송 및 데이터 수집

실제 TikTok 계정을 코드에 연결할 때 사용합니다. Content Posting, Display, Business Account API를 통해 OAuth 인증, 청크 분할 동영상 게시 및 상태 폴링, 조회수/시청 시간/트래픽 소스 데이터를 가져와 wiki에 날짜별 피드백 레코드로 기록합니다. 단기 토큰 만료, 확인되지 않은 URL 소유권, Rate Limit을 처리합니다. 무엇을 게시할지 또는 패키징 방법은 다루지 않습니다(이는 `shortform-strategy` 및 `shortform-packaging` 담당).

rsc-harness — TikTok API 전송 및 데이터 수집란 무엇인가요?

이 스킬은 실제 TikTok 계정과 상호작용하는 모든 코드(스크립트, AI 에이전트, 크론 작업)를 위한 핵심 전송 계층입니다. Content Posting API(게시), Display API(기본 조회수/좋아요 등), Business Account API(시청 시간, 완료율, 트래픽 소스)라는 세 가지 별도 TikTok API를 OAuth 2.0 인증을 통해 안전하게 호출합니다. 주요 기능으로는 액세스 토큰 자동 갱신(24시간 만료, 리프레시 토큰 365일), 청크 분할(FILE_UPLOAD) 또는 URL 기반(PULL_FROM_URL) 동영상 게시, 게시 상태 폴링, 분당 6회의 엄격한 Rate Limit 준수, Display API와 Business API에서 수집한 성능 데이터를 wiki(`02-DOCS/wiki/shortform/`)에 날짜별로 기록하여 전략/패키징 관련 스킬이 참조할 수 있는 피드백 로그를 만듭니다. 이 스킬은 '무엇을' 만들지, '언제' 게시할지 또는 '어떻게' 캡션을 달지 결정하지 않으며, 순수한 데이터 전송과 로깅에 집중합니다. TikTok 애플리케이션 감사, URL 소유권 확인, Business 포털 활성화 등 사전 설정이 필요합니다.

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

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

TikTok API — 실제 계정 전송 및 데이터 수집

당신이 유선(wire)을 소유합니다: TikTok 계정에 인증하고, 동영상을 게시하고, 수치를 가져와서 wiki에 지속적인 피드백 로그로 기록합니다. 무엇을 만들지, 언제 게시할지, 어떻게 캡션을 달지는 결정하지 않습니다 — 이는 shortform 전략/패키징 제품군의 역할입니다. 깨끗한 전송과 질의 가능한 로그를 제공하고, 다른 스킬들이 해석하도록 맡깁니다.

TikTok은 세 가지 개별 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 API for Business — 풍부한 읽기 측: 시청 시간, 완료율, 트래픽 소스. 표준 개발자 앱이 아닌 별도의 비즈니스 포털을 통해 활성화됩니다.

인증은 **사용자 OAuth v2(Login Kit)**를 통해서만 가능하며, 서비스 토큰은 사용할 수 없습니다. 사람이 계정을 소유하며, 당신은 리프레시 토큰을 사용하여 그들을 대신해 작업합니다. 공식 TikTok SDK는 없습니다 — 직접 REST 엔드포인트를 HTTP 클라이언트로 호출합니다. 액세스 토큰은 수명이 짧고 갱신 가능한 자격 증명 객체로 취급하며, 하드코딩된 리터럴로 절대 사용하지 마십시오.

사용 시기 / 사용하지 말아야 할 때

다음과 같은 경우 사용합니다:

  • 스크립트나 에이전트를 계정에 연결하여 게시: Direct Post 또는 업로드-초안 via /v2/post/publish/video/init/ (또는 /inbox/ 초안), 그 다음 FILE_UPLOAD 청크 분할 PUT 또는 PULL_FROM_URL, 이후 /v2/post/publish/status/fetch/ 폴링.
  • 계정 자체 동영상 통계 가져오기: Display 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 (catalog id)
클립 아이디어, 후크, 주제 백로그shortform-ideation (catalog id)
캡션 / 커버 / 제목 패키징, A/B 프레이밍shortform-packaging (catalog id)
실제 클립 파일 자르기/캡션/렌더링shortform-editing (catalog 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 (catalog id)
게시 → Notion 행 → Slack을 도구 간에 연결automation-flows *(catalog 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-접두사). 그렇지 않으면 모든 초기화가 url_ownership_unverified를 반환합니다.

세 가지 게이트는 독립적입니다. 하나의 승인이 모든 것을 포괄한다고 가정하지 마십시오:

잘못된 예:  "내 앱이 승인되었으므로 게시와 인사이트 모두 작동할 것이다."
올바른 예: Content Posting *감사*는 공개 게시를 제어;
      Display *범위* (video.list)는 자체 동영상 조회수를 제어;
      Business *포털* 액세스는 시청 시간 / 완료율 / 트래픽 소스를 제어.
      세 가지 별도 게이트 — 각각 확인해야 함.

범위 표 — 작업에 필요한 것만 요청하십시오:

범위부여하는 권한사용처
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)하며 사용자 재동의 없이 갱신됩니다. 따라서 매일 실행되는 크론은 매 실행마다 액세스 토큰을 갱신해야 하며, 오래 유휴 상태인 계정은 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가 플래그하는 내용입니다.

전체 토큰 교환 흐름 (authorize URL 매개변수, PKCE, 코드 교환)은 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"]

전송 — upload_url에 순차적으로 Content-Range 헤더와 함께 PUT 청크. 청크 최소 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/min 제한 — 절대 회전하지 말고 sleep

Rate limit: 사용자 액세스 토큰당 분당 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 / Following / profile /
# search), audience_countries. (엔드포인트 형태는 references/metrics-and-publish.md 참조)
잘못된 예:  /v2/video/query/에서 average_time_watched / full_video_watched_rate 기대
올바른 예: Display /v2/video/query/에서 카운터;
      Business Account API에서 시청 시간 + 완료율 + 트래픽 소스.

주의사항: Business 인사이트 메트릭은 24–48시간 지연되며 앱 내 수치와 다를 수 있습니다. 방금 가져온 데이터는 잠정적으로 간주 — wiki 로그(다음 섹션)에서 값이 안정화되는 것을 관찰합니다. API별 전체 메트릭 카탈로그는 references/metrics-and-publish.md에 있습니다.

5. wiki로 수집 — 실제 결과물

stdout에 출력하고 사라지는 가져오기는 낭비입니다. 모든 가져오기는 날짜가 표시된 항목을 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

…

[참고: 원본 SKILL.md가 잘렸으나, 나머지 내용도 동일한 방식으로 번역됩니다.]

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

관련 스킬