spotify-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Spotify API Skill

Spotify API 技能

Version: 0.9.1 | Release Date: October 22, 2025
版本: 0.9.1 | 发布日期: 2025年10月22日

Overview

概述

This skill directly interacts with the Spotify Web API to manage music and playlists.
此技能可直接与Spotify Web API交互,以管理音乐和播放列表。

⚡ Unique Capability: Image Generation

⚡ 独特功能:图片生成

🎨 This skill can GENERATE IMAGES - something Claude cannot do natively! It creates custom SVG-based cover art for Spotify playlists with large, readable typography optimized for thumbnail viewing. Each cover art is dynamically generated with theme-appropriate colors, gradients, and text layouts.
Use this skill when you need to:
  • 🎨 Generate cover art images - Create custom playlist covers (Claude's built-in image generation limitation is bypassed!)
  • 🎵 Create playlists from artist names, themes, or specific songs
  • 🔍 Search for tracks, artists, albums
  • Add/remove tracks from playlists
  • ▶️ Control playback (play, pause, skip)
  • 📊 Get user data (profile, top tracks, listening history)
When to use this skill: The user wants you to create a playlist, search for music, manage their Spotify account, or generate custom cover art images.
🎨 本技能可生成图片——这是Claude本身无法做到的!它能为Spotify播放列表创建自定义的基于SVG的封面,采用适合缩略图查看的大尺寸易读字体。每个封面都会根据主题动态生成匹配的颜色、渐变和文本布局。
在以下场景中使用本技能:
  • 🎨 生成封面图片 - 创建自定义播放列表封面(绕过Claude内置的图片生成限制!)
  • 🎵 创建播放列表 - 按艺术家、主题或特定歌曲创建
  • 🔍 搜索 - 查找曲目、艺术家、专辑
  • 添加/删除曲目 - 管理播放列表中的曲目
  • ▶️ 控制播放(播放、暂停、切歌)
  • 📊 获取用户数据(个人资料、热门曲目、收听历史)
何时使用本技能:用户需要你创建播放列表、搜索音乐、管理他们的Spotify账户,或生成自定义封面图片时。

Core Capabilities

核心功能

  1. 🎨 Cover Art Image Generation - Generate custom images with SVG → PNG conversion (Claude cannot generate images natively!)
  2. Intelligent Playlist Creation - Create playlists by artist, theme, lyrics, or song list
  3. Playlist Management - Create, list, update, delete playlists
  4. Search & Discovery - Find tracks, artists, albums, playlists
  5. Track Management - Add/remove tracks, get recommendations
  6. Playback Control - Play, pause, skip, control volume
  7. User Library - Access saved tracks, profile, listening history
  1. 🎨 封面图片生成 - 生成自定义图片并完成SVG → PNG转换(Claude本身无法生成图片!)
  2. 智能播放列表创建 - 按艺术家、主题、歌词或歌曲列表创建播放列表
  3. 播放列表管理 - 创建、列出、更新、删除播放列表
  4. 搜索与发现 - 查找曲目、艺术家、专辑、播放列表
  5. 曲目管理 - 添加/删除曲目、获取推荐
  6. 播放控制 - 播放、暂停、切歌、控制音量
  7. 用户库访问 - 访问已保存曲目、个人资料、收听历史

Quick Start

快速开始

All Spotify API operations use the
SpotifyClient
class from
scripts/spotify_client.py
. The client handles OAuth authentication and provides methods for all operations.
所有Spotify API操作均使用
scripts/spotify_client.py
中的
SpotifyClient
类。该客户端处理OAuth认证并提供所有操作的方法。

Prerequisites

前提条件

1. Enable Network Access (REQUIRED)
⚠️ This skill requires network access to reach api.spotify.com
In Claude Desktop, you must enable network egress:
  • Go to SettingsDeveloperAllow network egress
  • Toggle it ON (blue)
  • Under "Domain allowlist", choose either:
    • "All domains" (easiest), OR
    • "Specified domains" and add
      api.spotify.com
      (more secure/restricted)
  • This allows the skill to make API calls to Spotify's servers
Without network access enabled, API calls will fail with connection errors.
2. Install Dependencies
bash
pip install -r requirements.txt
Required packages:
  • requests>=2.31.0
    - HTTP requests for Spotify Web API
  • python-dotenv>=1.0.0
    - Environment variable management
  • cairosvg>=2.7.0
    - SVG to PNG conversion for image generation
  • pillow>=10.0.0
    - Image processing for cover art creation
💡 Note: The
cairosvg
and
pillow
packages enable image generation - allowing this skill to create cover art images even though Claude cannot generate images natively!
1. 启用网络访问(必填)
⚠️ 本技能需要网络访问权限以连接api.spotify.com
在Claude桌面端,你必须启用网络出站访问:
  • 进入设置开发者允许网络出站访问
  • 将其切换为开启(蓝色)
  • 在「域名白名单」中选择:
    • 「所有域名」(最简单),或者
    • **「指定域名」**并添加
      api.spotify.com
      (更安全/受限)
  • 这将允许本技能向Spotify服务器发起API请求
如果未启用网络访问,API请求将因连接错误而失败。
2. 安装依赖
bash
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本身无法生成图片,这两个包也能让本技能创建封面图片!

Basic Setup

基础设置

The easiest way to initialize the client is using credentials from environment variables (loaded from
.env
file):
python
from spotify_client import create_client_from_env
最简单的客户端初始化方式是使用环境变量中的凭证(从
.env
文件加载):
python
from spotify_client import create_client_from_env

Initialize client from environment variables (.env file)

从环境变量(.env文件)初始化客户端

client = create_client_from_env()
client = create_client_from_env()

If you have a refresh token, refresh the access token

如果有刷新令牌,刷新访问令牌

if client.refresh_token: client.refresh_access_token()

Alternatively, you can manually provide credentials:

```python
from spotify_client import SpotifyClient
if client.refresh_token: client.refresh_access_token()

你也可以手动提供凭证:

```python
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 )
client = SpotifyClient( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", redirect_uri="http://localhost:8888/callback", refresh_token="YOUR_REFRESH_TOKEN" # 可选(如果有) )

Refresh to get current access token

刷新以获取当前访问令牌

if client.refresh_token: client.refresh_access_token()
undefined
if client.refresh_token: client.refresh_access_token()
undefined

Common Operations

常见操作

List ALL user playlists (with pagination):
python
undefined
列出所有用户播放列表(支持分页)
python
undefined

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)")

