Open52

DuckDB + Claude Desktop + MCP で X(Twitter)のアーカイブデータを閲覧する

hagiwarahagiwara

X(Twitter)アーカイブのダウンロード

hagiwarahagiwara

もっと見る > アカウント > データのアーカイブをダウンロード

hagiwarahagiwara

X(Twitter)アーカイブのデータからポストの JSON を抜き出してファイルを作成する

hagiwarahagiwara

データ変換用のスクリプト(Claude 作)

convert-tweet-data.js
const fs = require('fs')
const path = require('path')

/**
 * TwitterアーカイブのJSファイルをJSONに変換する関数
 * @param {string} inputFile - 入力ファイル(.jsファイル)のパス
 * @param {string} outputFile - 出力JSONファイルのパス
 */
function convertTwitterArchiveToJson(inputFile, outputFile) {
  try {
    // ファイルを読み込む
    let fileContent = fs.readFileSync(inputFile, 'utf8')

    // window.YTD.tweet.part0 = [...] の形式から実際のJSONデータを抽出
    // 正規表現を使用して [...] の部分を取得
    const match = fileContent.match(
      /^window\.YTD\.\w+\.part\d+\s*=\s*(\[[\s\S]*\])/
    )

    if (!match || !match[1]) {
      throw new Error('Twitter archiveデータの形式が想定と異なります')
    }

    // JSONデータを取得
    const jsonData = match[1]

    // JSON形式に変換してファイルに書き込む
    fs.writeFileSync(outputFile, jsonData, 'utf8')

    console.log(`変換完了: ${outputFile} にJSONデータを書き込みました`)
    return true
  } catch (error) {
    console.error('エラーが発生しました:', error.message)
    return false
  }
}

// コマンドライン引数からファイルパスを取得
const args = process.argv.slice(2)
if (args.length < 2) {
  console.log(
    '使用方法: node convert-tweet-data.js <入力ファイル> <出力ファイル>'
  )
  console.log(
    '例: node convert-tweet-data.js ./data/tweets.js ./data/tweets.json'
  )
  process.exit(1)
}

const inputFile = args[0]
const outputFile = args[1]

// 変換実行
convertTwitterArchiveToJson(inputFile, outputFile)
hagiwarahagiwara

スクリプトを実行する

node convert-tweet-data.js ./path/to/tweets.js ./path/to/tweets.json
hagiwarahagiwara

DuckDB で JSON ファイルを読み込む

hagiwarahagiwara

DuckDBを起動して新しいデータベースファイルを作成する

duckdb tweet_archive.db
hagiwarahagiwara

JSONデータからテーブルを作成する

CREATE TABLE raw_tweets AS
SELECT * FROM read_json_auto('./path/to/tweets.json');
hagiwarahagiwara

DuckDB Local UI を使ってみる

hagiwarahagiwara
  1. Attatched database にローカルの .db ファイルを読み込む
  2. Notebooks にノートブックを作成する
  3. Add Cell して SQL を入力・実行する
hagiwarahagiwara

MotherDuck MCP Server(mcp-server-motherduck)を Claude Desktop で使ってみる

hagiwarahagiwara

mcp-server-motherduck をインストールする

uv pip install mcp-server-motherduck
hagiwarahagiwara

Claude Desktop の設定ファイルを編集する(Claude for Mac の場合)

  1. 設定 > 開発者 > 構成を編集
  2. Finder で ~/Library/Application Support/Claude/claude_desktop_config.json が表示される
  3. 編集する(↓)
claude_desktop_config.json
{
  "mcpServers": {
    "local-duckdb": {
      "command": "uvx",
      "args": [
        "mcp-server-duckdb",
        "--db-path",
        "/Users/ユーザー名/path/to/database.db"
      ]
    }
  }
}
hagiwarahagiwara

Claude Desktop でデータを閲覧してみる

hagiwarahagiwara

途中でエラー出てた

Database error: Invalid Input Error: Required module 'pytz' failed to import, due to the following Python exception:
ModuleNotFoundError: No module named 'pytz'
hagiwarahagiwara
CREATE VIEW tweets AS
SELECT
  tweet ->> 'id_str'           AS id_str,
  STRPTIME(tweet ->> 'created_at', '%a %b %d %H:%M:%S %z %Y') AS created_at,
  tweet ->> 'full_text'        AS full_text,
  CAST(tweet ->> 'retweet_count' AS INTEGER)    AS retweet_count,
  CAST(tweet ->> 'favorite_count' AS INTEGER)   AS favorite_count,
  tweet ->> 'lang'             AS lang,
  json_extract_string(tweet, '$.entities.user_mentions[0].screen_name') AS mention_screen_name
FROM raw_tweets;

STRPTIME(tweet ->> 'created_at', '%a %b %d %H:%M:%S %z %Y') AS created_at, のところが原因らしい
DuckDB の Local UI で実行したときは問題なかったけど、ローカル環境には pytz がインストールされてなかった模様

hagiwarahagiwara

SQL を都度表示してくれるので、SQL の学習にも使えるかもね

hagiwarahagiwara

きっかけ)

  • DuckDB を知り、試してみたかった
  • MCP 使ってみたかった
  • それなりの分量のまとまったデータとして X(Twitter)のアーカイブがあった
    • X や Twilog の仕様が変わってメモがわりのポストが検索できなくて困ってた