| name | spoticlaw |
| description | Spotify Web API client for Nyx agents. Use when interacting with Spotify: search, playback, playlists, library, tracks, artists, albums, shows, podcasts. Requires SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI, and a local .spotify_cache token file. |
| homepage | https://github.com/ledzgio/spoticlaw |
| metadata | {"clawdbot":{"emoji":"🎵","requires":{"env":["SPOTIFY_CLIENT_ID","SPOTIFY_CLIENT_SECRET","SPOTIFY_REDIRECT_URI"],"files":[".spotify_cache"]},"primaryEnv":"SPOTIFY_CLIENT_ID"}} |
Spoticlaw - Spotify Web API Client
A lightweight Spotify Web API client using direct HTTP requests. No Spotipy dependency.
Quick Start
pip install requests python-dotenv
import sys
sys.path.insert(0, "skills/spoticlaw/scripts")
from spoticlaw import player, search, playlists, library
results = search().query("coldplay", types=["track"], limit=10)
player().play(uris=["spotify:track:..."])
playlists().create("My Playlist")
playlists().add_items("playlist_id", ["spotify:track:..."])
library().save(["spotify:track:..."])
Or run from the scripts directory:
cd skills/spoticlaw/scripts
python -c "from spoticlaw import player; player().play(...)"
Required Configuration
Required env vars in agent runtime:
SPOTIFY_CLIENT_ID
SPOTIFY_CLIENT_SECRET
SPOTIFY_REDIRECT_URI (recommended: http://127.0.0.1:8888/callback)
Required file:
.spotify_cache (OAuth token cache)
Authentication
Security Note: Tokens never pass through the AI model. Authentication is done locally, and the token file is copied manually to the agent.
Setup
- Create a Spotify app at https://developer.spotify.com/dashboard
- Get
CLIENT_ID and CLIENT_SECRET
- Add
http://127.0.0.1:8888/callback as Redirect URI
- Create
.env file in your LOCAL machine:
SPOTIFY_CLIENT_ID=your_client_id
SPOTIFY_CLIENT_SECRET=your_client_secret
SPOTIFY_REDIRECT_URI=http://127.0.0.1:8888/callback
- Run authentication on your LOCAL machine:
cd skills/spoticlaw/scripts
pip install -r requirements.txt
python auth.py
-
Open the displayed URL in your browser, authorize
-
Copy the token file to your agent:
cp .spotify_cache /path/to/agent/skills/spoticlaw/.spotify_cache
scp .spotify_cache user@agent:/path/to/skills/spoticlaw/.spotify_cache
That's it! No token ever touches the AI. The agent just reads the file.
Token Auto-Refresh
The library automatically handles token refresh only if the agent has the same app credentials in .env:
- Access token expires after ~1 hour
- On first API call after expiry, it uses
refresh_token + client credentials to request a new access token
- Requires
SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET in the agent environment
- If
.spotify_cache exists but .env is missing/mismatched, refresh fails (invalid_client)
- If you get an error, run
python auth.py locally again and copy updated .spotify_cache
For more on Spotify's OAuth flow, see: https://developer.spotify.com/documentation/web-api/tutorials/code-flow
Required Scopes
The auth.py script requests these scopes:
user-read-playback-state - Read playback state
user-modify-playback-state - Control playback
playlist-read-private - Read private playlists
playlist-modify-public - Modify public playlists
playlist-modify-private - Modify private playlists
user-library-read - Read user library
user-library-modify - Modify user library
user-read-recently-played - Recently played tracks
user-top-read - Top tracks/artists
user-follow-read - Followed artists
Primitives
Important: Add the module path and install deps first:
pip install requests python-dotenv
import sys
sys.path.insert(0, "skills/spoticlaw/scripts")
User
from spoticlaw import user
user().me()
Returns: {id, display_name, email, country, ...}
Search
from spoticlaw import search
search().query("song name", types=["track"], limit=10)
search().query("artist name", types=["artist"], limit=10)
search().query("coldplay", types=["track", "artist", "album"], limit=10)
Parameters:
q: Search query string
types: List of types: track, artist, album, playlist, show, episode, audiobook
limit: Max 10 results (Spotify limit)
offset: Pagination offset
Tracks
from spoticlaw import tracks
tracks().get("track_id")
tracks().get_multiple(["id1", "id2"])
Returns track metadata: {name, artists, album, duration_ms, uri, ...}
Artists
from spoticlaw import artists
artists().get("artist_id")
artists().get_albums("artist_id", limit=10)
Album filters (include_groups):
album, single, compilation, appears_on
Albums
from spoticlaw import albums
albums().get("album_id")
albums().get_tracks("album_id")
Shows (Podcasts)
from spoticlaw import shows
shows().get("show_id")
shows().get_episodes("show_id", limit=10)
Episodes
from spoticlaw import episodes
episodes().get("episode_id")
Playlists
from spoticlaw import playlists, user_playlists
user_playlists().get(limit=50)
playlists().get("playlist_id")
playlists().get_items("playlist_id", limit=50)
playlists().create(name="My Playlist", description="...", public=False)
playlists().update("playlist_id", name="New Name")
playlists().add_items("playlist_id", ["spotify:track:...", "spotify:track:..."])
playlists().remove_items("playlist_id", ["spotify:track:..."])
playlists().delete("playlist_id")
Library
from spoticlaw import library
library().save(["spotify:track:..."])
library().remove(["spotify:track:..."])
library().check(["spotify:track:..."])
Player
from spoticlaw import player
player().get_playback_state()
player().get_currently_playing()
player().get_devices()
player().transfer("device_id", play=True)
player().play(uris=["spotify:track:..."])
player().play(context_uri="spotify:album:...")
player().pause()
player().next()
player().previous()
player().seek(60000)
player().set_volume(80)
player().add_to_queue("spotify:track:...")
player().get_queue()
player().set_shuffle(True)
player().set_repeat("off")
player().get_recently_played(limit=50)
Personalisation
from spoticlaw import personalisation
personalisation().get_top("tracks", time_range="medium_term", limit=20)
personalisation().get_top("artists", time_range="long_term", limit=20)
Follow
from spoticlaw import follow
follow().get_followed(limit=50)
Composite Workflows
The primitives can be mixed and matched to create powerful automations. Here are practical examples:
Workflow 1: Play a Specific Song
from spoticlaw import search, player
results = search().query("stairway to heaven", types=["track"], limit=5)
song = results["tracks"]["items"][0]
song_uri = song["uri"]
print(f"Playing: {song['name']} by {song['artists'][0]['name']}")
player().play(uris=[song_uri])
Workflow 2: Create Playlist from Search Results
from spoticlaw import search, playlists
results = search().query("led zeppelin", types=["track"], limit=10)
track_uris = [t["uri"] for t in results["tracks"]["items"][:5]]
pl = playlists().create("Led Zeppelin Mix", public=False)
playlist_id = pl["id"]
playlists().add_items(playlist_id, track_uris)
print(f"Created playlist: {pl['name']}")
Workflow 3: Save Album to Library
from spoticlaw import artists, albums, library
artist = search().query("the weeknd", types=["artist"], limit=1)["artists"]["items"][0]
albums_list = artists().get_albums(artist["id"], include_groups="album", limit=5)
album = albums_list["items"][0]
library().save([album["uri"]])
print(f"Saved album: {album['name']}")
Workflow 4: Play Podcast Episode
from spoticlaw import search, shows, player
podcast = search().query("joe rogan", types=["show"], limit=1)["shows"]["items"][0]
show_id = podcast["id"]
episodes = shows().get_episodes(show_id, limit=1)
episode = episodes["items"][0]
episode_uri = episode["uri"]
devices = player().get_devices()
if devices.get("devices"):
device_id = devices["devices"][0]["id"]
player().transfer(device_id, play=True)
player().play(uris=[episode_uri])
print(f"Playing: {episode['name']}")
Workflow 5: Transfer Playback and Play
from spoticlaw import player, search
devices = player().get_devices()
print("Available devices:", [d["name"] for d in devices.get("devices", [])])
if devices.get("devices"):
device_id = devices["devices"][0]["id"]
player().transfer(device_id, play=True)
results = search().query("dream on", types=["track"], limit=1)
track_uri = results["tracks"]["items"][0]["uri"]
player().play(uris=[track_uri])
Workflow 6: Get User's Top Artists and Follow One
from spoticlaw import personalisation, search, library
top = personalisation().get_top("artists", limit=10)
print("Your top artists:")
for i, a in enumerate(top["items"], 1):
print(f" {i}. {a['name']}")
new_artist = search().query("tame impala", types=["artist"], limit=1)["artists"]["items"][0]
print(f"\nFound: {new_artist['name']}")
Workflow 7: Build Queue from Album
from spoticlaw import albums, player
album_id = "4aawyAB9vmqN3uQ7FjRGTy"
tracks = albums().get_tracks(album_id)
for track in tracks["items"][:5]:
player().add_to_queue(track["uri"])
print("Added 5 tracks to queue")
Workflow 8: Check Library for Multiple Tracks
from spoticlaw import library, search
results = search().query("classic rock", types=["track"], limit=20)
track_uris = [t["uri"] for t in results["tracks"]["items"]]
saved = library().check(track_uris)
for i, (track, is_saved) in enumerate(zip(results["tracks"]["items"], saved)):
status = "✓ saved" if is_saved else "○ not saved"
print(f"{i+1}. {track['name']} - {status}")
Workflow 9: Get Recently Played and Save One
from spoticlaw import player, library
recent = player().get_recently_played(limit=10)
print("Recently played:")
for i, item in enumerate(recent["items"], 1):
track = item["track"]
print(f" {i}. {track['name']} - {track['artists'][0]['name']}")
if recent["items"]:
track_uri = recent["items"][0]["track"]["uri"]
library().save([track_uri])
print(f"\nSaved: {recent['items'][0]['track']['name']}")
Workflow 10: Play from Playlist
from spoticlaw import playlists, player
my_playlists = user_playlists().get(limit=10)
print("Your playlists:")
for p in my_playlists["items"]:
print(f" - {p['name']} ({p['tracks']['total']} tracks)")
if my_playlists["items"]:
playlist_id = my_playlists["items"][0]["id"]
devices = player().get_devices()
if devices.get("devices"):
player().transfer(devices["devices"][0]["id"], play=True)
player().play(context_uri=f"spotify:playlist:{playlist_id}")
print(f"Playing: {my_playlists['items'][0]['name']}")
Error Handling
from spoticlaw import player, SpotifyException
try:
player().play(uris=["spotify:track:..."])
except SpotifyException as e:
if "NO_ACTIVE_DEVICE" in str(e):
print("No device found. Open Spotify and try again.")
elif "Invalid token" in str(e):
print("Token expired. Re-authenticate: python auth.py")
else:
print(f"Error: {e}")
Common Issues
| Error | Solution |
|---|
No token. Re-authenticate. | Run python auth.py |
The access token expired | Should auto-refresh. If not, run python auth.py |
Insufficient client scope | Re-auth with more scopes |
NO_ACTIVE_DEVICE | Open Spotify app, then retry |
Invalid limit | Use max 10 for search, 50 for playlists |
Resource not found | Invalid ID or item unavailable |
API Limits
- Search: max 10 results
- Playlist items: max 50
- Pagination: Use
offset parameter
- Player: Requires active Spotify session
Files
scripts/spoticlaw.py - Main API client
scripts/auth.py - Authentication helper
scripts/requirements.txt - Dependencies
More Info
For setup, troubleshooting, and contributions:
https://github.com/your-org/spoticlaw