**Create a new playlist:**
```python
playlist = client.create_playlist(
    name="My Awesome Playlist",
    description="A curated collection",
    public=True
)
Search for tracks:
python
results = client.search_tracks(query="artist:The Beatles", limit=20)
Add tracks to playlist:
python
client.add_tracks_to_playlist(
    playlist_id="playlist_123",
    track_ids=["track_1", "track_2", "track_3"]
)
all_playlists = [] offset = 0 limit = 50 # 每次请求的最大数量
while True: playlists = client.get_user_playlists(limit=limit, offset=offset) if not playlists: break # 没有更多播放列表 all_playlists.extend(playlists) offset += limit if len(playlists) < limit: break # 最后一页(返回结果少于限制数量)
print(f"总播放列表数: {len(all_playlists)}") for playlist in all_playlists: print(f"- {playlist['name']} ({playlist['tracks']['total']} 首曲目)")

**创建新播放列表**:
```python
playlist = client.create_playlist(
    name="我的精彩播放列表",
    description="精心挑选的合集",
    public=True
)
搜索曲目
python
results = client.search_tracks(query="artist:The Beatles", limit=20)
向播放列表添加曲目
python
client.add_tracks_to_playlist(
    playlist_id="playlist_123",
    track_ids=["track_1", "track_2", "track_3"]
)

Playlist Management Workflows

播放列表管理工作流

List All User Playlists

列出所有用户播放列表

Important: Users may have more than 50 playlists. Always use pagination to get ALL playlists:
python
undefined
重要提示:用户的播放列表可能超过50个。请务必使用分页来获取所有播放列表:
python
undefined

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)}")
all_playlists = [] offset = 0 limit = 50 # Spotify允许的每次请求最大数量
while True: batch = client.get_user_playlists(limit=limit, offset=offset) if not batch: break # 没有更多播放列表可获取
all_playlists.extend(batch)
print(f"已获取 {len(batch)} 个播放列表(当前总数: {len(all_playlists)})")

