mcpField
S
spotify-api

spotify-api

github.com/fabioc-alohaクリエイティブ・メディア18129 回インストール52 週間前に更新
リポジトリ

spotify-api について

spotify-apiは、Spotify Web APIで音楽やプレイリスト、再生を操作するスキルです。SVGのカバー画像を生成し、PNGに変換する機能も備えています。

主な機能

  1. 01プレイリスト用カバー画像の生成
  2. 02アーティスト、テーマ、曲からのプレイリスト作成
  3. 03曲、アーティスト、アルバム、プレイリストの検索
  4. 04プレイリストと収録曲の管理
  5. 05再生操作とユーザーデータへのアクセス

活用シーン

  1. 01アーティストやムードに沿ったプレイリスト作成
  2. 02曲の検索とプレイリストへの追加
  3. 03独自のプレイリスト画像の生成とアップロード

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/fabioc-aloha/spotify-skill --skill spotify-api

インストール後、Claude Code で/spotify-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

.env.example
ADVANCED_USAGE.md
COVER_ART_TROUBLESHOOTING.md
requirements.txt
references/
api_reference.md
authentication_guide.md
COVER_ART_LLM_GUIDE.md
scripts/
cover_art_generator.py
export_data.py
playlist_creator.py
spotify_client.py
test_credentials.py

詳細

Spotify API スキル

バージョン: 0.9.1 | リリース日: 2025年10月22日

概要

このスキルは Spotify Web API を直接操作し、音楽やプレイリストを管理します。

⚡ 独自の機能:画像生成

🎨 このスキルは画像を生成できます ― Claude には標準機能として備わっていない機能です!サムネイルでの表示に最適化された、大きく読みやすいタイポグラフィを使った、Spotify プレイリスト向けのカスタム SVG ベースのカバーアートを作成します。テーマに合った色、グラデーション、テキストレイアウトを使い、カバーアートを動的に生成します。

次のような場合にこのスキルを使用してください。

  • 🎨 カバーアート画像を生成する ― カスタムのプレイリストカバーを作成します(Claude に組み込まれた画像生成の制限を回避できます!)
  • 🎵 アーティスト名、テーマ、または特定の曲からプレイリストを作成する
  • 🔍 トラック、アーティスト、アルバムを検索する
  • ➕ プレイリストのトラックを追加/削除する
  • ▶️ 再生を操作する(再生、一時停止、スキップ)
  • 📊 ユーザーデータを取得する(プロフィール、トップトラック、再生履歴)

このスキルを使用する場面: ユーザーがプレイリストの作成、音楽の検索、Spotify アカウントの管理、またはカスタムカバーアート画像の生成を希望している場合です。

主な機能

  1. 🎨 カバーアート画像の生成 - SVG → PNG 変換でカスタム画像を生成します(Claude には標準の画像生成機能がありません!)
  2. インテリジェントなプレイリスト作成 - アーティスト、テーマ、歌詞、または曲のリストからプレイリストを作成します
  3. プレイリスト管理 - プレイリストの作成、一覧表示、更新、削除
  4. 検索と発見 - トラック、アーティスト、アルバム、プレイリストを検索します
  5. トラック管理 - トラックの追加/削除、レコメンデーションの取得
  6. 再生操作 - 再生、一時停止、スキップ、音量の調整
  7. ユーザーライブラリ - 保存済みトラック、プロフィール、再生履歴にアクセスします

クイックスタート

Spotify API のすべての操作には、scripts/spotify_client.py の SpotifyClient クラスを使用します。このクライアントは OAuth 認証を処理し、すべての操作に対応するメソッドを提供します。

前提条件

1. ネットワークアクセスを有効にする(必須)

⚠️ このスキルは api.spotify.com にアクセスするためにネットワーク接続が必要です

Claude Desktop では、ネットワークの外向き通信を有効にする必要があります。

  • Settings → Developer → Allow network egress に移動します
  • ON(青色)に切り替えます
  • 「Domain allowlist」で、次のいずれかを選択します。
    • 「All domains」(最も簡単)、または
    • **「Specified domains」**を選択し、api.spotify.com を追加します(より安全で制限された設定)
  • これにより、このスキルが Spotify のサーバーに API 呼び出しを行えるようになります

ネットワークアクセスが有効でない場合、API 呼び出しは接続エラーで失敗します。

2. 依存関係をインストールする

pip install -r requirements.txt

必要なパッケージ:

  • requests>=2.31.0 - Spotify Web API への HTTP リクエスト
  • python-dotenv>=1.0.0 - 環境変数の管理
  • cairosvg>=2.7.0 - 画像生成のための SVG から PNG への変換
  • pillow>=10.0.0 - カバーアート作成のための画像処理

