async def init(self, login: str = '', pwd: str = ''): """ Start point for get music.yandex.ru client :param login: Username or token string :param pwd: Password string :return: yandex_music.Client """ try: if login != '' and pwd != '': # Old authorization method, report_new_fields no need to new auth # self.client = Client.from_credentials(login, pwd, report_new_fields=False) self.client = Client.from_credentials(login, pwd) return True else: if pwd == '' and login != '': # Old authorization method, report_new_fields no need to new auth # self.client = Client.from_token(login, report_new_fields=False) self.client = Client.from_token(login) return True else: # Old authorization method, report_new_fields no need to new auth # self.client = Client.from_credentials(LOGIN, PWD, report_new_fields=False) self.client = Client.from_credentials(LOGIN, PWD) return True except Unauthorized: print("Unauthorized") return False except YandexMusicError: print("YandexMusicError") return False
def check_login(settings): token = settings.getSetting('token') if not token: return False, Client() try: client = Client.from_token(token) return True, client except Unauthorized as _: return False, Client()
def __init__(self, setting): self.client = Client() super().__init__() self.select_PL = None self.start_load_Pl = False self.start_download = False self.this = None self.list_track = [] self.setting = setting self.play_lists_info = dict()
def get_artist_and_title_from_yandex(album_id, track_id): from yandex_music import Client client = Client() if album_id == "": track_info = client.tracks(track_id) else: trackID = str(track_id) + ':' + str(album_id) track_info = client.tracks(trackID) title, artist = track_info[0].title, track_info[0].artists_name()[0] return artist, title
def initialize(self): self.api = Client(token=self.config.token) try: self.api.init() except (UnauthorizedError, NetworkError) as e: logging.error(e) raise errors.ServiceError(e) if not self.api.account_status().account.uid: self.warning_message = self.bot.translator.translate( "Token is not provided") elif not self.api.account_status().plus["has_plus"]: self.warning_message = self.bot.translator.translate( "You don't have Yandex Plus")
def __init__(self): self.client = Client() self.url_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/album\/([0-9]+)\/track\/([0-9]+)' ) self.url_without_album_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/track\/([0-9]+)' ) self.url_artist_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/artist\/([0-9]+)' ) self.url_album_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/album\/([0-9]+)' )
def __init__(self, title: str, username: str | None = None, password: str | None = None, token: str | None = None, cache="/tmp/YMStreamer", debug=False): super().__init__(title, debug) if token is not None: self.client = Client.from_token(token) else: self.client = Client.from_credentials(username or '', password or '') global CACHE_FOLDER CACHE_FOLDER = cache
def auth(self): if self.read_auth_token_from_file(): try: self.client = Client(self.auth_token) except Unauthorized as auth_exception: self.show_popup_error('Authorisation error', f'{auth_exception}', 1) else: self.show_auth_dialog() try: self.client = Client.from_credentials(self.auth_email, self.auth_password) self.save_auth_token_in_file() except BadRequest as auth_exception: self.show_popup_error('Auth by credentials error', f'{auth_exception}', 1)
def get_url_from_yandex_by_artist_and_title(artist, title): from yandex_music.utils.request import Request from yandex_music import Client request = Request(proxy_url='socks5://socks.zaborona.help:1488') client = Client(request=request) query = artist + " " + title search_result = client.search(query) if len(search_result['tracks']['results']) != 0: best = search_result['tracks']['results'][0] full_id = best.track_id.split(':') album_id = full_id[1] track_id = full_id[0] return "https://music.yandex.ru/album/" + album_id + "/track/" + track_id else: return "None"
def __init__(self, bot: Bot, yandex_client: Client = None): self.bot = bot if yandex_client is None: yandex_client = Client() self.yandex_client = yandex_client self.players = YandexAudioPlayerPool()
def doLogin(settings, username, password): try: token = Client().generate_token_by_username_and_password(username, password) settings.setSetting('token', token) return True except Unauthorized as ex: return False except BadRequest as ex: return False
def __init__(self,log,pas): client = captcha_key = captcha_answer = None while not client: try: client = Client.from_credentials(log,pas,captcha_answer,captcha_key) except Captcha as e: e.captcha.download('captcha.png') captcha_key = e.captcha.x_captcha_key captcha_answer = input('Число с картинки:') self.client = client
def text(message): if 'https://music.apple.com' in message.text: # print(message.text) resp = requests.get(message.text, verify=False).text soup = BeautifulSoup(resp, 'lxml') ex = 0 # определяем музыканта [ ,альбом] [, название композиции] try: musician = ' '.join(soup.find('div', {'class': 'product-creator typography-large-title'}).text.strip().split()) except: musician = ' '.join(soup.find('h1', {'class': 'typography-header-emphasized artist-header__product-title-product-name artist-header__product-title-product-name--non-persistent-color'}).text.strip()) try: album = ' '+soup.find('h1', {'class': 'product-name typography-large-title-semibold clamp-4'}).text.strip() except: album = '' try: select_track = ' '+soup.find('div', {'aria-checked': 'true'}).text.strip() tracks = soup.find_all('div', {'class': 'songs-list-row songs-list-row--selected selected songs-list-row--web-preview web-preview songs-list-row--song'}) for i in tracks: if 'aria-checked="true"' in str(i): index = int(i['data-row']) #если мы даём ссылку на конкретную композицию, то скачаем и отправим в чат 1,5минутный отрывок example = soup.find('script', {'id': 'shoebox-media-api-cache-amp-music'}).text.replace('\\', '') example = re.findall('(https://audio-ssl.itunes.apple.com/[^"]+)', example)[index] example = requests.get(example, verify=False).content ex = 1 except: select_track = '' # print(musician, album, select_track) #yandex ym_service = YMClient() search_result = ym_service.search(musician+album+select_track) if select_track!='': yalink = f"https://music.yandex.ru/track/{search_result['tracks']['results'][0]['id']}" elif album!='': yalink = f"https://music.yandex.ru/album/{search_result['albums']['results'][0]['id']}" else: yalink = f"https://music.yandex.ru/artist/{search_result['artists']['results'][0]['id']}" #spoty head = { 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"', 'sec-ch-ua-mobile': '?0', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36' } resp = requests.get(f'https://open.spotify.com/search/{musician}{album}{select_track}', headers=head, verify=False).text soup = BeautifulSoup(resp, 'lxml') bearer = eval(soup.find('script').text.replace('true', 'True').replace('false','False').replace('null','None').strip())['accessToken'] head = {'authorization':f'Bearer {bearer}'} resp = requests.get(f'https://api.spotify.com/v1/search?type=album%2Cartist%2Cplaylist%2Ctrack%2Cshow_audio%2Cepisode_audio&q={musician}+{album}+{select_track}&decorate_restrictions=false&best_match=true&include_external=audio&limit=10&market=RU', headers=head, verify=False).json() try: if select_track!='': spoty = resp['tracks']['items'][0]['external_urls']['spotify'] elif album!='': spoty = resp['albums']['items'][0]['external_urls']['spotify'] else: spoty = resp['artists']['items'][0]['external_urls']['spotify'] except: spoty = '' while True: try: if spoty!='': bot.reply_to(message, f"<a href='{yalink}'>ссылка на Яндекс.Музыку\n</a><a href='{spoty}'>ссылка на Spotify</a>", parse_mode='html', disable_web_page_preview=True) else: #spotify хуже справляется с поиском bot.reply_to(message, f"<a href='{yalink}'>ссылка на Яндекс.Музыку</a>", parse_mode='html', disable_web_page_preview=True) if ex==1: bot.send_audio(message.chat.id, example) break except: pass
def authorization_token(self, token): try: self.client = Client.from_token(token) except Exception as e: logging.getLogger(e.args[0])
class GoYandex(): def __init__(self, setting): self.client = Client() super().__init__() self.select_PL = None self.start_load_Pl = False self.start_download = False self.this = None self.list_track = [] self.setting = setting self.play_lists_info = dict() def generate_token(self, login, pas): try: token = self.client.generate_token_by_username_and_password( username=login, password=pas) self.setting.save('token', token) return False except Exception as e: if e.args[0].startswith('invalid_grant'): err = e.args[0][14:] logging.getLogger(err) else: err = e.args[0] logging.getLogger(err) return err def authorization_token(self, token): try: self.client = Client.from_token(token) except Exception as e: logging.getLogger(e.args[0]) def get_play_lists_info(self): # FIXME: убрать после теста долгой загрузки # time.sleep(5) # run in Thread try: personal_playlist_blocks = self.client.landing( blocks=['personalplaylists']).blocks[0] except Exception as e: logging.getLogger(e.args[0]) return False for plLst in personal_playlist_blocks.entities: if plLst.data.data.play_counter is not None: pc = plLst.data.data.play_counter pc.description = pc.description.replace(' ', ' ') pc.description = pc.description.replace('—', '–') self.play_lists_info[ plLst.data.data.generated_playlist_type] = plLst.data.data return True def get_play_list(self): # run in Thread if not self.get_play_lists_info(): return if self.this.play_list_type not in self.play_lists_info: # FIXME: выбрать поле для вывода информации print('Не удалось найти плейлист') logging.getLogger('Не удалось найти плейлист') self.start_load_Pl = False return daily_play_list = self.play_lists_info[self.this.play_list_type] self.list_track.clear() self.select_PL = self.client.users_playlists( user_id=daily_play_list.uid, kind=daily_play_list.kind) plTitle = self.select_PL[0].title plCount = self.select_PL[0].track_count self.this.set_title(plTitle) for counter, track in enumerate(self.select_PL[0].tracks, 1): self.list_track.append(track.track) self.this.set_title(f'{plTitle} - {counter}/{plCount}') if self.this.play_list_type != 'podcasts': try: artist = track.track.artists[0].name except IndexError: artist = '<BREAK>' else: artist = track.track.albums[0].title self.this.add_row(counter, track.track.title, artist, utils.timeStr(track.track.duration_ms)) if not self.start_load_Pl: self.this.set_title(f'{plTitle} - {counter}/{plCount} - BREAK') break else: duration = utils.timeStr(self.select_PL[0].duration_ms, 0) self.this.set_title(f'{plTitle} - {duration}') self.this.set_normal_status() self.start_load_Pl = False def save_tracks(self): ''' Скачивание треков и задание id3-тегов ''' # run in Thread self.this.show_prigress_bar() self.this.set_prigress_bar(0) for num, track in enumerate(self.list_track, 1): if self.this.play_list_type != 'podcasts': if len(track.artists): artist = track.artists[0].name else: artist = '' else: artist = track.albums[0].title path = self.this.get_path() file_name = f'[{track.real_id}] {artist} - {track.title}' file_name = utils.delSpecCh(file_name) file_name = f'{path}{file_name}.mp3' print(file_name) if os.path.isfile(file_name): # Трек уже скачан и находится в папке self.this.set_prigress_bar((num / len(self.list_track)) * 100) continue track.download(file_name) # FIXME add exception () mp3file = MetadataMP3(file_name) mp3file.set_tags( artist=artist, title=track.title, album=track.albums[0].title, # FIX track_num=track.albums[0].track_position.index, year=track.albums[0].year, genre=track.albums[0].genre) mp3file.set_image(track.og_image) mp3file.save() self.this.set_prigress_bar((num / len(self.list_track)) * 100) if not self.start_download: # Пользователь прервал скачивание break self.this.set_normal_status() self.this.hide_prigress_bar() self.start_download = False
class YandexMusic(MusicService): name = "YandexMusic" def __init__(self): self.client = Client() self.url_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/album\/([0-9]+)\/track\/([0-9]+)' ) self.url_without_album_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/track\/([0-9]+)' ) self.url_artist_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/artist\/([0-9]+)' ) self.url_album_regex = re.compile( r'((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/album\/([0-9]+)' ) # link example: https://music.yandex.ru/album/43233/track/418016 # regex: ((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/album\/([0-9]+)\/track\/([0-9]+) # link example: https://music.yandex.ru/track/418016 # regex: ((http|https)://)?(www\.)?music\.yandex\.(ru|com)\/track\/([0-9]+) @staticmethod def get_track_id_from_match(match): return match[6] + ":" + match[5] @staticmethod def get_entity_id_from_match(match): return match[5] def search_track_by_link(self, link): match = self.url_regex.match(link) if not match is None: track_id = self.get_track_id_from_match(match) else: match = self.url_without_album_regex.match(link) if match is None: return None track_id = self.get_entity_id_from_match(match) tracks = self.client.tracks([track_id]) if len(tracks) == 0: return None else: track = tracks[0].title artists = [artist.name for artist in tracks[0].artists] album = tracks[0].albums[0].title if len( tracks[0].albums) != 0 else None return track, artists, album, self._get_entity_id( track_id, self.Entity.Track) def search_track(self, track, artists, album=None): query = ', '.join(artists) + " - " + track result = self.client.search(text=query, type_='track') if not result.tracks or result.tracks.total == 0: return None id = result.tracks.results[0].track_id if id.find(":") != -1: track_id, album_id = id.split(':') return "https://music.yandex.ru/album/%s/track/%s" % (album_id, track_id) else: return "https://music.yandex.ru/track/%s" % id def search_track_by_query(self, query, limit=None): if not limit: limit = self.default_limit result = self.client.search(text=query, type_='track') if not result.tracks or result.tracks.total == 0: return [] tracks = result.tracks.results[:limit] track_list = [] for track in tracks: track_json = { 'track': track.title, 'artists': [artist.name for artist in track.artists], } if len(track.track_id.split(':')) == 2: track_id, album_id = track.track_id.split(':') track_json[ 'url'] = "https://music.yandex.ru/album/%s/track/%s" % ( album_id, track_id) else: track_json[ 'url'] = "https://music.yandex.ru/track/%s" % track.track_id if track.albums and len(track.albums) > 0: track_json['album'] = track.albums[0].title track_list.append(track_json) response = {'service_name': self.name, 'tracks': track_list} return response # https://music.yandex.ru/artist/41126 def search_artist_by_link(self, link): match = self.url_artist_regex.match(link) if match: artist_id = self.get_entity_id_from_match(match) else: return None artists = self.client.artists(artist_id) if len(artists) == 0: return None else: return artists[0].name, self._get_entity_id( artist_id, self.Entity.Artist) def search_artist(self, name): result = self.client.search(text=name, type_='artist') if not result.artists or result.artists.total == 0: return None artist_id = result.artists.results[0].id return "https://music.yandex.ru/artist/%s" % artist_id # https://music.yandex.ru/album/14619914 def search_album_by_link(self, link): match = self.url_album_regex.match(link) if match: album_id = self.get_entity_id_from_match(match) else: return None albums = self.client.albums(album_id) if len(albums) == 0: return None else: return albums[0].title, self._get_entity_id( album_id, self.Entity.Album) def search_album(self, name): result = self.client.search(text=name, type_='album') if not result.albums or result.albums.total == 0: return None album_id = result.albums.results[0].id return "https://music.yandex.ru/album/%s" % album_id def detect_entity_by_link(self, link): if link.find("track") != -1: return self.Entity.Track elif link.find('album') != -1: return self.Entity.Album elif link.find('artist') != -1: return self.Entity.Artist else: return None @staticmethod def _entity_type_to_string(entity: MusicService.Entity): if entity == MusicService.Entity.Album: return "album" elif entity == MusicService.Entity.Track: return "track" elif entity == MusicService.Entity.Artist: return "artist" else: return None @staticmethod def _extract_track_data(track_json): album = track_json.albums[0].title if track_json.albums and len( track_json.albums) > 0 else track_json.title return { 'track': track_json.title, 'album': album, 'artists': [artist.name for artist in track_json.artists], 'url': "https://music.yandex.ru/track/%s" % track_json.track_id } @staticmethod def _extract_album_data(album_json): return { 'album': album_json.title, 'artists': [artist.name for artist in album_json.artists], 'url': "https://music.yandex.ru/album/%s" % album_json.id } @staticmethod def _extract_artist_data(artist_json): return { 'artist': artist_json.name, 'url': "https://music.yandex.ru/artist/%s" % artist_json.id } @staticmethod def _extract_search_data(data_json, entity): if entity == MusicService.Entity.Album: return YandexMusic._extract_album_data(data_json) elif entity == MusicService.Entity.Track: return YandexMusic._extract_track_data(data_json) elif entity == MusicService.Entity.Artist: return YandexMusic._extract_artist_data(data_json) else: return None def search_by_query(self, query, entity: MusicService.Entity, limit=MusicService.default_limit): entity_str = self._entity_type_to_string(entity) if not entity_str: return None plural_entity_str = entity_str + "s" entity_list = [] count = limit page = 0 while count > 0: results = self.client.search(text=query, type_=entity_str, page=page) if results[plural_entity_str].results is None: return None results = results[plural_entity_str].results[:count] if len(results) == 0: break for result in results: entity_list.append(self._extract_search_data(result, entity)) count -= 1 page += 1 response = {'service_name': self.name, plural_entity_str: entity_list} return response
def client(): return Client()
import os from yandex_music import Client TOKEN = os.environ.get('TOKEN') client = Client(TOKEN) queues = client.queues_list() # Последняя проигрываемая очередь всегда в начале списка last_queue = client.queue(queues[0].id) last_track_id = last_queue.get_current_track() last_track = last_track_id.fetch_track() artists = ', '.join(last_track.artists_name()) title = last_track.title print(f'Сейчас играет: {artists} - {title}') supplement = last_track.get_supplement() if supplement.lyrics: print(supplement.lyrics.full_lyrics) else: print('Текст песни отсутствует')
if args.print_args: print(args) sys.exit() if type(args.token) is str and re.match(r'^[A-z0-9]{39}$', args.token): if not args.no_save_token: parser.get_default('token').write_text(args.token) else: try: args.token = Path(args.token).read_text() except FileNotFoundError: print('Config file not found. Use --token to create it') sys.exit(2) client = Client.from_token(args.token, report_new_fields=False) print('Hello,', client.me.account.first_name) if client.me.account.now and client.me.account.now.split( 'T')[0] == client.me.account.birthday: print('Happy birthday!') if args.playlist == 'user': user_playlists = client.users_playlists_list() if not args.playlist_name: print('specify --playlist-name', list(p.title for p in user_playlists)) sys.exit(1) playlist = next( (p for p in user_playlists if p.title == args.playlist_name), None) if playlist == None: print(f'playlist "{args.playlist_name}" not found')
import os from yandex_music import Client TOKEN = os.environ.get('TOKEN') ALBUM_ID = 2832563 client = Client(TOKEN) success = client.users_likes_albums_add(ALBUM_ID) answer = 'Лайкнут' if success else 'Произошла ошибка' print(answer) success = client.users_likes_albums_remove(ALBUM_ID) answer = 'Дизлайкнут' if success else 'Произошла ошибка' print(answer) # Тоже самое и в другими сущностями (плейлист, трек, исполнитель) # client.users_likes_playlists_add(f'{user_id}:{playlist_id}') # client.users_likes_playlists_remove(f'{user_id}:{playlist_id}') # client.users_likes_tracks_add(track_id) # client.users_likes_tracks_remove(track_id) # и т.д. Читайте документацию.
import os from yandex_music import Client # без авторизации недоступен список треков альбома TOKEN = os.environ.get('TOKEN') ALBUM_ID = 2832563 client = Client(TOKEN) album = client.albums_with_tracks(ALBUM_ID) tracks = [] for i, volume in enumerate(album.volumes): if len(album.volumes) > 1: tracks.append(f'💿 Диск {i + 1}') tracks += volume text = 'АЛЬБОМ\n\n' text += f'{album.title}\n' text += f"Исполнитель: {', '.join([artist.name for artist in album.artists])}\n" text += f'{album.year} · {album.genre}\n' cover = album.cover_uri if cover: text += f'Обложка: {cover.replace("%%", "400x400")}\n\n' text += 'Список треков:' print(text) for track in tracks:
import discord import datetime import sqlalchemy import sqlalchemy.orm as orm from imgurpython import ImgurClient from sqlalchemy.orm import Session import sqlalchemy.ext.declarative as dec from data import db_session from data.users import User import os from yandex_music import Client TOKEN = '' YM_TOKEN = '' prefix = '-' ya_music = Client.from_token(YM_TOKEN) def get_my_files(content): f = io.BytesIO(content) my_files = [ discord.File(f, "tmpcat.jpg"), ] return my_files class YLBotClient(discord.Client): def __init__(self): super().__init__() self.timers = [] self.queue = asyncio.Queue()
help='Token from music.yandex.com account') parser.add_argument('-i', '--ignore', nargs='+', help='Don\'t import some items', choices=['likes', 'playlists', 'albums', 'artists'], default=[]) arguments = parser.parse_args() auth_manager = SpotifyOAuth( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI, scope= 'playlist-modify-public, user-library-modify, user-follow-modify, ugc-image-upload', username=arguments.spotify) spotify_client_ = spotipy.Spotify(auth_manager=auth_manager) if arguments.login and arguments.password: yandex_client_ = Client.from_credentials(arguments.login, arguments.password, captcha_callback=proc_captcha) elif arguments.token: yandex_client_ = Client(arguments.token) else: raise RuntimeError('Provide yandex account conditionals or token!') Importer(spotify_client_, yandex_client_, arguments.ignore).import_all()
from yandex_music import Client _login = "" _passwd = "" client = Client.from_credentials(username=_login, password=_passwd)
import os from yandex_music import Client from yandex_music.exceptions import YandexMusicError from yandex_music.utils.request import Request yandex_music_token = os.environ.get('YANDEX_MUSIC_TOKEN') proxied_request = Request(proxy_url=os.environ.get('PROXY_URL')) try: if not yandex_music_token: raise YandexMusicError() # подключаемся без прокси для получения информации об аккаунте (доступно из других стран) client = Client(yandex_music_token, request=Request()) # проверяем отсутствие подписки у пользователя if client.me and client.me.plus and not client.me.plus.has_plus: # если подписки нет - пересоздаем клиент с использованием прокси client = Client(yandex_music_token, request=proxied_request) except YandexMusicError: # если есть проблемы с авторизацией, токеном или чем-либо еще, то инициализируем клиент без авторизации # так как сервисом можно пользоваться будучи гостем, но со своими ограничениями client = Client(request=proxied_request, fetch_account_status=False)
from math import floor from random import random from time import sleep from yandex_music import Client from radio import Radio # API instance client = Client(token="YOUR_TOKEN_HERE") # Get random station _stations = client.rotor_stations_list() _station_random_index = floor(len(_stations) * random()) _station = _stations[_station_random_index].station _station_id = f'{_station.id.type}:{_station.id.tag}' _station_from = _station.id_for_from # Radio instance radio = Radio(client) # start radio and get first track first_track = radio.start_radio(_station_id, _station_from) print("[Radio] First track is:", first_track) # get new track every 5 sec while True: sleep(5) next_track = radio.play_next() print("[Radio] Next track is:", next_track)
from yandex_music import Client client = Client() type_to_name = { 'track': 'трек', 'artist': 'исполнитель', 'album': 'альбом', 'playlist': 'плейлист', 'video': 'видео', 'user': '******', 'podcast': 'подкаст', 'podcast_episode': 'эпизод подкаста', } def send_search_request_and_print_result(query): search_result = client.search(query) text = [f'Результаты по запросу "{query}":', ''] best_result_text = '' if search_result.best: type_ = search_result.best.type best = search_result.best.result text.append(f'❗️Лучший результат: {type_to_name.get(type_)}') if type_ in ['track', 'podcast_episode']: artists = '' if best.artists:
# Picture 'APIC': APIC(encoding=3, text=cover_filename, data=open(cover_filename, 'rb').read()) }) lyrics = client.track_supplement(track.track_id).lyrics if lyrics: # Song lyrics file.tags.add(USLT(encoding=3, text=lyrics.full_lyrics)) file.save() os.chdir(pwd) print("done") if __name__ == "__main__": folder = os.path.normpath(FOLDER) os.makedirs(folder, exist_ok=True) os.chdir(folder) pwd = os.getcwd() client = Client.from_credentials(LOGIN, PASSWORD) liked_by_plist = client.users_playlists(kind=3) if liked_by_plist: download_playlist(liked_by_plist[0]) else: print("`Liked by me` list is empty")
import os from yandex_music import Client CHART_ID = 'world' TOKEN = os.environ.get('TOKEN') client = Client(TOKEN) chart = client.chart(CHART_ID).chart text = [f'🏆 {chart.title}', chart.description, '', 'Треки:'] for track_short in chart.tracks: track, chart = track_short.track, track_short.chart artists = '' if track.artists: artists = ' - ' + ', '.join(artist.name for artist in track.artists) track_text = f'{track.title}{artists}' if chart.progress == 'down': track_text = '🔻 ' + track_text elif chart.progress == 'up': track_text = '🔺 ' + track_text elif chart.progress == 'new': track_text = '🆕 ' + track_text elif chart.position == 1: track_text = '👑 ' + track_text track_text = f'{chart.position} {track_text}' text.append(track_text)
def client(): return Client(fetch_account_status=False)