offset += limit
if len(batch) < limit:
    break  # 最后一页 - 返回结果少于限制数量表示已完成
print(f"\n✓ 共找到 {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']}")
undefined
for i, playlist in enumerate(all_playlists, 1): print(f"{i}. {playlist['name']}") print(f" 曲目数: {playlist['tracks']['total']}") print(f" 公开状态: {playlist['public']}") print(f" ID: {playlist['id']}")
undefined

Playlist Creation Workflows

播放列表创建工作流

By Artist/Band Name

按艺术家/乐队名称创建

Create a playlist containing all or most popular tracks by a specific artist:
python
undefined
创建包含特定艺术家全部或最热门曲目的播放列表:
python
undefined

STEP 1: Search for the artist by name

步骤1:按名称搜索艺术家

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")
undefined
artists = client.search_artists(query="The Beatles", limit=1) if not artists: print"艺术家未找到" # 处理错误:艺术家不存在或名称拼写错误 else: artist_id = artists[0]['id'] # 获取第一个搜索结果的Spotify ID
# 步骤2:获取艺术家的最热门曲目
# 注意:Spotify API每个艺术家最多返回10首热门曲目
tracks = client.get_artist_top_tracks(artist_id=artist_id)
track_ids = [t['id'] for t in tracks]  # 仅提取曲目ID

# 步骤3:创建新播放列表并添加曲目
playlist = client.create_playlist(name="The Beatles 合集")
client.add_tracks_to_playlist(playlist['id'], track_ids)
print(f"已创建包含 {len(track_ids)} 首曲目的播放列表")
undefined

By Theme/Mood

按主题/情绪创建

Create thematic playlists by searching for tracks matching mood keywords:
python
undefined
通过搜索匹配情绪关键词的曲目创建主题播放列表:
python
undefined

STEP 1: Define search queries for your theme

步骤1:定义主题搜索查询

Spotify search syntax: "genre:indie mood:chill" or "genre:indie year:2020-2024"

