### Install pycloudmusic Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/README.md Install the pycloudmusic library using pip. Ensure you have Python 3.9 or higher. ```bash pip install pycloudmusic ``` -------------------------------- ### Get Daily Recommended Playlist (My.recommend_resource) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Fetches the daily recommended playlist, returning a generator of ShortPlayList objects. This provides access to a curated list of songs for the day. ```python async def recommend_resource(self) -> Generator[ShortPlayList, None, None]: ``` -------------------------------- ### GET /album Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Album.md Retrieves album details and supports iteration over tracks. ```APIDOC ## GET /album ### Description Retrieves an album object by its ID. The object supports direct iteration to return Music objects for each track. ### Method GET ### Endpoint /album ### Parameters #### Query Parameters - **id** (int) - Required - The unique identifier of the album. ``` -------------------------------- ### Get Comments and Replies - Python Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Demonstrates how to fetch comments for a music item, including nested replies (floors). Requires login for certain operations like liking or replying. ```python from pycloudmusic import Music163Api import asyncio async def main(): # 需要登录才能进行评论操作 musicapi = Music163Api("your_cookie_here") music = await musicapi.music(1902224491) # 获取评论 count, comments = await music.comments(hot=True, page=0, limit=10) for comment in comments: print(f"评论: {comment.content}") print(f" 评论ID: {comment.id}") print(f" 用户: {comment.user_str}") print(f" 点赞数: {comment.liked_count}") print(f" 是否已点赞: {comment.liked}") # 获取楼层评论(回复) floor_count, floor_comments = await comment.floors(page=0, limit=10) if floor_count > 0: print(f" 楼层回复 ({floor_count}):") for floor in floor_comments: print(f" {floor.user_str}: {floor.content}") # 点赞评论 # result = await comment.like(in_=True) # 回复评论 # result = await comment.reply("回复内容") # 删除评论(仅能删除自己的评论) # result = await comment.delete() asyncio.run(main()) ``` -------------------------------- ### Get Daily Recommended Songs (My.recommend_songs) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Retrieves daily recommended songs as a generator yielding Music objects. This method is useful for personalized music discovery. ```python async def recommend_songs(self) -> Generator[Music, None, None]: ``` -------------------------------- ### Get Similar Artists Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Artist.md Fetches a list of artists similar to the current artist object. ```python async def similar(self) -> Any: ``` -------------------------------- ### Get Personal FM (My.fm) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Instantiates and returns an Fm object for accessing the user's personal FM radio. ```python def fm(self) -> Fm: ``` -------------------------------- ### Get Cloud Drive Data (My.cloud) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Fetches cloud drive data and instantiates a Cloud object. Returns API error information if instantiation fails. ```python async def cloud(self, page: int = 0, limit: int = 30) -> Cloud: ``` -------------------------------- ### Get Subscribed Albums (My.sublist_album) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Fetches a list of albums that the user has subscribed to. Returns a tuple with the total album count and a generator of ShortAlbum objects. ```python async def sublist_album(self, page: int = 0, limit: int = 25) -> tuple[int, Generator[ShortAlbum, None, None]]: ``` -------------------------------- ### Smart Play Mode (My.playmode_intelligence) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Initiates smart play mode for a given song, returning a generator of Music objects. Optionally specify a starting song ID or a playlist ID. ```python async def playmode_intelligence(self, music_id: Union[str, int], sid: Optional[Union[str, int]] = None, playlist_id: Optional[Union[str, int]] = None) -> Generator[Music, None, None]: ``` -------------------------------- ### Get Subscribed MVs (My.sublist_mv) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Fetches a list of MVs that the user has subscribed to. Returns a tuple with the total MV count and a generator of ShortMv objects. ```python async def sublist_mv(self, page: int = 0, limit: int = 25) -> tuple[int, Generator[ShortMv, None, None]]: ``` -------------------------------- ### Implement Music163CommentItem Class Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/CommentObject.md Example implementation of a comment item class inheriting from CommentItemObject, mapping raw dictionary data to object attributes. ```python class Music163CommentItem(CommentItemObject): def __init__( self, headers: Optional[dict[str, str]], comment_data: dict[str, Any] ) -> None: super().__init__(headers, comment_data) # 评论 id self.id = comment_data["commentId"] # 资源 id self.thread_id = comment_data["threadId"] # 用户 id self.user = comment_data["user"] # 用户名 self.user_str = comment_data["user"]["nickname"] # 评论内容 self.content = comment_data["content"] # 评论时间 self.time = comment_data["time"] self.time_str = comment_data["timeStr"] # 评论点赞数 self.liked_count = comment_data["likedCount"] # 是否点赞了该评论 self.liked = comment_data["liked"] ``` -------------------------------- ### LoginMusic163 - Email Login Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Performs login using email and password. Returns a status code, cookie, and an authenticated Music163Api object. Useful for programmatic access after initial setup. ```python from pycloudmusic import LoginMusic163 import asyncio async def main(): login = LoginMusic163() # 方式一:邮箱登录 code, cookie, musicapi = await login.email("your_email@example.com", "your_password") print(f"登录状态码: {code}") print(f"Cookie: {cookie[:50]}...") # 验证登录状态 my = await musicapi.my() print(f"用户名: {my.name}") print(f"等级: {my.level}") print(f"最后登录IP: {my.login_ip}") print(f"最后登录时间: {my.login_time_str}") asyncio.run(main()) ``` -------------------------------- ### Get Subscribed DJs (My.sublist_dj) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Retrieves a list of DJ programs that the user has subscribed to. Returns a tuple containing the total DJ count and a generator of ShortDj objects. ```python async def sublist_dj(self, page: int = 0, limit: int = 25) -> tuple[int, Generator[ShortDj, None, None]]: ``` -------------------------------- ### Configure Proxy Settings and Callback Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/README.md Demonstrates how to set a proxy for requests and configure a callback function to update the proxy if an error occurs. The callback should return the new proxy and authentication details. ```python from pycloudmusic import Music163Api, set_proxy, set_proxy_callback import asyncio # 正常这里是多个 proxy ip proxy = [ "http://117.114.149.66:55443" ] # 设置 proxy set_proxy(proxy[0]) # proxy 更新回调 def proxy_callback(err): # 如果 proxy 时出现错误这里更新 # 第一个返回值新的 proxy ip # 第二个返回值 aiohttp.BasicAuth proxy 身份验证, 没有为 None return proxy[0], None # 设置 proxy 更新回调 set_proxy_callback(proxy_callback) async def main(): musicapi = Music163Api() # 获取歌曲 421531 # https://music.163.com/#/song?id=421531 music = await musicapi.music(421531) await music.play() # 打印歌曲信息 print(music) print("=" * 50) asyncio.run(main()) ``` -------------------------------- ### GET /dj/read Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Dj.md Retrieves a list of programs for a specific radio station. ```APIDOC ## GET /dj/read ### Description Fetches radio programs for the station, updates the internal data list, and returns the raw JSON response. ### Method GET ### Parameters #### Query Parameters - **page** (int) - Optional - The page number to retrieve. Defaults to 0. - **limit** (int) - Optional - Number of items per page. Defaults to 30. - **asc** (bool) - Optional - Sort order. False for chronological, True for reverse chronological. ``` -------------------------------- ### Global Configuration - Python Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Demonstrates how to set global configuration parameters for the library using `set_config`. This includes download path, concurrency limits, chunk size, reconnection attempts, timeouts, and objects to exclude from printing. ```python from pycloudmusic import Music163Api, set_config import asyncio # 设置全局配置 set_config({ "DOWNLOAD_PATH": "./my_downloads", # 下载目录 "LIMIT": 16, # 最大并行请求数 "CHUNK_SIZE": 2048, # 下载文件缓存大小(KB) "RECONNECTION": 5, # 重连次数 "TIMEOUT": 60, # 超时时间(秒) "NOT_PRINT_OBJECT_DICT": ["music_list"] # 打印时不输出的列表 }) async def main(): musicapi = Music163Api() music = await musicapi.music(421531) # 下载将使用配置的路径 file_path = await music.play() print(f"下载到: {file_path}") asyncio.run(main()) ``` -------------------------------- ### My Class Initialization Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Initializes the My class with headers and user data, inheriting all instance variables and methods from the User class. ```APIDOC ## My Class Initialization ### Description Initializes the My class with optional headers and user data. It inherits all instance variables and methods from the User class and adds specific attributes related to the user's login information. ### Parameters #### Request Body - **headers** (Optional[dict[str, str]]) - Optional headers for the request. - **user_data** (dict[str, Any]) - A dictionary containing user profile information, including login IP and time. ``` -------------------------------- ### GET /dj Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Dj.md Retrieves radio station details and allows iteration over radio programs. ```APIDOC ## GET /dj ### Description Retrieves radio station data and provides methods to interact with the station's programs and metadata. ### Method GET ### Endpoint /dj ### Parameters #### Path Parameters - **id** (int) - Required - The unique identifier for the radio station. ### Response #### Success Response (200) - **name** (string) - Radio station title - **id** (int) - Radio station ID - **cover** (string) - Radio station cover image URL - **music_count** (int) - Total number of programs in the radio station - **subscribed_count** (int) - Total number of subscribers ``` -------------------------------- ### Music Class Initialization Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Music.md The constructor initializes the Music object with headers and raw music data, mapping fields like ID, name, artist, and quality settings. ```python class Music(_Music): def __init__( self, headers: Optional[dict[str, str]], music_data: dict[str, Any] ) -> None: super().__init__(headers, music_data) # 资源类型 self.data_type = DATA_TYPE[0] # 歌曲id self.id = music_data['id'] # 标题列表 [大标题, 副标题] self.name = [music_data['name'], music_data["alia"][0] if music_data["alia"] != [] else ""] self.name_str = self.name[0] + self.name[1] # 作者列表 [作者, 作者, ...] self.artist = [{"id": artist["id"], "name": artist["name"]} for artist in music_data['ar']] self.artist_str = "/".join([author["name"] for author in self.artist]) # 专辑列表 self.album_data = music_data["al"] self.album_str = self.album_data["name"] # 所有音质 self.quality = { "h": music_data["h"], "m": music_data["m"], "l": music_data["l"], "sq": music_data["sq"], "hr": music_data["hr"], } # mv id self.mv_id = music_data["mv"] self.publish_time = music_data["publishTime"] # 推荐理由 self.reason = music_data["reason"] if "reason" in music_data else None ``` -------------------------------- ### Initialize My Class Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Initializes the My class with headers and user data, inheriting all instance variables from the User class. It also extracts login IP and time from the provided user data. ```python class My(User): def __init__( self, headers: Optional[dict[str, str]], user_data: dict[str, Any] ) -> None: super().__init__(headers, user_data) """包括 User 的所有实例变量""" # 登录ip self.login_ip = user_data["profile"]["lastLoginIP"] # 登录时间 self.login_time = int(user_data["profile"]["lastLoginTime"] / 1000) self.login_time_str = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(self.login_time)) ``` -------------------------------- ### My.playmode_intelligence Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Initiates intelligent playback based on a given song, optionally starting from a specific track or playlist. ```APIDOC ## My.playmode_intelligence ### Description Starts intelligent playback (also known as "heart mode") for a song. Returns a generator that yields Music objects. ### Method `async def playmode_intelligence(self, music_id: Union[str, int], sid: Optional[Union[str, int]] = None, playlist_id: Optional[Union[str, int]] = None) -> Generator[Music, None, None]` ### Parameters #### Query Parameters - **music_id** (Union[str, int]) - Required. The ID of the song to base the intelligent playback on. - **sid** (Optional[Union[str, int]]) - Optional. The ID of the song to start playback from. - **playlist_id** (Optional[Union[str, int]]) - Optional. The ID of the playlist to use. Defaults to the user's liked songs playlist. ### Response Example ```json [ { "id": "11223", "title": "Intelligent Track", "artist": "AI Composer" } ] ``` ``` -------------------------------- ### Initialize PersonalizedMusic Instance Variables Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/ShortObject.md Initializes instance variables for PersonalizedMusic, extracting details like song ID, name, artists, album, and audio quality from music data. Requires Optional headers and a music_data dictionary. ```python class PersonalizedMusic(_Music): def __init__( self, headers: Optional[dict[str, str]], music_data: dict[str, Any] ) -> None: super().__init__(headers, music_data) # 资源类型 self.data_type = DATA_TYPE[0] # 歌曲id self.id = music_data['id'] # 标题列表 [大标题, 副标题] self.name = [music_data["name"], " ".join(music_data["alias"])] self.name_str = f"{self.name[0]} {self.name[1]}" # 作者列表 [作者, 作者, ...] self.artist = [{"id": artist["id"], "name": artist["name"]} for artist in music_data['artists']] self.artist_str = "/".join([author["name"] for author in self.artist]) # 专辑列表 self.album_data = music_data["album"] self.album_str = music_data["album"]["name"] # 所有音质 self.quality = { "b": music_data["bMusic"], "h": music_data["hMusic"], "m": music_data["mMusic"], "l": music_data["lMusic"], "sq": music_data.get("sqMusic"), "hr": music_data.get("hrMusic"), } # mv id self.mv_id = music_data["mvid"] # 发表时间 self.album_data["publishTime"] ``` -------------------------------- ### Get User's Liked Music Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/User.md Retrieves a PlayList object containing the user's liked music. ```python async def like_music(self) -> PlayList: ``` -------------------------------- ### Get Private Messages (My.message) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Instantiates and returns a Message object for accessing the user's private messages. ```python def message(self) -> Message: ``` -------------------------------- ### Iterating through Fm songs Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Fm.md Demonstrates how to initialize the Music163Api, authenticate, and then continuously fetch and process personalized FM songs. ```Python import pycloudmusic import asyncio import time async def main(): musicapi = pycloudmusic.Music163Api("your_netease_cookie") my = await musicapi.my() print(my) print("=" * 60) fm = my.fm() while True: await fm.read() for music in fm: print(music.name, music.artist_str, music.id) time.sleep(3) asyncio.run(main()) ``` -------------------------------- ### Get User's Playlist Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/User.md Retrieves a generator of PlayList objects for the user. Supports pagination with page and limit parameters. ```python async def playlist(self, page: int = 0, limit: int = 30) -> Generator[PlayList, None, None]: ``` -------------------------------- ### Proxy Configuration - Python Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Shows how to configure HTTP proxies for API requests and set up a callback function to automatically switch proxies upon failure. The callback should return a new proxy URL and authentication details. ```python from pycloudmusic import Music163Api, set_proxy, set_proxy_callback import asyncio # 代理列表 proxy_list = [ "http://117.114.149.66:55443", "http://proxy2.example.com:8080" ] current_index = 0 # 设置初始代理 set_proxy(proxy_list[0]) # 代理更新回调 def proxy_callback(err): global current_index current_index = (current_index + 1) % len(proxy_list) new_proxy = proxy_list[current_index] print(f"代理失败,切换到: {new_proxy}") # 返回 (新代理URL, aiohttp.BasicAuth 或 None) return new_proxy, None # 设置回调 set_proxy_callback(proxy_callback) async def main(): musicapi = Music163Api() # 使用代理获取歌曲 music = await musicapi.music(421531) print(f"歌曲: {music.name_str}") asyncio.run(main()) ``` -------------------------------- ### Iterate over Fm tracks Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Fm.md Demonstrates how to initialize the API, retrieve the FM object, and iterate through tracks while refreshing the list. ```python """迭代 Fm""" from pycloudmusic import Music163Api import asyncio import time async def mian(): musicapi = Music163Api("你网易云的 Cookie") # 验证 cookie 有效性, 并返回 my 对象 my = await musicapi.my() # 打印 Cookie 用户信息 print(my) print("=" * 60) """ 每 3 秒, 获取一次 Fm 歌曲 """ # 返回 fm 对象 fm = my.fm() while True: # 获取 Fm 歌曲 await fm.read() # 打印 Fm 歌曲 for music in fm: print(music.name, music.artist_str, music.id) # 休息 3 秒 time.sleep(3) asyncio.run(mian()) ``` -------------------------------- ### Get User Events (My.event) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Instantiates and returns an Event object for accessing the user's activity feed and events. ```python def event(self) -> Event: ``` -------------------------------- ### Initialize Artist Object Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Artist.md Initializes an Artist object with headers and artist data. It populates attributes like ID, name, description, album count, music count, MV count, and cover image. ```python class Artist(_Artist): def __init__( self, headers: Optional[dict[str, str]], artist_data: dict[str, Any] ) -> None: super().__init__(headers, artist_data) # 歌手id self.id = artist_data["id"] # 歌手 self.name = artist_data["name"] # 歌手简介 self.brief_desc_str = artist_data["briefDesc"] self.brief_desc = artist_data["briefDesc"].split("\n") # 专辑数 self.album_size = artist_data["albumSize"] # 单曲数 self.music_size = artist_data["musicSize"] # mv数 self.mv_size = artist_data["mvSize"] # 头像 self.cover = artist_data["cover"] ``` -------------------------------- ### Get Subscribed Topics (My.sublist_topic) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Retrieves a list of topics that the user has subscribed to. Returns a dictionary containing topic information. ```python async def sublist_topic(self, page: int = 0, limit: int = 50) -> dict[str, Any]: ``` -------------------------------- ### Authenticate with Email using LoginMusic163 Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/LoginMusic163.md Demonstrates logging in via email and password to retrieve a session cookie and an authenticated API instance. ```python from pycloudmusic import LoginMusic163 import asyncio async def main(): login = LoginMusic163() # 邮箱登录 cookie, musicapi = await login.email("you login email", "you login password") # 验证登录 print(cookie, musicapi) print("=" * 60) print(await musicapi.my()) asyncio.run(main()) ``` -------------------------------- ### Get Artist Albums Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Artist.md Retrieves albums by the artist, supporting pagination for fetching results. Returns a generator of Album objects. ```python async def album(self, page: int = 0, limit: int = 30) -> Generator[Album, None, None]: ``` -------------------------------- ### Get Artist Songs Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Artist.md Retrieves songs by the artist, with options to sort by popularity or time. Supports pagination for fetching songs. ```python async def song(self, hot: bool = True, page: int = 0, limit: int = 100) -> Generator[Music, None, None]: ``` -------------------------------- ### Iterate Album Tracks Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Album.md Demonstrates how to fetch an album and iterate through its tracks to access music details. ```python """迭代 Album""" from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # 获取歌单 62338 album = await musicapi.album(62338) # 迭代 album 打印专辑曲目 for music in album: print(music.name, music.artist_str, music.id) asyncio.run(main()) ``` -------------------------------- ### Get Personalized Playlists Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Retrieves a generator of ShorterPlayList objects representing personalized playlists. A limit can be specified for the number of playlists returned. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # 获取推荐歌单 playlists = await musicapi.personalized_playlist(limit=10) for playlist in playlists: print(f"{playlist.name}") asyncio.run(main()) ``` -------------------------------- ### Iterate Dj Radio Programs Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Dj.md Demonstrates how to fetch a radio station and iterate through its programs by reading pages. ```python """迭代 Dj""" from pycloudmusic import Music163Api import asyncio async def mian(): musicapi = Music163Api() # 获取电台 # https://music.163.com/#/djradio?id=342290050 dj = await musicapi.dj(342290050) # 计算电台页数 dj_music_page = int(dj.music_count / 30) while dj_music_page > 0: # 获取电台节目 await dj.read(dj_music_page, asc=True) # 打印电台节目 for music in dj: print(music.name, music.id) dj_music_page -= 1 asyncio.run(mian()) ``` -------------------------------- ### Get Artist Top 50 Songs Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Artist.md Fetches the top 50 most popular songs by the artist, returning them as a generator of Music objects. ```python async def song_top(self) -> Generator[Music, None, None] ``` -------------------------------- ### Iterate over PlayList tracks Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/PlayList.md Demonstrates how to fetch a playlist and iterate through its tracks to access music metadata. ```python """迭代 PlayList""" from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # 获取歌单 7487291782 playlist = await musicapi.playlist(7487291782) # 迭代 PlayList 打印歌单曲目 for music in playlist: print(music.name, music.artist_str, music.id) asyncio.run(main()) ``` -------------------------------- ### Iterate User Events with Event Class Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Event.md Demonstrates how to initialize the Event class and iterate through a user's dynamic feed by managing the last_time parameter. ```python """迭代 Event""" from pycloudmusic import Music163Api import asyncio async def mian(): musicapi = Music163Api("你网易云的 Cookie") # 验证 cookie 有效性, 并返回 my 对象 my = await musicapi.my() # 打印 Cookie 用户信息 print(my) print("=" * 60) # 初始化 event, last_time, count = my.event(), -1, 0 while True: try: # 获取动态并重设 last_time # https://music.163.com/#/user/home?id=1452176465 last_time = (await event.read_user(1452176465, last_time))["lasttime"] except KeyError: # 没有动态时不会有 lasttime 会发生 KeyError, 依赖这个判断跳出循环 break # 打印动态 for event_item in event: print(event_item.user_str, event_item.msg["msg"], event_item.id) count += 1 # 打印总动态数 print(f"总动态数: {count}") asyncio.run(mian()) ``` -------------------------------- ### Email Login with pycloudmusic Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/README.md Demonstrates how to log in using email and password to maintain a long-term valid cookie. This method does not require manual interaction. ```python from pycloudmusic import LoginMusic163 import asyncio async def main(): login = LoginMusic163() # 邮箱登录 code, cookie, musicapi = await login.email("you login email", "you login password") # 验证登录 print("=" * 60) print(code, cookie, musicapi) print("=" * 60) print(await musicapi.my()) asyncio.run(main()) ``` -------------------------------- ### Iterating Through a PlayList Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/PlayList.md Demonstrates how to fetch a playlist and iterate through its songs, printing the name, artist, and ID of each track. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # Get playlist 7487291782 playlist = await musicapi.playlist(7487291782) # Iterate through PlayList and print track details for music in playlist: print(music.name, music.artist_str, music.id) asyncio.run(main()) ``` -------------------------------- ### Retrieve All API Pages with Page.all Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Tools.md Demonstrates using the Page.all method to fetch all pages of data at once instead of iterating incrementally. ```python from pycloudmusic import Music163Api, Page import asyncio async def main(): musicapi = Music163Api() # https://music.163.com/song?id=1902224491&userid=492346933 music = await musicapi.music(1902224491) # 一次性请求所有数据 for count, comments in await Page(music.comments, hot=False).all(): # 遍历一页的数据 for comment in comments: print(f"{comment.user_str}: {comment.content}") asyncio.run(main()) ``` -------------------------------- ### Page Object Initialization Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Tools.md The Page object is used to iterate over paginated data from bound APIs. It can be initialized with an API function, limit, and starting page. ```APIDOC ## `class` Page **`def __init__(self, api_fun: Callable, limit: Optional[int] = None, page: int = 0, **kwargs) -> None:`** Page 对象可以按内部设置的方法来遍历绑定 Api 的页 > `api_fun`: 绑定的 Api > > `limit`: 一页的数据量 > > `page`: 遍历起点页数, 默认0 (重头开始) > > `**kwargs`: 绑定的 Api 其它参数 ``` -------------------------------- ### Core API Usage with Music163Api Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Demonstrates basic usage of the Music163Api class to fetch various music resources like songs, playlists, users, artists, albums, MVs, and radio stations. No login is required for these basic functionalities. ```python from pycloudmusic import Music163Api import asyncio async def main(): # 创建 API 实例(无需登录即可使用基础功能) musicapi = Music163Api() # 获取单首歌曲 # https://music.163.com/#/song?id=421531 music = await musicapi.music(421531) print(f"歌曲: {music.name_str}") print(f"歌手: {music.artist_str}") print(f"专辑: {music.album_str}") # 批量获取多首歌曲 music_ids = [421531, 1902224491, 1899317143] musics = await musicapi.music(music_ids) for m in musics: print(f"{m.name_str} - {m.artist_str}") # 获取歌单 # https://music.163.com/#/playlist?id=7487291782 playlist = await musicapi.playlist(7487291782) print(f"歌单: {playlist.name}") print(f"创建者: {playlist.user_str}") print(f"播放量: {playlist.play_count}") # 获取用户信息 user = await musicapi.user(492346933) print(f"用户: {user.name}") print(f"等级: {user.level}") # 获取歌手信息 artist = await musicapi.artist(12138269) print(f"歌手: {artist.name}") print(f"专辑数: {artist.album_size}") # 获取专辑信息 album = await musicapi.album(62338) print(f"专辑: {album.name}") print(f"曲目数: {album.size}") # 获取 MV 信息 mv = await musicapi.mv(5436712) print(f"MV: {mv.name}") print(f"播放量: {mv.play_count}") # 获取电台信息 dj = await musicapi.dj(342290050) print(f"电台: {dj.name}") print(f"节目数: {dj.music_count}") asyncio.run(main()) ``` -------------------------------- ### Get Top Artist List Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Fetches a list of top artists, categorized by region (Chinese, European/American, Korean, Japanese). Returns a generator of Artist objects. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # 获取华语歌手榜 (type_: 1华语, 2欧美, 3韩国, 4日本) artists = await musicapi.top_artist_list(type_=1, page=0, limit=20) print("华语歌手榜:") for artist in artists: print(f"{artist.name} - 单曲数: {artist.music_size}") asyncio.run(main()) ``` -------------------------------- ### Subscribe/Unsubscribe Items - Python Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Demonstrates how to subscribe (favorite) or unsubscribe from various music items like playlists, albums, artists, MVs, and radio stations. Requires login. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api("your_cookie_here") # 收藏歌单 playlist = await musicapi.playlist(7487291782) result = await playlist.subscribe(in_=True) # True=收藏, False=取消 print(f"收藏歌单: {result}") # 收藏专辑 album = await musicapi.album(62338) result = await album.subscribe(in_=True) print(f"收藏专辑: {result}") # 收藏歌手 artist = await musicapi.artist(12138269) result = await artist.subscribe(in_=True) print(f"收藏歌手: {result}") # 收藏 MV mv = await musicapi.mv(5436712) result = await mv.subscribe(in_=True) print(f"收藏MV: {result}") # 收藏电台 dj = await musicapi.dj(342290050) result = await dj.subscribe(in_=True) print(f"收藏电台: {result}") asyncio.run(main()) ``` -------------------------------- ### PlayList class definition and instance variables Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/PlayList.md Shows the internal structure of the PlayList class and how instance variables are initialized from playlist data. ```python class PlayList(_PlayList): def __init__( self, headers: Optional[dict[str, str]], playlist_data: dict[str, Any] ) -> None: super().__init__(headers, playlist_data) # 资源类型 self.data_type = DATA_TYPE[2] # 歌单id self.id = playlist_data["id"] # 歌单标题 self.name = playlist_data["name"] # 歌单封面 self.cover = playlist_data['coverImgUrl'] # 歌单创建者 self.user = playlist_data['creator'] self.user_str = playlist_data['creator']["nickname"] # 歌单tags self.tags = playlist_data['tags'] self.tags_str = "/".join(playlist_data['tags']) # 歌单描述 self.description = playlist_data["description"] # 歌单播放量 self.play_count = playlist_data["playCount"] # 歌单收藏量 self.subscribed_count = playlist_data["subscribedCount"] # 歌单创建时间 self.create_time = playlist_data["createTime"] # 歌单歌曲 self.music_list = playlist_data["tracks"] ``` -------------------------------- ### Get User's Listening Record Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/User.md Retrieves a generator of Music objects representing the user's listening history. Can fetch all-time or recent week records. ```python async def record(self, type_: bool = True) -> Generator[Music, None, None]: ``` -------------------------------- ### Album Class Instance Variables Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/Album.md Shows the internal structure and initialization of the Album class for accessing metadata via dot notation. ```python class Album(_Album): def __init__( self, headers: Optional[dict[str, str]], album_data: dict[str, Any] ) -> None: super().__init__(headers, album_data) # 专辑id self.id = album_data["album"]["id"] # 专辑标题 self.name = album_data["album"]["name"] # 专辑类型 self.sub_type = album_data["album"]["subType"] # 专辑别名 self.alias = album_data["album"]["alias"] self.alias_str = "/".join(self.alias) # 专辑主作者 self.artist = album_data["album"]["artist"] # 专辑所有作者 self.artists = album_data["album"]["artists"] self.artists_str = "/".join([artists_data["name"] for artists_data in self.artists]) # 专辑曲目数 self.size = album_data["album"]["size"] # 专辑简介 self.description = album_data["album"]["description"] # 未知 self.liked = album_data["album"]["info"]["liked"] # 专辑评论数 self.comment_count = album_data["album"]["info"]["commentCount"] # 专辑分享数 self.share_count = album_data["album"]["info"]["shareCount"] # 未知 self.liked_count = album_data["album"]["info"]["likedCount"] # 专辑封面 self.cover = album_data["album"]['picUrl'] # 专辑曲目 (json) self.music_list = album_data["songs"] ``` -------------------------------- ### Get Subscribed Artists (My.sublist_artist) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Retrieves a list of artists that the user has subscribed to. Returns a tuple containing the total count of followed artists and a generator of ShortArtist objects. ```python async def sublist_artist(self, page: int = 0, limit: int = 25) -> tuple[int, Generator[ShortArtist, None, None]]: ``` -------------------------------- ### Sign In (My.sign) Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/My.md Performs a sign-in action for the user. Use `type_=True` for Android sign-in (3 experience points) or `type_=False` for web sign-in (2 experience points). ```python async def sign(self, type_: bool = True) -> dict[str, Any]: ``` -------------------------------- ### Authenticate with QR Code using LoginMusic163 Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/LoginMusic163.md Retrieves a QR key, displays the URL for QR generation, and waits for the user to scan and authorize the login. ```python from pycloudmusic import LoginMusic163 import asyncio async def main(): login = LoginMusic163() # 获取二维码 key qr_key = await login.qr_key() # 去 https://cli.im/ 生成二维码或者自己生成二维码 print(f"请使用该 url 生成二维码: {qr_key[1]}") # 等待扫码 cookie, musicapi = await login.qr(qr_key[0]) # 验证登录 print(cookie, musicapi) print("=" * 60) print(await musicapi.my()) asyncio.run(main()) ``` -------------------------------- ### User Class Initialization Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/User.md Details on how a User object is initialized with user data and headers. ```APIDOC ## User Class Initialization ### Description Initializes a User object with provided headers and user profile data. ### Parameters #### Request Body - **headers** (dict[str, str]) - Optional - Headers for API requests. - **user_data** (dict[str, Any]) - Required - Dictionary containing user profile information. ``` -------------------------------- ### Initialize User Class Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/User.md Initializes a User object with user data and optional headers. Extracts user ID, name, signature, level, avatar, and VIP status from the provided data. ```python class User(Api): def __init__( self, headers: Optional[dict[str, str]], user_data: dict[str, Any] ) -> None: super().__init__(headers) _user_data = user_data["profile"] if "profile" in user_data else user_data # 用户uid self.id = _user_data["userId"] # 用户名称 self.name = _user_data["nickname"] # 用户签名 self.signature = _user_data["signature"] # 用户等级 self.level = user_data["level"] if "level" in user_data else None # 头像 self.cover = _user_data['avatarUrl'] # 会员 0 无 self.vip = _user_data["vipType"] self.like_playlist_id = None ``` -------------------------------- ### Use Intelligent Playback Mode Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Generates a recommended playlist based on a specific song ID using the intelligence playback mode. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api("your_cookie_here") my = await musicapi.my() # 心动模式 - 基于某首歌曲生成推荐列表 songs = await my.playmode_intelligence( music_id=421531, # 基准歌曲ID sid=None, # 可选:开始播放的歌曲ID playlist_id=None # 可选:歌单ID,默认使用喜欢的歌曲 ) print("心动模式推荐:") for song in songs: print(f" {song.name_str} - {song.artist_str}") asyncio.run(main()) ``` -------------------------------- ### Get New Songs (Top Song) Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Retrieves new songs ('New Music Express'), with options to filter by region (All, Chinese, European/American, Japanese, Korean). Returns a generator of PersonalizedMusic objects. ```python from pycloudmusic import Music163Api import asyncio async def main(): musicapi = Music163Api() # 获取新歌速递 (type_: 0全部, 7华语, 96欧美, 8日本, 16韩国) songs = await musicapi.top_song(type_=0) print("新歌速递:") for song in songs: print(f"{song.name} - {song.artist_str}") asyncio.run(main()) ``` -------------------------------- ### PlayList Class Overview Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/PlayList.md The PlayList class is a DataListObject that represents a music playlist. It supports direct iteration to get Music objects, attribute access using dot notation, and playlist-related API calls. It also supports comments. ```APIDOC ## PlayList Class ### Description A data list object representing a music playlist. Supports iteration for songs, attribute access, and playlist management APIs. ### Attributes - **data_type** (string) - Resource type. - **id** (string) - Playlist ID. - **name** (string) - Playlist title. - **cover** (string) - Playlist cover image URL. - **user** (dict) - Creator information. - **user_str** (string) - Creator's nickname. - **tags** (list) - List of tags associated with the playlist. - **tags_str** (string) - Formatted string of playlist tags. - **description** (string) - Playlist description. - **play_count** (integer) - Number of times the playlist has been played. - **subscribed_count** (integer) - Number of users who have subscribed to the playlist. - **create_time** (integer) - Timestamp of when the playlist was created. - **music_list** (list) - List of tracks in the playlist. ``` -------------------------------- ### Manage User Account and Personal Data Source: https://context7.com/fengliufeseliud/pycloudmusic/llms.txt Demonstrates accessing user profile information, performing daily check-ins, and retrieving personalized recommendations like songs, playlists, and subscriptions. ```python from pycloudmusic import Music163Api import asyncio async def main(): # 使用已登录的 Cookie musicapi = Music163Api("your_cookie_here") # 获取当前登录用户信息 my = await musicapi.my() # 访问用户属性(继承自 User) print(f"用户名: {my.name}") print(f"等级: {my.level}") print(f"最后登录IP: {my.login_ip}") print(f"最后登录时间: {my.login_time_str}") # 签到(安卓端3点经验/网页端2点经验) sign_result = await my.sign(type_=True) # True=安卓端 print(f"签到结果: {sign_result}") # 获取日推歌曲 daily_songs = await my.recommend_songs() print("\n每日推荐:") for song in daily_songs: print(f" {song.name_str} - {song.artist_str}") # 获取每日推荐歌单 daily_playlists = await my.recommend_resource() print("\n推荐歌单:") for pl in daily_playlists: print(f" {pl.name}") # 获取收藏的歌手 count, artists = await my.sublist_artist(page=0, limit=25) print(f"\n收藏的歌手 ({count}):") for artist in artists: print(f" {artist.name}") # 获取收藏的专辑 count, albums = await my.sublist_album(page=0, limit=25) print(f"\n收藏的专辑 ({count}):") for album in albums: print(f" {album.name}") asyncio.run(main()) ``` -------------------------------- ### PlayList.add Method Source: https://github.com/fengliufeseliud/pycloudmusic/blob/main/docs/PlayList.md Adds one or more songs to the playlist. ```APIDOC ## POST /playlist/add/track ### Description Adds one or more songs to the playlist. ### Method POST ### Endpoint `/playlist/add/track` ### Parameters #### Request Body - **music_id** (string or integer or list) - Required - The ID(s) of the song(s) to add. Can be a single ID or a list of IDs. ```