💡 注: cairosvg と pillow のパッケージにより、画像を生成できるようになります。Claude には標準の画像生成機能がありませんが、このスキルではカバーアート画像を作成できます!

基本設定

クライアントを初期化する最も簡単な方法は、環境変数(.env ファイルから読み込み)に設定した認証情報を使用することです。

from spotify_client import create_client_from_env

# Initialize client from environment variables (.env file)
client = create_client_from_env()

# If you have a refresh token, refresh the access token
if client.refresh_token:
    client.refresh_access_token()

または、認証情報を手動で指定することもできます。

from spotify_client import SpotifyClient

# Initialize with credentials directly
client = SpotifyClient(
    client_id="YOUR_CLIENT_ID",
    client_secret="YOUR_CLIENT_SECRET",
    redirect_uri="http://localhost:8888/callback",
    refresh_token="YOUR_REFRESH_TOKEN"  # if available
)

# Refresh to get current access token
if client.refresh_token:
    client.refresh_access_token()
よく使う操作

ユーザーのプレイリストをすべて一覧表示する(ページネーション対応):

# Get all playlists - handles pagination automatically
all_playlists = []
offset = 0
limit = 50  # Max allowed per request

while True:
    playlists = client.get_user_playlists(limit=limit, offset=offset)
    if not playlists:
        break  # No more playlists
    all_playlists.extend(playlists)
    offset += limit
    if len(playlists) < limit:
        break  # Last page (fewer than limit returned)

print(f"Total playlists: {len(all_playlists)}")
for playlist in all_playlists:
    print(f"- {playlist['name']} ({playlist['tracks']['total']} tracks)")

新しいプレイリストを作成する:

playlist = client.create_playlist(
    name="My Awesome Playlist",
    description="A curated collection",
    public=True
)

トラックを検索する:

results = client.search_tracks(query="artist:The Beatles", limit=20)

プレイリストにトラックを追加する:

client.add_tracks_to_playlist(
    playlist_id="playlist_123",
    track_ids=["track_1", "track_2", "track_3"]
)

プレイリスト管理のワークフロー

ユーザーのプレイリストをすべて一覧表示する

重要: ユーザーが50件を超えるプレイリストを持っている場合があります。すべてのプレイリストを取得するには、必ずページネーションを使用してください。

# Get ALL playlists using pagination
all_playlists = []
offset = 0
limit = 50  # Spotify's max per request

while True:
    batch = client.get_user_playlists(limit=limit, offset=offset)
    if not batch:
        break  # No more playlists to fetch

    all_playlists.extend(batch)
    print(f"Fetched {len(batch)} playlists (total so far: {len(all_playlists)})")

    offset += limit
    if len(batch) < limit:
        break  # Last page - fewer results than limit means we're done

print(f"\n✓ Total playlists found: {len(all_playlists)}")

# Display all playlists with details
for i, playlist in enumerate(all_playlists, 1):
    print(f"{i}. {playlist['name']}")
    print(f"   Tracks: {playlist['tracks']['total']}")
    print(f"   Public: {playlist['public']}")
    print(f"   ID: {playlist['id']}")

プレイリスト作成のワークフロー

アーティスト/バンド名から作成する

特定のアーティストのすべて、または人気の高いトラックの大部分を含むプレイリストを作成します。

# STEP 1: Search for the artist by name
artists = client.search_artists(query="The Beatles", limit=1)
if not artists:
    print("Artist not found")
    # Handle error: artist doesn't exist or name is misspelled
else:
    artist_id = artists[0]['id']  # Get Spotify ID of first result

    # STEP 2: Get the artist's most popular tracks
    # Note: Spotify API returns up to 10 top tracks per artist
    tracks = client.get_artist_top_tracks(artist_id=artist_id)
    track_ids = [t['id'] for t in tracks]  # Extract just the track IDs

    # STEP 3: Create a new playlist and add the tracks
    playlist = client.create_playlist(name="The Beatles Collection")
    client.add_tracks_to_playlist(playlist['id'], track_ids)
    print(f"Created playlist with {len(track_ids)} tracks")
テーマ/ムードから作成する

ムードを表すキーワードに一致するトラックを検索し、テーマに沿ったプレイリストを作成します。

# STEP 1: Define search queries for your theme
# Spotify search syntax: "genre:indie mood:chill" or "genre:indie year:2020-2024"
theme_queries = [
    "genre:indie mood:chill",      # Search for chill indie tracks
    "genre:indie year:2020-2024"   # Search for recent indie tracks
]

# STEP 2: Search for tracks matching each query
all_tracks = []
for query in theme_queries:
    results = client.search_tracks(query=query, limit=50)  # Get up to 50 per query
    all_tracks.extend(results)  # Combine results from all queries

