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
Google Cloud Console にアクセスし、Google アカウントでログインする。 Access Google Cloud Console and sign in with your Google account.
ヘッダーのプロジェクトセレクターをクリックし「新しいプロジェクト」を選択する。 Click the project selector in the header and choose "New Project".
プロジェクト名を入力(例:
ai-cohabitation-life)し「作成」をクリックする。 Enter a project name (e.g.ai-cohabitation-life) and click "Create".作成が完了したら、そのプロジェクトが選択状態であることを確認する。 Once created, confirm the project is selected.
2. API の有効化 / Enable APIs
左メニューから 「API とサービス」→「ライブラリ」 を開く。 Open "APIs & Services" → "Library" from the left menu.
以下の 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
「API とサービス」→「認証情報」→「+認証情報を作成」→「OAuth クライアント ID」 を選択する。 Go to "APIs & Services" → "Credentials" → "+ Create Credentials" → "OAuth client ID".
初回はまず 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)
OAuth クライアント ID を作成する: Create the OAuth client ID:
- アプリケーションの種類: ウェブアプリケーション (Web application)
- 承認済みリダイレクト URI:
https://developers.google.com/oauthplaygroundAuthorized redirect URI:https://developers.google.com/oauthplayground
表示される クライアント 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.
右上の歯車アイコンをクリックし、以下を設定する: 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
左側のスコープ一覧から以下を選択し「Authorize APIs」をクリック: Select the following scopes from the left panel and click "Authorize APIs":
https://www.googleapis.com/auth/youtube.readonlyhttps://www.googleapis.com/auth/youtube.force-ssl
Google アカウントでログインし、アクセスを許可する。 Sign in with your Google account and grant access.
「Exchange authorization code for tokens」をクリックする。 Click "Exchange authorization code for tokens".
表示される Refresh Token を
.envに保存する。 Save the displayed Refresh Token to your.envfile.
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: followpollingIntervalMillisfrom 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 500in 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, useMOCK_MODE=trueto 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.
npm install tiktok-live-connector2. 接続方法 / 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.
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 |
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
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 イベントをシミュレートする。 UseMOCK_MODE=trueto simulate TikTok events.
Claude API (Anthropic)
1. API キー取得 / Obtain API Key
Anthropic Console にアクセスし、アカウントを作成またはログインする。 Access Anthropic Console and create an account or sign in.
「API Keys」 セクションに移動する。 Navigate to the "API Keys" section.
「Create Key」 をクリックし、キー名を入力して発行する。 Click "Create Key", enter a key name, and generate it.
表示される API キーを 一度だけ コピーし、
.envのANTHROPIC_API_KEYに保存する。 Copy the displayed API key (shown only once) and save it toANTHROPIC_API_KEYin.env.
セキュリティ注意 / Security Notice
API キーは絶対にソースコードに直接記載しないこと。必ず環境変数を使用する。 Never hard-code API keys in source code. Always use environment variables.
2. SDK インストール / Install SDK
npm install @anthropic-ai/sdk3. モデル ID / Model ID
本プロジェクトでは以下のモデルを使用する: This project uses the following model:
| モデル / Model | ID |
|---|---|
| Claude Haiku (高速・低コスト / Fast & low-cost) | claude-haiku-4-5-20251001 |
4. 基本呼び出しパターン / Basic Usage Pattern
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.
cp .env.example .env.env.example をコピーして .env を作成し、各値を入力する。 Copy .env.example to .env and fill in each value.
セキュリティ考慮事項 / Security Considerations
.envは.gitignoreに含まれており、Git にコミットされない。.envis included in.gitignoreand 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.exampleand obtain their own keys individually.