📰

Claude API + GitHub Actions で毎朝AIニュースを自動生成する【月500円】

に公開

はじめに

毎朝6時に、世界中のニュースを収集し、AIが日英バイリンガルの記事と音声を自動生成する——そんなシステムを個人開発で作り、月額約500円で運用しています。

https://keylang.study/daily-news
実際に生成された記事

作ったもの

英語学習サービス KeyLang.study の機能として、「Daily News」を毎朝自動配信しています。

特徴:

  • 🌍 世界6地域・26メディアからニュースを自動収集
  • 🤖 Claude APIで日英両言語の原稿を生成
  • 🎧 Google Cloud TTSで英語音声を生成
  • ⏰ 毎朝6時(JST)に完全自動で公開

この記事では、実際に運用しているコードとコスト内訳を全て公開します。


アーキテクチャ

全体の流れはシンプルな4ステップです。

┌─────────────────────────────────────────────────────────────────┐
│                    GitHub Actions (毎朝 6:00 JST)                │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  ┌──────────┐    ┌──────────┐    ┌──────────┐    ┌──────────┐  │
│  │ Step 1   │    │ Step 2   │    │ Step 3   │    │ Step 4   │  │
│  │ RSS取得  │ →   │ Claude   │ → │ TTS生成  │  →  │ 公開     │  │
│  │          │    │ API      │    │          │    │          │  │
│  └──────────┘    └──────────┘    └──────────┘    └──────────┘  │
│       ↑               ↑               ↑               ↓        │
│  26 RSS Feeds    Anthropic     Google Cloud      Supabase      │
│                                    TTS         (DB + Storage)   │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

使用技術

用途 技術
ワークフロー実行 GitHub Actions
ニュース取得 rss-parser (npm)
記事生成 Claude API (claude-sonnet-4-20250514)
音声生成 Google Cloud Text-to-Speech
データベース Supabase
音声ストレージ Supabase Storage
フロントエンド Next.js (Vercel)

Step 1: RSSフィードからニュースを収集

まず、世界中のニュースソースからRSSフィードを取得します。

ニュースソースの設計

地域バランスを重視し、欧米に偏らないよう6地域からソースを選定しました。

config/rss-sources.json
{
  "sources": [
    { "name": "NPxxxxxxx", "url": "https://feeds.nxxxxxxxx/rss.xml", "region": "North America", "priority": 1 },
    { "name": "BBxxxxxxx", "url": "http://feeds.bxxxxxxxxx/rss.xml", "region": "Europe", "priority": 1 },
    { "name": "Alxxxxxa", "url": "https://www.axxxxxxxxxxxx/all.xml", "region": "MENA", "priority": 1 },
    { "name": "NHxxxxxx", "url": "https://www3.nhxxxxxxxxxxxxxxx/cat0.xml", "region": "Asia-Pacific", "priority": 1 },
    { "name": "Afrixxxxxx", "url": "https://www.afrixxxxxxxx/feed/", "region": "Sub-Saharan Africa", "priority": 1 },
    { "name": "Mercxxxxxx", "url": "https://en.mercxxxxxxxxxxx/rss", "region": "Latin America", "priority": 1 }
    // ... 合計26ソース
  ],
  "regionBalance": {
    "target": {
      "Europe": 4,
      "North America": 3,
      "MENA": 4,
      "Asia-Pacific": 5,
      "Sub-Saharan Africa": 2,
      "Latin America": 2
    }
  }
}

スコアリングアルゴリズム

収集した記事を重要度でランキングし、上位20件を選定します。

scripts/daily-news/01-fetch-news.ts
function calculateScore(article: Article): number {
  let score = 0;
  const text = (article.title + ' ' + article.description).toLowerCase();

  // 高インパクトキーワード: +10点
  const highImpactKeywords = [
    'war', 'peace', 'ceasefire', 'election', 'president',
    'earthquake', 'flood', 'climate', 'summit', 'treaty'
  ];
  highImpactKeywords.forEach((keyword) => {
    if (text.includes(keyword)) score += 10;
  });

  // ソースの優先度: priority 1 = +20点
  score += (3 - article.priority) * 10;

  // 新鮮度: 6時間以内 = +15点
  const hoursAgo = (Date.now() - new Date(article.pubDate).getTime()) / (1000 * 60 * 60);
  if (hoursAgo <= 6) score += 15;
  else if (hoursAgo <= 12) score += 10;

  return score;
}

