Skip to content

__init__

Init module for spotdl. This module contains the main entry point for spotdl. And Spotdl class

Spotdl(client_id, client_secret, user_auth=False, cache_path=None, no_cache=False, headless=False, downloader_settings=None, loop=None) ¤

Spotdl class, which simplifies the process of downloading songs from Spotify.

from spotdl import Spotdl

spotdl = Spotdl(client_id='your-client-id', client_secret='your-client-secret')

songs = spotdl.search(['joji - test drive',
    'https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT'])

results = spotdl.download_songs(songs)
song, path = spotdl.download(songs[0])
Arguments¤
  • client_id: Spotify client id
  • client_secret: Spotify client secret
  • user_auth: If true, user will be prompted to authenticate
  • cache_path: Path to cache directory
  • no_cache: If true, no cache will be used
  • headless: If true, no browser will be opened
  • downloader_settings: Settings for the downloader
  • loop: Event loop to use
Source code in spotdl/__init__.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def __init__(
    self,
    client_id: str,
    client_secret: str,
    user_auth: bool = False,
    cache_path: Optional[str] = None,
    no_cache: bool = False,
    headless: bool = False,
    downloader_settings: Optional[
        Union[DownloaderOptionalOptions, DownloaderOptions]
    ] = None,
    loop: Optional[asyncio.AbstractEventLoop] = None,
):
    """
    Initialize the Spotdl class

    ### Arguments
    - client_id: Spotify client id
    - client_secret: Spotify client secret
    - user_auth: If true, user will be prompted to authenticate
    - cache_path: Path to cache directory
    - no_cache: If true, no cache will be used
    - headless: If true, no browser will be opened
    - downloader_settings: Settings for the downloader
    - loop: Event loop to use
    """

    if downloader_settings is None:
        downloader_settings = {}

    # Initialize spotify client
    SpotifyClient.init(
        client_id=client_id,
        client_secret=client_secret,
        user_auth=user_auth,
        cache_path=cache_path,
        no_cache=no_cache,
        headless=headless,
    )

    # Initialize downloader
    self.downloader = Downloader(
        settings=downloader_settings,
        loop=loop,
    )

download(song) ¤

Download and convert song to the output format.

Arguments¤
  • song: Song object
Returns¤
  • A tuple containing the song and the path to the downloaded file if successful.
Source code in spotdl/__init__.py
141
142
143
144
145
146
147
148
149
150
151
152
def download(self, song: Song) -> Tuple[Song, Optional[Path]]:
    """
    Download and convert song to the output format.

    ### Arguments
    - song: Song object

    ### Returns
    - A tuple containing the song and the path to the downloaded file if successful.
    """

    return self.downloader.download_song(song)

download_songs(songs) ¤

Download and convert songs to the output format.

Arguments¤
  • songs: List of Song objects
Returns¤
  • A list of tuples containing the song and the path to the downloaded file if successful.
Source code in spotdl/__init__.py
154
155
156
157
158
159
160
161
162
163
164
165
def download_songs(self, songs: List[Song]) -> List[Tuple[Song, Optional[Path]]]:
    """
    Download and convert songs to the output format.

    ### Arguments
    - songs: List of Song objects

    ### Returns
    - A list of tuples containing the song and the path to the downloaded file if successful.
    """

    return self.downloader.download_multiple_songs(songs)

get_download_urls(songs) ¤

Get the download urls for a list of songs.

Arguments¤
  • songs: List of Song objects
Returns¤
  • A list of urls if successful.
Notes¤
  • This function is multi-threaded.
Source code in spotdl/__init__.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def get_download_urls(self, songs: List[Song]) -> List[Optional[str]]:
    """
    Get the download urls for a list of songs.

    ### Arguments
    - songs: List of Song objects

    ### Returns
    - A list of urls if successful.

    ### Notes
    - This function is multi-threaded.
    """

    urls: List[Optional[str]] = []
    with concurrent.futures.ThreadPoolExecutor(
        max_workers=self.downloader.settings["threads"]
    ) as executor:
        future_to_song = {
            executor.submit(self.downloader.search, song): song for song in songs
        }
        for future in concurrent.futures.as_completed(future_to_song):
            song = future_to_song[future]
            try:
                data = future.result()
                urls.append(data)
            except Exception as exc:
                logger.error("%s generated an exception: %s", song, exc)

    return urls

search(query) ¤

Search for songs.

Arguments¤
  • query: List of search queries
Returns¤
  • A list of Song objects
Notes¤
  • query can be a list of song titles, urls, uris
