Skip to content

API セットアップ / API Setup

本ページでは YouTube・TikTok・Claude 各 API の認証セットアップ手順を解説します。 This page explains the authentication setup procedures for the YouTube, TikTok, and Claude APIs.


YouTube Live Streaming API

1. Google Cloud プロジェクト作成 / Create a Google Cloud Project

  1. Google Cloud Console にアクセスし、Google アカウントでログインする。 Access Google Cloud Console and sign in with your Google account.

  2. ヘッダーのプロジェクトセレクターをクリックし「新しいプロジェクト」を選択する。 Click the project selector in the header and choose "New Project".

  3. プロジェクト名を入力(例: ai-cohabitation-life)し「作成」をクリックする。 Enter a project name (e.g. ai-cohabitation-life) and click "Create".

  4. 作成が完了したら、そのプロジェクトが選択状態であることを確認する。 Once created, confirm the project is selected.

2. API の有効化 / Enable APIs

  1. 左メニューから 「API とサービス」→「ライブラリ」 を開く。 Open "APIs & Services" → "Library" from the left menu.

  2. 以下の 2 つの API を検索し、それぞれ 「有効にする」 をクリックする。 Search for the following 2 APIs and click "Enable" for each:

    • YouTube Data API v3
    • YouTube Live Streaming API