地域バランスを考慮した選定

単純にスコア順で選ぶと欧米メディアに偏るため、各地域の最低数を保証しています。

function selectArticles(articles: Article[], config: RSSConfig): Article[] {
  const selected: Article[] = [];
  const { target, minimum } = config.regionBalance;

  // まず各地域の最低数を確保
  for (const region of Object.keys(minimum)) {
    const regionArticles = articles
      .filter(a => a.region === region)
      .sort((a, b) => (b.score || 0) - (a.score || 0));
    
    for (let i = 0; i < minimum[region] && i < regionArticles.length; i++) {
      selected.push(regionArticles[i]);
    }
  }

  // 残りの枠をスコア順で埋める(地域上限あり)
  // ...
  
  return selected.slice(0, 20);
}

出力例:

Region distribution: {
  "Asia-Pacific": 5,
  "Europe": 4,
  "MENA": 4,
  "North America": 3,
  "Sub-Saharan Africa": 2,
  "Latin America": 2
}

Step 2: Claude APIで日英バイリンガル原稿を生成

収集したニュースデータをClaude APIに送り、日英両言語のニュース原稿を生成します。

編集方針(プロンプト設計)

ニュースの中立性を担保するため、厳密な編集方針をプロンプトに組み込んでいます。

prompts/news-prompt.md
あなたは「KeyLang Daily News」のニュース原稿ライターです。
世界中の出来事を、偏りなく、フラットに、事実ベースで伝えることがミッションです。

## 編集方針

### 1. 事実と意見の分離
- 事実のみを伝える。意見・評価・予測は加えない
- 誰かの主張を伝える場合は「〜と述べた」「〜と主張している」と明示

### 2. 複数視点の併記
- 対立がある場合、必ず双方の立場を伝える
- どちらかを正当化したり、悪者にしたりしない

### 3. 禁止表現
使用禁止:残虐な、卑劣な、野蛮な、英雄的な、テロリスト
推奨表現:「〜と報じられています」「〜と主張しています」

## 原稿仕様
- ニュース本数: 20本
- 1本あたり: 3-5文(日本語120-180文字、英語60-90語)
- 英語の語彙レベル: CEFR B1-B2(中級学習者向け)

API呼び出し

scripts/daily-news/02-generate-script.ts
import Anthropic from '@anthropic-ai/sdk';

const anthropic = new Anthropic();

async function generateScript(newsData: NewsData, promptTemplate: string) {
  const formattedNews = formatNewsForPrompt(newsData);

  const response = await anthropic.messages.create({
    model: 'claude-sonnet-4-20250514',
    max_tokens: 8000,
    system: promptTemplate,
    messages: [{
      role: 'user',
      content: `以下のニュースデータを元に、KeyLang Daily News の原稿を作成してください。
      
【出力形式】JSON形式で出力

${formattedNews}`
    }]
  });

  // JSONを抽出してパース
  const text = response.content[0].text;
  const jsonMatch = text.match(/```json\n([\s\S]*?)\n```/);
  return JSON.parse(jsonMatch[1]);
}

出力形式

{
  "date": "2026年1月4日",
  "english": {
    "opening": "Hello, and welcome to KeyLang Daily News...",
    "news": [
      {
        "rank": 1,
        "category": "International Politics",
        "categoryIcon": "🌍",
        "headline": "UN Security Council Meets...",
        "body": "The United Nations Security Council convened..."
      }
    ],
    "closing": "That's all for today's world news...",
    "keyPhrases": [
      {
        "phrase": "convene a meeting",
        "meaning": "会議を招集する",
        "example": "The committee will convene a meeting next week.",
        "exampleJp": "委員会は来週会議を招集します。"
      }
    ]
  },
  "japanese": {
    "opening": "こんにちは。KeyLang Daily Newsの時間です...",
    "news": [...]
  }
}