# STEP 3: Remove duplicates (same track may match multiple queries)
# Use set() with track IDs to keep only unique tracks
unique_track_ids = list(set(t['id'] for t in all_tracks))

# STEP 4: Create playlist with unique tracks (limit to 100 for reasonable size)
playlist = client.create_playlist(name="Chill Indie Evening")
client.add_tracks_to_playlist(playlist['id'], unique_track_ids[:100])
print(f"Created playlist with {len(unique_track_ids[:100])} tracks")
歌詞の内容から作成する

Spotify の検索機能を使用して、特定の歌詞のテーマに合うトラックを検索します。

# STEP 1: Define keywords related to lyrical content
# Note: Spotify search indexes track/artist names and some metadata,
# not full lyrics, so results are based on title/description matching
queries = ["love", "heartbreak", "summer", "midnight"]

# STEP 2: Search for tracks matching each keyword
all_tracks = []
for keyword in queries:
    results = client.search_tracks(query=keyword, limit=20)  # 20 tracks per keyword
    all_tracks.extend(results)

# STEP 3: Remove duplicates (same track may match multiple keywords)
# Use set() with track IDs to keep only unique tracks
unique_track_ids = list(set(t['id'] for t in all_tracks))
print(f"Found {len(all_tracks)} total matches, {len(unique_track_ids)} unique tracks")

# STEP 4: Create playlist (limit to 100 tracks for reasonable size)
playlist = client.create_playlist(name="Love & Heartbreak")
client.add_tracks_to_playlist(playlist['id'], unique_track_ids[:100])
print(f"Created playlist with {len(unique_track_ids[:100])} unique tracks")
特定の曲のリストから作成する

ユーザーが指定したトラック URI または検索語句のリストから、プレイリストを作成します。

# STEP 1: Get the list of songs from the user
# User provides song names (can also use Spotify URIs like "spotify:track:...")
song_list = ["Shape of You", "Blinding Lights", "As It Was"]

# STEP 2: Search for each song and collect track IDs
track_ids = []
for song_name in song_list:
    results = client.search_tracks(query=song_name, limit=1)  # Get best match
    if results:
        track_ids.append(results[0]['id'])  # Add first result's ID
        print(f"✓ Found: {results[0]['name']} by {results[0]['artists'][0]['name']}")
    else:
        print(f"✗ Not found: {song_name}")  # Song doesn't exist or name is wrong

# STEP 3: Create playlist with found tracks
playlist = client.create_playlist(name="My Favorites")
if track_ids:
    client.add_tracks_to_playlist(playlist['id'], track_ids)
    print(f"Created playlist with {len(track_ids)}/{len(song_list)} tracks")
else:
    print("No tracks found - playlist is empty")

🎨 カバーアート画像の生成

⚡ 独自の機能:画像を生成できます!

Claude は標準では画像を生成できませんが、このスキルではカスタム SVG グラフィックを作成して PNG 画像に変換することで、その制限を回避し、Spotify プレイリストのカバーを作成します。

🚨 必須:カバーアート LLM ガイドを使用してください

⚠️ 完全な実行ガイドを先に読まずに、カバーアートを生成しようとしないでください。

➡️ まずこのファイルを読んでください:references/COVER_ART_LLM_GUIDE.md

このガイドは必須で、以下の内容が記載されています:

  • 手順を網羅した実行方法
  • プレイリストの内容を分析し、適切な色を判断する方法
  • ジャンルから色、ムードから色への対応表
  • タイポグラフィのルールとアクセシビリティ要件
  • エッジケースへの対処方法と品質チェックリスト

このガイドを確認せずに、カバーアートの生成を進めないでください。

⚠️ アップロードに必要なスコープ

カバーアートを Spotify にアップロードするには、ugc-image-upload スコープを有効にする必要があります:

  1. Spotify Developer Dashboard にアクセスします
  2. アプリを選択します
  3. 認可に ugc-image-upload スコープが含まれていることを確認します
  4. このスコープを含む新しいリフレッシュトークンを取得するため、OAuth フローを再実行します:python get_refresh_token.py
  5. .env ファイルのリフレッシュトークンを更新します

このスコープがない場合: アップロード時に 401 エラーが発生します。ただし、カバーアート画像をローカルで生成し、Spotify のウェブアプリまたはモバイルアプリから手動でアップロードすることはできます。

📖 お困りですか? 詳しい解決方法は COVER_ART_TROUBLESHOOTING.md をご覧ください。

基本的な使用例

⚠️ カバーアートを生成する前に、references/COVER_ART_LLM_GUIDE.md を読むことを忘れないでください!

from cover_art_generator import CoverArtGenerator