Spotify搜索语法:"genre:indie mood:chill" 或 "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 ]
theme_queries = [ "genre:indie mood:chill", # 搜索舒缓的独立音乐 "genre:indie year:2020-2024" # 搜索近年的独立音乐 ]

STEP 2: Search for tracks matching each query

步骤2:搜索每个查询匹配的曲目

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
all_tracks = [] for query in theme_queries: results = client.search_tracks(query=query, limit=50) # 每个查询最多获取50首 all_tracks.extend(results) # 合并所有查询结果

STEP 3: Remove duplicates (same track may match multiple queries)

步骤3:去重(同一曲目可能匹配多个查询)

Use set() with track IDs to keep only unique tracks

使用曲目ID的集合来保留唯一曲目

unique_track_ids = list(set(t['id'] for t in all_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)

步骤4:创建包含唯一曲目的播放列表(限制为100首以保证合理规模)

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")
undefined
playlist = client.create_playlist(name="舒缓独立夜曲") client.add_tracks_to_playlist(playlist['id'], unique_track_ids[:100]) print(f"已创建包含 {len(unique_track_ids[:100])} 首曲目的播放列表")
undefined

By Lyrics Content

按歌词内容创建

Search for tracks with specific lyrical themes using Spotify's search:
python
undefined
使用Spotify的搜索功能查找包含特定歌词主题的曲目:
python
undefined

STEP 1: Define keywords related to lyrical content

步骤1:定义与歌词内容相关的关键词

Note: Spotify search indexes track/artist names and some metadata,

注意:Spotify搜索索引曲目/艺术家名称和部分元数据,

not full lyrics, so results are based on title/description matching

不包含完整歌词,因此结果基于标题/描述匹配

queries = ["love", "heartbreak", "summer", "midnight"]
queries = ["love", "heartbreak", "summer", "midnight"]

STEP 2: Search for tracks matching each keyword

步骤2:搜索每个关键词匹配的曲目

all_tracks = [] for keyword in queries: results = client.search_tracks(query=keyword, limit=20) # 20 tracks per keyword all_tracks.extend(results)
all_tracks = [] for keyword in queries: results = client.search_tracks(query=keyword, limit=20) # 每个关键词最多20首 all_tracks.extend(results)

STEP 3: Remove duplicates (same track may match multiple keywords)

步骤3:去重(同一曲目可能匹配多个关键词)

Use set() with track IDs to keep only unique tracks

使用曲目ID的集合来保留唯一曲目

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")
unique_track_ids = list(set(t['id'] for t in all_tracks)) print(f"共找到 {len(all_tracks)} 个匹配结果,{len(unique_track_ids)} 首唯一曲目")

STEP 4: Create playlist (limit to 100 tracks for reasonable size)

步骤4:创建播放列表(限制为100首以保证合理规模)

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")
undefined
playlist = client.create_playlist(name="爱与心碎") client.add_tracks_to_playlist(playlist['id'], unique_track_ids[:100]) print(f"已创建包含 {len(unique_track_ids[:100])} 首唯一曲目的播放列表")
undefined

From Specific Song List

按特定歌曲列表创建

Create a playlist from a user-provided list of track URIs or search terms:
python
undefined
根据用户提供的曲目URI或搜索词列表创建播放列表:
python
undefined

STEP 1: Get the list of songs from the user

步骤1:获取用户提供的歌曲列表

User provides song names (can also use Spotify URIs like "spotify:track:...")

用户提供歌曲名称(也可以使用Spotify URI,如"spotify:track:...")

song_list = ["Shape of You", "Blinding Lights", "As It Was"]
song_list = ["Shape of You", "Blinding Lights", "As It Was"]

STEP 2: Search for each song and collect track IDs

步骤2:搜索每首歌曲并收集曲目ID

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
track_ids = [] for song_name in song_list: results = client.search_tracks(query=song_name, limit=1) # 获取最佳匹配 if results: track_ids.append(results[0]['id']) # 添加第一个结果的ID print(f"✓ 找到: {results[0]['name']} by {results[0]['artists'][0]['name']}") else: print(f"✗ 未找到: {song_name}") # 歌曲不存在或名称错误

STEP 3: Create playlist with found tracks

步骤3:创建包含找到的曲目的播放列表

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")
undefined
playlist = client.create_playlist(name="我的最爱") if track_ids: client.add_tracks_to_playlist(playlist['id'], track_ids) print(f"已创建包含 {len(track_ids)}/{len(song_list)} 首曲目的播放列表") else: print"未找到任何曲目 - 播放列表为空"
undefined

🎨 Cover Art Image Generation

🎨 封面图片生成

⚡ UNIQUE CAPABILITY: This skill can generate images!
Claude cannot generate images natively, but this skill bypasses that limitation by creating custom SVG graphics and converting them to PNG images for Spotify playlist covers.
🚨 MANDATORY: USE THE COVER ART LLM GUIDE
⚠️ DO NOT attempt to generate cover art without first reading the complete execution guide.
➡️ READ THIS FILE FIRST: references/COVER_ART_LLM_GUIDE.md
This guide is REQUIRED and contains:
  • Complete step-by-step execution instructions
  • How to analyze playlist content to determine appropriate colors
  • Genre-to-color and mood-to-color mapping tables
  • Typography rules and accessibility requirements
  • Edge case handling and quality checklist
Do not proceed with cover art generation without consulting this guide first.
⚡ 独特功能:本技能可生成图片!
Claude本身无法生成图片,但本技能通过创建自定义SVG图形并将其转换为PNG图片,绕过了这一限制,可用于Spotify播放列表封面。
🚨 强制要求:使用封面艺术LLM指南
⚠️ 在未阅读完整执行指南前,请勿尝试生成封面。
➡️ 请先阅读此文件:references/COVER_ART_LLM_GUIDE.md
本指南是必填的,包含:
  • 完整的分步执行说明
  • 如何分析播放列表内容以确定合适的颜色
  • 流派-颜色和情绪-颜色映射表
  • 排版规则和可访问性要求
  • 边缘情况处理和质量检查清单
在未查阅本指南前,请勿进行封面生成操作。

⚠️ Required Scope for Upload

⚠️ 上传所需的权限范围

To upload cover art to Spotify, you MUST have the
ugc-image-upload
scope enabled:
  1. Go to Spotify Developer Dashboard
  2. Select your app
  3. Ensure
    ugc-image-upload
    scope is included in your authorization
  4. Re-run OAuth flow to get a new refresh token with this scope:
    python get_refresh_token.py
  5. Update your
    .env
    file with the new refresh token
Without this scope: You'll get a 401 error when trying to upload. However, you can still generate cover art images locally and upload them manually via Spotify's web/mobile app.
📖 Having trouble? See COVER_ART_TROUBLESHOOTING.md for detailed solutions.
要将封面上传到Spotify,你必须启用
ugc-image-upload
权限范围:
  1. 访问Spotify开发者控制台
  2. 选择你的应用
  3. 确保授权中包含
    ugc-image-upload
    权限范围
  4. 重新运行OAuth流程以获取包含此权限的新刷新令牌:
    python get_refresh_token.py
  5. 使用新的刷新令牌更新你的
    .env
    文件
如果没有此权限:上传时会收到401错误。不过你仍然可以在本地生成封面图片,然后通过Spotify网页/移动应用手动上传。
📖 遇到问题? 请查看COVER_ART_TROUBLESHOOTING.md获取详细解决方案。

Basic Usage Example

基础使用示例

⚠️ Remember: Read references/COVER_ART_LLM_GUIDE.md before generating cover art!
python
from cover_art_generator import CoverArtGenerator
⚠️ 请记住:在生成封面前,请先阅读references/COVER_ART_LLM_GUIDE.md
python
from cover_art_generator import CoverArtGenerator

Initialize generator (uses same credentials as SpotifyClient)

初始化生成器(使用与SpotifyClient相同的凭证)

art_gen = CoverArtGenerator(client_id, client_secret, access_token)
art_gen = CoverArtGenerator(client_id, client_secret, access_token)

Generate and upload cover art

生成并上传封面

(Follow the LLM guide for how to determine appropriate colors)

(请遵循LLM指南确定合适的颜色)

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" )

**All cover art generation workflows, color selection guidance, and advanced features are documented in [references/COVER_ART_LLM_GUIDE.md](references/COVER_ART_LLM_GUIDE.md).**
art_gen.create_and_upload_cover( playlist_id=playlist['id'], title="Beast Mode", # 主标题(大字体) subtitle="Gym", # 可选副标题 gradient_start="#E63946", # 根据指南确定的颜色 gradient_end="#1D1D1D", text_color="#FFFFFF" )

**所有封面生成工作流、颜色选择指南和高级功能均记录在[references/COVER_ART_LLM_GUIDE.md](references/COVER_ART_LLM_GUIDE.md)中。**

Advanced Operations

高级操作

Get Recommendations

获取推荐

python
undefined
python
undefined

Get AI-powered music recommendations based on seed artists/tracks/genres

根据种子艺术家/曲目/流派获取AI驱动的音乐推荐

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 )
recommendations = client.get_recommendations( seed_artists=["artist_id_1"], # 艺术家的Spotify ID seed_tracks=["track_id_1"], # 曲目的Spotify ID limit=50 # 要获取的推荐数量 )

Returns: List of recommended tracks similar to the seeds

返回值:与种子内容相似的推荐曲目列表

undefined
undefined

Access User Profile

访问用户个人资料

python
undefined
python
undefined

Get information about the current authenticated user

获取当前已认证用户的信息

profile = client.get_current_user()
profile = client.get_current_user()

Returns: user_id, display_name, email, followers, images, country, etc.

返回值:user_id、display_name、email、粉丝数、头像、国家等

print(f"Logged in as: {profile['display_name']}") print(f"User ID: {profile['id']}")
undefined
print(f"当前登录用户: {profile['display_name']}") print(f"用户ID: {profile['id']}")
undefined

Get User's Top Items

获取用户的热门内容

python
undefined
python
undefined

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']}")
top_artists = client.get_top_items( item_type="artists", limit=20, time_range="medium_term" # 选项:short_term(约4周)、medium_term(约6个月)、long_term(约数年) ) print(f"最受欢迎艺术家: {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']}")
undefined
top_tracks = client.get_top_items( item_type="tracks", limit=20, time_range="short_term" # 近期收听(过去约4周) ) print(f"最常播放曲目: {top_tracks[0]['name']} by {top_tracks[0]['artists'][0]['name']}")
undefined

Playback Control

播放控制

python
undefined
python
undefined

STEP 1: Start playback of a playlist or album

步骤1:开始播放播放列表或专辑

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 )
client.start_playback( device_id="device_123", # 可选:指定设备 context_uri="spotify:playlist:playlist_id", # 要播放的内容(播放列表/专辑/艺术家URI) offset=0 # 可选:从第0首开始播放 )

STEP 2: Pause playback

步骤2:暂停播放

client.pause_playback(device_id="device_123")
client.pause_playback(device_id="device_123")

STEP 3: Skip to next track

步骤3:跳至下一曲目

client.next_track(device_id="device_123")
client.next_track(device_id="device_123")

STEP 4: Check what's currently playing

步骤4:查看当前正在播放的内容

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")
undefined
current = client.get_currently_playing() if current and current.get('item'): track = current['item'] print(f"当前播放: {track['name']} by {track['artists'][0]['name']}") else: print"当前没有播放内容"
undefined

Authentication & Credentials

认证与凭证

See
references/authentication_guide.md
for detailed OAuth flow setup and credential management. Ensure credentials are available in environment variables or passed at initialization:
  • SPOTIFY_CLIENT_ID
  • SPOTIFY_CLIENT_SECRET
  • SPOTIFY_REDIRECT_URI
  • SPOTIFY_ACCESS_TOKEN
    (optional, can use refresh token)
  • SPOTIFY_REFRESH_TOKEN
    (for token refresh)
请查看
references/authentication_guide.md
获取详细的OAuth流程设置和凭证管理说明。确保凭证可从环境变量获取或在初始化时传入:
  • SPOTIFY_CLIENT_ID
  • SPOTIFY_CLIENT_SECRET
  • SPOTIFY_REDIRECT_URI
  • SPOTIFY_ACCESS_TOKEN
    (可选,可使用刷新令牌)
  • SPOTIFY_REFRESH_TOKEN
    (用于令牌刷新)

API Reference

API参考

See
references/api_reference.md
for complete Spotify API endpoint documentation, rate limits, response formats, and error handling patterns.
请查看
references/api_reference.md
获取完整的Spotify API端点文档、速率限制、响应格式和错误处理模式。

Scripts

脚本说明

spotify_client.py

spotify_client.py

Comprehensive Python wrapper for all Spotify Web API operations. Handles authentication, token management, rate limiting, and provides methods for:
  • Authentication and token refresh
  • Playlist CRUD operations
  • Search (tracks, artists, albums, playlists)
  • Track/URI management
  • User data access
  • Playback control
  • Recommendations engine
Spotify Web API的全面Python封装。处理认证、令牌管理、速率限制,并提供以下方法:
  • 认证和令牌刷新
  • 播放列表CRUD操作
  • 搜索(曲目、艺术家、专辑、播放列表)
  • 曲目/URI管理
  • 用户数据访问
  • 播放控制
  • 推荐引擎

playlist_creator.py

playlist_creator.py

High-level utility for intelligent playlist creation from various sources (artist, theme, lyrics, song list). Encapsulates common workflows and handles track deduplication and limit management.

用于从各种来源(艺术家、主题、歌词、歌曲列表)智能创建播放列表的高级工具。封装了常见工作流并处理曲目去重和数量限制。

For Developers Building Apps (Advanced)

面向开发应用的开发者(高级)

Note: The features below are for developers building web applications, NOT for direct playlist creation tasks.
If the user is asking you to build an application or export data, see:
  • ADVANCED_USAGE.md
    - Application development patterns
  • scripts/export_data.py
    - Export Spotify data as JSON
  • SpotifyAPIWrapper
    class - Error handling for production apps
For playlist creation and music management, use the workflows above.
注意:以下功能适用于开发Web应用的开发者,不适用于直接的播放列表创建任务
如果用户要求你构建应用导出数据,请查看:
  • ADVANCED_USAGE.md
    - 应用开发模式
  • scripts/export_data.py
    - 将Spotify数据导出为JSON
  • SpotifyAPIWrapper
    类 - 生产应用的错误处理
播放列表创建和音乐管理请使用上述工作流。