トークン使用量(実測値):

  • Input: 約4,000トークン
  • Output: 約6,000トークン
  • 1回あたりの費用: 約$0.05(約7円)

Step 3: Google Cloud TTSで音声生成

生成された原稿をGoogle Cloud Text-to-Speechで音声化します。

SSML(Speech Synthesis Markup Language)の活用

自然な読み上げのために、SSMLでポーズや強調を制御しています。

scripts/daily-news/03-generate-audio.ts
function buildSingleNewsSSML(item: NewsItem, newsNum: number): string {
  return `<speak>
<p>
  <s>News ${newsNum}. ${item.headline}</s>
  <break time="500ms"/>
  <s>${item.body}</s>
</p>
<break time="800ms"/>
</speak>`;
}

英語音声の設定

学習者向けにやや遅めの読み上げ速度を設定しています。

const VOICE_EN = {
  languageCode: 'en-US',
  name: 'en-US-Neural2-J', // Male, natural voice
};

const AUDIO_CONFIG = {
  audioEncoding: 'MP3',
  speakingRate: 0.95, // やや遅め(学習者向け)
  pitch: 0,
};

セグメント単位の生成

各ニュースを個別のMP3ファイルとして生成し、最後に結合します。これにより、後から「ニュース3だけ再生」といった機能も実装可能です。

// 各ニュースを個別に生成
for (let i = 0; i < english.news.length; i++) {
  const newsFile = path.join(OUTPUT_DIR, `${dateStr}-segment-${i+1}-news.mp3`);
  await synthesizeSpeech(
    buildSingleNewsSSML(english.news[i], i + 1),
    VOICE_EN,
    newsFile
  );
  segments.news.push({ file: newsFile, duration: getAudioDuration(newsFile) });
}

// 全セグメントを結合
await concatenateMP3Files(segmentFiles, finalFile);

生成される音声:

  • メイン音声: 約10分(20ニュース)
  • Key Phrases音声: 約3分(5フレーズ)

Step 4: Supabaseに公開

最後に、生成したコンテンツをSupabaseにアップロードして公開します。

音声ファイルのアップロード

scripts/daily-news/04-publish.ts
async function uploadAudioFiles(script: GeneratedScript) {
  const dateStr = new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Tokyo' });
  
  const fileBuffer = await fs.readFile(audioFilePath);
  
  const { error } = await supabase.storage
    .from('daily-news-audio')
    .upload(`${dateStr}/${filename}`, fileBuffer, {
      contentType: 'audio/mpeg',
      upsert: true,
    });

  // 公開URLを取得
  const { data } = supabase.storage
    .from('daily-news-audio')
    .getPublicUrl(`${dateStr}/${filename}`);
  
  return data.publicUrl;
}

ブログ記事の登録

const blogPost = {
  slug: dateStr, // 例: "2025-01-04"
  title: `KeyLang Daily News - ${script.date}`,
  content: generateBlogContent(script, audioUrls),
  category: 'daily-news',
  published: true,
  metadata: {
    audioUrls,
    newsCount: 20,
    keyPhrasesCount: 5,
  },
};

await supabase
  .from('blog_posts')
  .upsert(blogPost, { onConflict: 'slug' });

GitHub Actions ワークフロー

すべてを自動化するワークフローです。

.github/workflows/daily-news.yml
name: Daily News Generation

on:
  schedule:
    # UTC 21:00 = JST 06:00
    - cron: '0 21 * * *'
  workflow_dispatch: # 手動実行も可能