# Initialize generator (uses same credentials as SpotifyClient)
art_gen = CoverArtGenerator(client_id, client_secret, access_token)

# Generate and upload cover art
# (Follow the LLM guide for how to determine appropriate colors)
art_gen.create_and_upload_cover(
    playlist_id=playlist['id'],
    title="Beast Mode",           # Main title (large text)
    subtitle="Gym",                # Optional subtitle
    gradient_start="#E63946",      # Colors determined from guide
    gradient_end="#1D1D1D",
    text_color="#FFFFFF"
)

カバーアートの生成ワークフロー、色選びのガイダンス、高度な機能については、すべて references/COVER_ART_LLM_GUIDE.md に記載されています。

高度な操作

おすすめを取得する
# Get AI-powered music recommendations based on seed artists/tracks/genres
recommendations = client.get_recommendations(
    seed_artists=["artist_id_1"],  # Spotify IDs of artists
    seed_tracks=["track_id_1"],    # Spotify IDs of tracks
    limit=50                       # Number of recommendations to get
)
# Returns: List of recommended tracks similar to the seeds
ユーザープロフィールにアクセスする
# Get information about the current authenticated user
profile = client.get_current_user()
# Returns: user_id, display_name, email, followers, images, country, etc.
print(f"Logged in as: {profile['display_name']}")
print(f"User ID: {profile['id']}")
ユーザーの人気アイテムを取得する
# Get user's most played artists over different time periods
top_artists = client.get_top_items(
    item_type="artists",
    limit=20,
    time_range="medium_term"  # Options: short_term (~4 weeks), medium_term (~6 months), long_term (~years)
)
print(f"Top artist: {top_artists[0]['name']}")

# Get user's most played tracks
top_tracks = client.get_top_items(
    item_type="tracks",
    limit=20,
    time_range="short_term"  # Recent listening (last ~4 weeks)
)
print(f"Most played track: {top_tracks[0]['name']} by {top_tracks[0]['artists'][0]['name']}")
再生コントロール
# STEP 1: Start playback of a playlist or album
client.start_playback(
    device_id="device_123",                      # Optional: specific device
    context_uri="spotify:playlist:playlist_id",  # What to play (playlist/album/artist URI)
    offset=0                                     # Optional: start at track 0
)

# STEP 2: Pause playback
client.pause_playback(device_id="device_123")

# STEP 3: Skip to next track
client.next_track(device_id="device_123")

# STEP 4: Check what's currently playing
current = client.get_currently_playing()
if current and current.get('item'):
    track = current['item']
    print(f"Now playing: {track['name']} by {track['artists'][0]['name']}")
else:
    print("Nothing is currently playing")

認証と認証情報

OAuth フローの設定と認証情報の管理については、references/authentication_guide.md をご覧ください。認証情報が環境変数として利用可能であるか、初期化時に渡されることを確認してください:

  • SPOTIFY_CLIENT_ID
  • SPOTIFY_CLIENT_SECRET
  • SPOTIFY_REDIRECT_URI
  • SPOTIFY_ACCESS_TOKEN(任意。リフレッシュトークンを使用できます)
  • SPOTIFY_REFRESH_TOKEN(トークンの更新用)

API リファレンス

Spotify API エンドポイントの完全なドキュメント、レート制限、レスポンス形式、エラー処理のパターンについては、references/api_reference.md をご覧ください。

スクリプト

spotify_client.py

Spotify Web API のすべての操作に対応した包括的な Python ラッパーです。認証、トークン管理、レート制限を処理し、以下のメソッドを提供します:

  • 認証とトークンの更新
  • プレイリストの CRUD 操作
  • 検索(トラック、アーティスト、アルバム、プレイリスト)
  • トラック/URI の管理
  • ユーザーデータへのアクセス
  • 再生コントロール
  • おすすめエンジン
playlist_creator.py

さまざまな入力元(アーティスト、テーマ、歌詞、曲リスト)からプレイリストをインテリジェントに作成するための高水準ユーティリティです。一般的なワークフローをまとめ、トラックの重複排除と件数制限の管理を行います。


アプリを開発する開発者向け(上級)

注: 以下の機能はウェブアプリケーションを開発する開発者向けであり、プレイリストを直接作成するタスク向けではありません。

ユーザーからアプリケーションの構築またはデータのエクスポートを依頼された場合は、以下をご覧ください:

  • ADVANCED_USAGE.md - アプリケーション開発のパターン
  • scripts/export_data.py - Spotify データを JSON としてエクスポート
  • SpotifyAPIWrapper クラス - 本番アプリ向けのエラー処理

プレイリストの作成と音楽の管理には、上記のワークフローを使用してください。

コメント