Source code in spotdl/__init__.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def search(self, query: List[str]) -> List[Song]:
    """
    Search for songs.

    ### Arguments
    - query: List of search queries

    ### Returns
    - A list of Song objects

    ### Notes
    - query can be a list of song titles, urls, uris
    """

    return parse_query(
        query=query,
        threads=self.downloader.settings["threads"],
        use_ytm_data=self.downloader.settings["ytm_data"],
        playlist_numbering=self.downloader.settings["playlist_numbering"],
        album_type=self.downloader.settings["album_type"],
    )

console_entry_point() ¤

Console entry point for spotdl. This is where the magic happens.

Source code in spotdl/console/entry_point.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def console_entry_point():
    """
    Console entry point for spotdl. This is where the magic happens.
    """

    # Create config file if it doesn't exist
    generate_initial_config()

    # Check if sys.argv contains an action
    # If it does, we run the action and exit
    try:
        action_to_run = next(
            action for action_name, action in ACTIONS.items() if action_name in sys.argv
        )
    except StopIteration:
        action_to_run = None

    if action_to_run:
        action_to_run()
        return None

    # Parse the arguments
    arguments = parse_arguments()

    # Create settings dicts
    spotify_settings, downloader_settings, web_settings = create_settings(arguments)

    init_logging(downloader_settings["log_level"], downloader_settings["log_format"])

    # If the application is frozen, we check for ffmpeg
    # if it's not present download it create config file
    if is_executable():
        if is_ffmpeg_installed() is False:
            download_ffmpeg()

    # Check if ffmpeg is installed
    if is_ffmpeg_installed(downloader_settings["ffmpeg"]) is False:
        raise FFmpegError(
            "FFmpeg is not installed. Please run `spotdl --download-ffmpeg` to install it, "
            "or `spotdl --ffmpeg /path/to/ffmpeg` to specify the path to ffmpeg."
        )

    # Check if we are not blocked by ytm
    if "youtube-music" in downloader_settings["audio_providers"]:
        if not check_ytmusic_connection():
            raise DownloaderError(
                "You are blocked by YouTube Music. "
                "Please use a VPN, change youtube-music to piped, or use other audio providers"
            )

    # Initialize spotify client
    SpotifyClient.init(**spotify_settings)
    spotify_client = SpotifyClient()

    # If the application is frozen start web ui
    # or if the operation is `web`
    if is_executable() or arguments.operation == "web":

        # Default to the current directory when running a frozen application
        if is_executable():
            web_settings["web_use_output_dir"] = True

        # Start web ui
        web(web_settings, downloader_settings)

        return None

    # Check if save file is present and if it's valid
    if isinstance(downloader_settings["save_file"], str) and (
        not downloader_settings["save_file"].endswith(".spotdl")
        and not downloader_settings["save_file"] == "-"
    ):
        raise DownloaderError("Save file has to end with .spotdl")

    # Check if the user is logged in
    if (
        arguments.query
        and "saved" in arguments.query
        and not spotify_settings["user_auth"]
    ):
        raise SpotifyError(
            "You must be logged in to use the saved query. "
            "Log in by adding the --user-auth flag"
        )

    # Initialize the downloader
    # for download, load and preload operations
    downloader = Downloader(downloader_settings)

    def graceful_exit(_signal, _frame):
        if spotify_settings["use_cache_file"]:
            save_spotify_cache(spotify_client.cache)

        downloader.progress_handler.close()
        sys.exit(0)

    signal.signal(signal.SIGINT, graceful_exit)
    signal.signal(signal.SIGTERM, graceful_exit)

    start_time = time.perf_counter()

    try:
        # Pick the operation to perform
        # based on the name and run it!
        OPERATIONS[arguments.operation](
            query=arguments.query,
            downloader=downloader,
        )
    except Exception as exc:
        if downloader_settings["save_errors"]:
            with open(
                downloader_settings["save_errors"], "a", encoding="utf-8"
            ) as error_file:
                error_file.write("\n".join([exc + "\n" for exc in exc.args]))

            logger.debug("Saved errors to %s", downloader_settings["save_errors"])

        end_time = time.perf_counter()
        logger.debug("Took %d seconds", end_time - start_time)

        downloader.progress_handler.close()
        logger.exception("An error occurred")

        sys.exit(1)

    end_time = time.perf_counter()
    logger.debug("Took %d seconds", end_time - start_time)

    if spotify_settings["use_cache_file"]:
        save_spotify_cache(spotify_client.cache)

    downloader.progress_handler.close()

    return None