jobs:
  generate-daily-news:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
      - uses: pnpm/action-setup@v4
      - run: pnpm install

      # Google Cloud認証
      - uses: google-github-actions/auth@v2
        with:
          credentials_json: ${{ secrets.GOOGLE_CLOUD_CREDENTIALS }}

      # 4ステップを順番に実行
      - name: Step 1 - Fetch News
        run: pnpm tsx scripts/daily-news/01-fetch-news.ts

      - name: Step 2 - Generate Script
        run: pnpm tsx scripts/daily-news/02-generate-script.ts
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

      - name: Step 3 - Generate Audio
        run: pnpm tsx scripts/daily-news/03-generate-audio.ts

      - name: Step 4 - Publish
        run: pnpm tsx scripts/daily-news/04-publish.ts
        env:
          NEXT_PUBLIC_SUPABASE_URL: ${{ secrets.NEXT_PUBLIC_SUPABASE_URL }}
          SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.SUPABASE_SERVICE_ROLE_KEY }}

コスト内訳

月額コストの内訳(実績値):

サービス 月額 備考
Claude API ¥200〜400 Sonnet 4, 約7円/日 × 30日
Google Cloud TTS ¥90 Neural2音声, 約3円/日 × 30日
Supabase ¥0 無料枠内(Storage 1GB)
Vercel ¥0 無料枠内
GitHub Actions ¥0 無料枠内(2000分/月)
合計 約¥200〜490

コスト最適化のポイント

  1. Claude Sonnet を使用

    • Opus(最上位モデル)ではなくSonnetで十分な品質
    • 価格は約1/5
  2. Google Cloud TTSのNeural2音声

    • WaveNet(最高品質)より安価
    • 学習用途には十分なクオリティ
  3. Supabaseの無料枠を活用

    • Storage 1GBまで無料
    • 音声ファイルは1日あたり約2MBなので余裕

ハマったポイント

1. タイムゾーンの罠

GitHub Actionsはデフォルトでutc。日本時間での日付を正しく扱うのに苦労しました。

// ❌ これだと UTC の日付になる
const dateStr = new Date().toISOString().split('T')[0];

// ✅ 日本時間で日付を取得
const dateStr = new Date().toLocaleDateString('sv-SE', { timeZone: 'Asia/Tokyo' });

2. Claude APIのレート制限

短時間に大量のリクエストを送るとレート制限に引っかかります。

// リトライロジックを追加
const response = await retry(
  () => anthropic.messages.create({ ... }),
  { retries: 3, delay: 1000 }
);

3. RSS フィードの不安定さ

一部のRSSフィードは頻繁にダウンしたり、形式が変わったりします。

// 各ソースを try-catch で囲む
async function fetchFeed(source: RSSSource): Promise<Article[]> {
  try {
    const feed = await parser.parseURL(source.url);
    return feed.items.map(item => ({ ... }));
  } catch (error) {
    console.error(`Error fetching ${source.name}: ${error.message}`);
    return []; // 失敗しても他のソースは継続
  }
}

4. 音声ファイルの結合

Node.js 単体では MP3 の結合が難しく、ffmpeg を使いました。

// ffmpegで結合
execSync(`ffmpeg -y -f concat -safe 0 -i "${listFile}" -c copy "${outputFile}"`);

実際の生成結果

毎朝生成される記事の一部を紹介します。

英語ニュースの例

🌍 UN Security Council Discusses Middle East Situation

The United Nations Security Council held an emergency meeting to discuss the ongoing situation in the Middle East. Representatives from multiple countries expressed their concerns and called for diplomatic solutions. The council is expected to issue a statement later this week.

Key Phrasesの例

フレーズ 意味 例文
hold an emergency meeting 緊急会議を開く The board will hold an emergency meeting tomorrow.
call for diplomatic solutions 外交的解決を求める Many nations called for diplomatic solutions to the conflict.

まとめ

このシステムで実現できたこと

✅ 完全自動化: 毎朝6時に人手ゼロで記事が公開される
✅ 低コスト: 月500〜700円で運用可能
✅ 中立性: AI + 厳密な編集方針で偏りのないニュースを提供
✅ 学習者向け: 音声速度・語彙レベルを調整

今後の改善予定

  • ユーザーの学習履歴に基づくニュース選定
  • 難易度別の音声速度切り替え

参考リンク


最後まで読んでいただきありがとうございます!

個人開発でAIを活用した自動化システムを作りたい方の参考になれば幸いです。質問やフィードバックがあれば、コメントや X (@keylang_study) でお気軽にどうぞ!

Discussion