3. OAuth 2.0 設定 / OAuth 2.0 Configuration

  1. 「API とサービス」→「認証情報」→「+認証情報を作成」→「OAuth クライアント ID」 を選択する。 Go to "APIs & Services" → "Credentials" → "+ Create Credentials" → "OAuth client ID".

  2. 初回はまず OAuth 同意画面 を構成する必要がある。 If this is your first time, you need to configure the OAuth consent screen first.

    • ユーザータイプ: 外部 (External)
    • アプリ名・メールアドレスを入力 Enter the app name and email address
    • スコープは後で設定するため、そのまま保存 Save without adding scopes (they'll be set later)
  3. OAuth クライアント ID を作成する: Create the OAuth client ID:

    • アプリケーションの種類: ウェブアプリケーション (Web application)
    • 承認済みリダイレクト URI: https://developers.google.com/oauthplayground Authorized redirect URI: https://developers.google.com/oauthplayground
  4. 表示される クライアント IDクライアントシークレット を控える。 Note down the displayed Client ID and Client Secret.

4. リフレッシュトークン取得 / Obtain Refresh Token

OAuth 2.0 Playground を使用してリフレッシュトークンを取得する。 Use the OAuth 2.0 Playground to obtain a refresh token.

  1. 右上の歯車アイコンをクリックし、以下を設定する: Click the gear icon in the top-right corner and configure:

    • Use your own OAuth credentials にチェック Check "Use your own OAuth credentials"
    • Client ID / Client Secret に取得済みの値を入力 Enter the Client ID / Client Secret obtained earlier
  2. 左側のスコープ一覧から以下を選択し「Authorize APIs」をクリック: Select the following scopes from the left panel and click "Authorize APIs":

    • https://www.googleapis.com/auth/youtube.readonly
    • https://www.googleapis.com/auth/youtube.force-ssl
  3. Google アカウントでログインし、アクセスを許可する。 Sign in with your Google account and grant access.

  4. Exchange authorization code for tokens」をクリックする。 Click "Exchange authorization code for tokens".

  5. 表示される Refresh Token.env に保存する。 Save the displayed Refresh Token to your .env file.

5. 必要スコープ / Required Scopes

スコープ / Scope用途 / Purpose
youtube.readonlyライブ配信の視聴データ取得 / Read live stream data
youtube.force-sslライブチャットメッセージの読み書き / Read/write live chat messages

6. Quota 管理 / Quota Management

  • YouTube Data API v3 のデフォルト Quota は 1 日 10,000 ユニット である。 The default quota for YouTube Data API v3 is 10,000 units per day.
  • ライブチャットのポーリング (liveChatMessages.list) は 1 回あたり約 5 ユニット消費する。 Polling live chat (liveChatMessages.list) costs approximately 5 units per call.
  • ポーリング間隔を適切に設定し(推奨: API レスポンスの pollingIntervalMillis に従う)、Quota 超過を防止する。 Set appropriate polling intervals (recommended: follow pollingIntervalMillis from API response) to avoid exceeding the quota.
  • Quota の上限引き上げが必要な場合は Google Cloud Console の Quota ページ から申請する。 If you need a higher quota limit, apply via the Quota page in Google Cloud Console.

7. 収益化条件未達時の運用 / Operation Without Monetization

YouTube のスーパーチャット(投げ銭)機能を利用するにはチャンネルの収益化が必要だが、収益化条件を満たしていない段階では以下の代替運用が可能: Super Chat (tipping) requires channel monetization, but the following alternatives are available before meeting monetization requirements:

  • チャットコマンド方式: 視聴者がチャットに !tip 500 のようなコマンドを投稿し、アプリ側で独自の投げ銭として処理する。 Chat command method: Viewers post commands like !tip 500 in chat, and the app processes them as custom tips.
  • 外部決済連携: StreamElements や Streamlabs 等の外部サービスの Donation 機能を Webhook で連携する。 External payment integration: Integrate donation features from services like StreamElements or Streamlabs via webhooks.
  • MOCK_MODE: 開発・テスト時は MOCK_MODE=true で投げ銭イベントをシミュレートできる。 During development/testing, use MOCK_MODE=true to simulate tipping events.

TikTok Live API

1. TikTok-Live-Connector の導入 / Install TikTok-Live-Connector

TikTok-Live-Connector は npm パッケージとして提供されている非公式ライブラリである。 TikTok-Live-Connector is an unofficial library available as an npm package.

bash
npm install tiktok-live-connector

2. 接続方法 / Connection Method

TikTok Live への接続にはAPIキーや認証トークンは不要である。ユーザー名を指定して WebSocket で接続する。 No API key or auth token is required to connect to TikTok Live. Connect via WebSocket by specifying a username.

javascript
import { WebcastPushConnection } from 'tiktok-live-connector';

const tiktokLive = new WebcastPushConnection(process.env.TIKTOK_USERNAME);

tiktokLive.connect()
  .then(state => {
    console.log(`Connected to ${state.roomId}`);
  })
  .catch(err => {
    console.error('Connection failed:', err);
  });

認証不要 / No Authentication Required

TikTok-Live-Connector は公開配信に対して認証なしで接続できる。.env にはユーザー名 (TIKTOK_USERNAME) のみ設定すればよい。 TikTok-Live-Connector can connect to public live streams without authentication. You only need to set the username (TIKTOK_USERNAME) in .env.

3. 受信イベント一覧 / Receivable Events

イベント / Event説明 / Description
chatチャットメッセージ / Chat message
giftギフト(投げ銭) / Gift (tip)
likeいいね / Like
followフォロー / New follower
shareシェア / Share
subscribeサブスクリプション / Subscription
member視聴者入室 / Viewer joined
roomUserルーム内ユーザー数更新 / Room user count update
liveIntro配信説明文の変更 / Live intro changed
emoteエモート / Emote
envelopeトレジャーボックス / Treasure box
javascript
tiktokLive.on('gift', data => {
  if (data.giftType === 1 && !data.repeatEnd) {
    // ストリーキングギフト(進行中) / Streaking gift (ongoing)
    return;
  }
  console.log(`${data.uniqueId} sent ${data.repeatCount}x ${data.giftName}`);
});

tiktokLive.on('chat', data => {
  console.log(`${data.uniqueId}: ${data.comment}`);
});

4. 自動再接続 / Auto-Reconnect

javascript
const tiktokLive = new WebcastPushConnection(process.env.TIKTOK_USERNAME, {
  enableExtendedGiftInfo: true,
  requestPollingIntervalMs: 1000,
});

tiktokLive.on('disconnected', () => {
  console.log('Disconnected. Attempting reconnect in 5s...');
  setTimeout(() => {
    tiktokLive.connect().catch(console.error);
  }, 5000);
});

5. フォロワー要件と代替戦略 / Follower Requirements & Alternatives

TikTok LIVE を利用するには通常 1,000 フォロワー以上 が必要である。 Using TikTok LIVE typically requires 1,000+ followers.

条件未達時の戦略: Strategies when requirements are not met:

  • YouTube 単独配信: まず YouTube のみで配信を開始し、TikTok は後から追加する。 YouTube-only streaming: Start streaming on YouTube only, and add TikTok later.
  • テスト用アカウント: TikTok から開発者アカウントの申請を行う。 Test account: Apply for a developer account from TikTok.
  • MOCK_MODE: MOCK_MODE=true で TikTok イベントをシミュレートする。 Use MOCK_MODE=true to simulate TikTok events.

Claude API (Anthropic)

1. API キー取得 / Obtain API Key

  1. Anthropic Console にアクセスし、アカウントを作成またはログインする。 Access Anthropic Console and create an account or sign in.

  2. 「API Keys」 セクションに移動する。 Navigate to the "API Keys" section.

  3. 「Create Key」 をクリックし、キー名を入力して発行する。 Click "Create Key", enter a key name, and generate it.

  4. 表示される API キーを 一度だけ コピーし、.envANTHROPIC_API_KEY に保存する。 Copy the displayed API key (shown only once) and save it to ANTHROPIC_API_KEY in .env.

セキュリティ注意 / Security Notice

API キーは絶対にソースコードに直接記載しないこと。必ず環境変数を使用する。 Never hard-code API keys in source code. Always use environment variables.

2. SDK インストール / Install SDK

bash
npm install @anthropic-ai/sdk

3. モデル ID / Model ID

本プロジェクトでは以下のモデルを使用する: This project uses the following model:

モデル / ModelID
Claude Haiku (高速・低コスト / Fast & low-cost)claude-haiku-4-5-20251001

4. 基本呼び出しパターン / Basic Usage Pattern

javascript
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

async function generateResponse(prompt, systemPrompt = '') {
  const message = await anthropic.messages.create({
    model: 'claude-haiku-4-5-20251001',
    max_tokens: 1024,
    system: systemPrompt,
    messages: [
      { role: 'user', content: prompt },
    ],
  });

  return message.content[0].text;
}

// 使用例 / Example usage
const response = await generateResponse(
  'サラに「おかえり」と言って。/ Say "welcome back" to Sara.',
  'あなたはジョンです。サラと同棲中の優しい彼氏です。/ You are John, a kind boyfriend living with Sara.'
);
console.log(response);

環境変数管理 / Environment Variable Management

.env ファイル / .env File

プロジェクトルートに .env ファイルを作成し、各 API キーやトークンを設定する。 Create a .env file in the project root and configure each API key and token.

bash
cp .env.example .env

.env.example をコピーして .env を作成し、各値を入力する。 Copy .env.example to .env and fill in each value.

セキュリティ考慮事項 / Security Considerations

  • .env.gitignore に含まれており、Git にコミットされない。 .env is included in .gitignore and will not be committed to Git.
  • API キーやトークンは 絶対に リポジトリにプッシュしないこと。 Never push API keys or tokens to the repository.
  • 本番環境ではサーバーの環境変数や Secrets Manager(例: Cloudflare Workers Secrets)を使用する。 In production, use server environment variables or Secrets Manager (e.g. Cloudflare Workers Secrets).
  • チームメンバーには .env.example を参照させ、個別にキーを取得してもらう。 Have team members refer to .env.example and obtain their own keys individually.