def startDownloading(): downloaded_arr = [] downloaded_file = open('downloaded.txt', 'r+') for line in downloaded_file: downloaded_arr.append(int(line)) downloaded_file.close() downloaded_file_a = open('downloaded.txt', 'a+') print("Feching metadata...") try: client = Client.from_credentials(YA_LOGIN, YA_PASS) except CaptchaRequired as e: print(e.captcha.x_captcha_url) captchaKey = input("Entered captcha value: ") print(captchaKey) client = Client.from_credentials(YA_LOGIN, YA_PASS, captchaKey, e.captcha.x_captcha_key) playlists = client.users_playlists_list(); for playlist in playlists: kind = playlist.kind playlistData = client.users_playlists(kind)[0] tracks = playlistData.tracks for track in tracks: if track.id in downloaded_arr: continue trackData = track.track downloaded_file_a.write(str(track.id)) downloaded_file_a.write("\n") downloaded_arr.append(track.id) downloadTrack(trackData) time.sleep(5)
def init_client(login=None, password=None, token=None, captcha_answer=None, captcha_key=None): client = captcha = None if token: try: client = Client.from_token(token) except BaseException as ex: client = None if login and password: try: client = Client.from_credentials(login, password, captcha_answer, captcha_key) except Captcha as e: captcha_key = e.captcha.x_captcha_key e.captcha.download( 'ymapp/static/captchas/{}_captcha.png'.format(captcha_key)) captcha = { 'file': '/static/captchas/{}_captcha.png'.format(captcha_key), 'cp_key': captcha_key } except BaseException as ex: flash(str(ex)) return client, captcha
def add_tracks(client: Client, tracks: tp.List[Track], playlist_name=None, like=False, reversed_order=False): if not tracks: echo.y('No tracks to add') return set() echo.g(f"Adding tracks to playlist: {playlist_name} {'and like' if like else ''} {len(tracks)}") p = create_playlist(client, name=playlist_name) error_tracks = set() for track in tracks if reversed_order else reversed(tracks): echo.c(f'Insert track: {track.artist} - {track.title} to {playlist_name}', end=' ') try: p = create_playlist(client, name=playlist_name) p = client.users_playlists_insert_track(p.kind, track.id, track.album_id, revision=p.revision) except NetworkError: p = None if p is None: echo.r('NOT OK') p = create_playlist(client, name=playlist_name) error_tracks.add(track) else: echo.g('OK') if like: echo.c(f'Like: {track.artist} - {track.title}', end=' ') if not client.users_likes_tracks_add(track.id): echo.r('NOT OK') error_tracks.add(track) else: echo.g('OK') echo.g('Complete!') return error_tracks
def get_client(token_file, credentials_file): token = read_json(token_file)['token'] cl = Client.from_token(token) if cl.me.account.login is None: token = generate_token(credentials_file) # TODO: ask user for input save_json(token_file, wrap_token(token)) cl = Client.from_token(token) return cl
def add_song_to_playlist(client: Client, playlist_kind: str or int, full_track_ids: str or List[str]): if isinstance(full_track_ids, list): for i, full_track_id in enumerate(full_track_ids): track_id, album_id = full_track_id.split(':') print(i) playlist = client.users_playlists_insert_track(playlist_kind, track_id, album_id, revision=i + 1) if playlist is None: print(f"Cant add {full_track_id} to playlist") else: track_id, album_id = full_track_ids.split(':') client.users_playlists_insert_track(playlist_kind, track_id, album_id)
def login(self, login=None, password=None): if self.conf.get_attr("token") is not False: client = Client().from_token(self.conf.get_attr("token")) elif login is not None and password is not None: client = Client().from_credentials(login, password) token = client.token self.conf.set_attr("token", token) else: client = Client() self.client = client return client
def init(self): if os.path.isfile('token.txt'): try: tokenFile = open('token.txt', 'r') self.token = tokenFile.read() tokenFile.close(); self.client = Client(self.token) self.loggedIn = True except: print("Failed to create client using saved token. Enter your login/password.") self.login() else: self.login()
def main(): print("Loading...") downloaded_arr = [] downloaded_file = open('downloaded.txt', 'r+') for line in downloaded_file: downloaded_arr.append(int(line)) downloaded_file.close() downloaded_file_a = open('downloaded.txt', 'a+') print("Feching metadata...") client = Client.from_credentials(YA_LOGIN, YA_PASS) playlists = client.users_playlists_list() for playlist in playlists: kind = playlist.kind playlistData = client.users_playlists(kind)[0] tracks = playlistData.tracks for track in tracks: if track.id in downloaded_arr: continue trackData = track.track downloaded_file_a.write(str(track.id)) downloaded_file_a.write("\n") downloaded_arr.append(track.id) downloadTrack(trackData) time.sleep(5)
def remove_playlist_duplicates(client: Client, playlist_name='VK2YA') -> Playlist: echo.c(f'Removing duplicates from playlist: {playlist_name}') p = create_playlist(client, playlist_name) unique_tracks = set() while len(p.tracks) != len(unique_tracks): was_len = len(p.tracks) unique_tracks = set() for i, t in enumerate(p.tracks): if t.id in unique_tracks: echo.y(f'Duplicate found: {t.track.artists[0].name} - {t.track.title}, removing') client.users_playlists_delete_track(p.kind, i, i+1, revision=p.revision) p = create_playlist(client, playlist_name) break unique_tracks.add(t.id) if was_len == len(p.tracks): break # recurse
def import_pl(): spotify_manager = SpotifyManager() spotify_manager.auth() client = Client.from_token(session.get('yandex_token')) ids = request.form.getlist('for_import[]') if ids: import_data = [] for id in ids: try: playlist = client.users_playlists(kind=id) except BadRequest: flash("Не удалось выполнить запрос в Яндекс.Музыке") else: track_ids = [track['id'] for track in playlist[0].tracks] if track_ids: tracks = client.tracks(track_ids) import_data.append({ "name": playlist[0].title, "description": "Yandex.Music", "tracks": tracks }) result = spotify_manager.import_playlists(import_data) else: flash("Не заданы ID плейлистов для импорта!") times = css_js_update_time() return render_template('index.html', result=result, progress=100, spotify_data=spotify_manager.user_data, times=times)
def __init__(self, token): self.client = Client.from_token(token) self.liked_tracks_dict = OrderedDict() self.liked_tracks_list = list() self.tracks = self.client.users_likes_tracks() self.load_liked_tracks_json() self.settings_dict = {}
def init(self): if os.path.isfile('token.txt'): try: tokenFile = open('token.txt', 'r') self.token = tokenFile.read() tokenFile.close() self.client = Client(self.token) self.loggedIn = True self.online = True except: return False else: return False return True
def init_client(): def process_captcha(captcha: Captcha) -> str: captcha.download('captcha.png') return input('Enter the number from picture: ') return Client.from_credentials(USER_LOGIN, USER_PASS, captcha_callback=process_captcha)
class YaMusic: cache_path = "ya_cache.json" def __init__(self): logger.level = logging.ERROR self.client = Client() self.cache = {} self.load_cache() self.i = 0 def load_cache(self): if not os.path.exists(self.cache_path): return with open(self.cache_path, "r") as file: d = json.load(file) for key, value in d.items(): self.cache[key] = Music.from_json(value) def save_cache(self): d = {} for key, value in self.cache.items(): d[key] = value.to_json() with open(self.cache_path, "w") as file: json.dump(d, file) def get_song(self, name, author): title = "{} - {}".format(author, name) song = self.cache.get(title, None) if song: return song self.i += 1 if self.i > 50: self.save_cache() self.i = 0 song = self.client.search(title).best if song is None or type(song.result) is not Track: music = Music() music.name = name music.author = [author] self.cache[title] = music return music song = song.result music = Music() music.duration = song.duration_ms music.name = song.title music.author = [a.name for a in song.artists] music.year = song.albums[0].year or song.albums[ 0].release_date if song.albums else None music.genres = [a.genre for a in song.albums if a.genre] for i in music.genres: if i not in all_genres: print(i) self.cache[title] = music return music
def try_cached_auth(self, config): token = self.get_token() if token: logging.info("Trying to login with previously saved token.") try: self.client_obj = YamClient.from_token(token) except Exception as exc: logging.info("Could not login with token") logging.exception(exc) pass
def auth(self, login, password): try: self.client = Client.from_credentials( login, password, captcha_callback=self.proc_captcha) tokenFile = open('token.txt', 'w') tokenFile.write(self.client.token) tokenFile.close() self.loggedIn = True return True except Exception as e: return False
def login_V2(email, password): client1 = Client.fromCredentials(email, password) settings_dict = {} settings_dict["TOKEN"] = client1.token main_TOKEN = client1.token with open('settings.json', 'w') as fp: json.dump(settings_dict, fp) isLoggedIn = True if os.path.exists('tracks.json'): os.remove('tracks.json') return main_TOKEN
def try_auth(self, config): self.try_cached_auth(config) if self.client_obj: self.authenticated = True self.client_obj.logger.setLevel(logging.ERROR) return logging.info("Trying to authenticate with \"{}\" method.".format( config.auth_method)) if config.auth_method == YAMU_AUTH_METHOD_USERNAME: self.client_obj = YamClient.from_credentials( config.username, config.password, captcha_callback=self.handle_captcha) elif config.auth_method == YAMU_AUTH_METHOD_TOKEN: self.client_obj = YamClient.from_token(config.token) else: self.authenticated = False # It's the default, but setting explicitly just in case raise RuntimeError("Invalid authentication method: {}".format( config.auth_method)) self.authenticated = True self.write_token()
def __init__(self, username=None, password=None): self.__client = None token = None try: with open(YandexMusic.__cache_path, 'r', encoding='utf-8') as f: logger.debug(f'reading token: {YandexMusic.__cache_path}') token = f.read() except FileNotFoundError: pass if token is not None: self.__client = Client.from_token(token) else: logger.info(f'token not found, logging in: {username}') self.__client = Client.from_credentials(username, password) with open(YandexMusic.__cache_path, 'w', encoding='utf-8') as f: logger.debug(f'write token: {YandexMusic.__cache_path}') f.write(self.__client.token) login = self.__client.me.account.login logger.info(f'logged in: {login}') pl = self.__client.users_likes_tracks() favorites = YandexPlaylist('user likes', pl.tracks) logger.debug('loaded user favorites') playlists = [] for lst in self.__client.users_playlists_list(): pl = self.__client.users_playlists(lst.kind)[0] playlists += [YandexPlaylist(pl.title, pl.tracks, pl.visibility)] logger.debug('loaded user playlists') super().__init__(favorites, playlists)
def get_music_list(): content = request.json username = content['username'] password = content['password'] client = Client.from_credentials(username, password) user_music_l = client.users_likes_tracks().tracks l = list() for u in user_music_l: l.append(u.track.to_dict()) return Response(json.dumps(l, ensure_ascii=False), mimetype='application/json')
def login(self): self.loggedIn = False while not self.loggedIn: try: login = input("Login: "******"Password: "******"Login failed!") print(e)
def login(): print("Enter your email and password") email = input("Email:") password = input("Password:"******"TOKEN"] = client1.token main_TOKEN = client1.token with open('settings.json', 'w') as fp: json.dump(settings_dict, fp) isLoggedIn = True if os.path.exists('tracks.json'): os.remove('tracks.json') return main_TOKEN client1 = Ya_Client(main_TOKEN)
def our_func (user, password): client = Client.from_credentials (user, password) my_list = client.users_likes_tracks ().tracks a = '' for x in my_list: track = client.tracks (x.id)[0] title = track.title name = '' for artist in track.artists: name += artist.name + ', ' name = name[:-2] uri = track.cover_uri uri = uri[:-2] uri = 'http://' + uri + '400x400' # urllib.request.urlretrieve (uri, title + '.jpg') a += '{' + title + ' ~ ' + name + ' ~ ' + uri + '}' return a
def getNameTrack(self): '''Grab liked tracks from Yandex Music and create list of tracks and artists''' client = Client() client = Client.from_credentials(self.userYaLogin, self.userYaPassword) listLikesTacks = [] listIDLikesTacks = client.users_likes_tracks().tracksIds #List of tracks ID for ids in listIDLikesTacks: try: songName = client.tracks([ids])[0]['title'] singerName = client.tracks([ids])[0]['artists'][0]['name'] track_info = [] track_info.append(songName) track_info.append(singerName) listLikesTacks.append(track_info) print('ID: 'ids) except: print('Founed error with ID:', ids) pass return listLikesTacks
import sys import datetime from yandex_music.client import Client # Help text if len(sys.argv) == 1 or len(sys.argv) > 3: print('Usage: DailyPlaylistUpdater.py token') print('token - Authentication token') print('\nUsage: DailyPlaylistUpdater.py username password') print('username - username in format \'[email protected]\'') print('password - your password') quit() # Authorization elif len(sys.argv) == 2: client = Client.fromToken(sys.argv[1]) elif len(sys.argv) == 3: client = Client.fromCredentials(sys.argv[1], sys.argv[2]) # Current daily playlist PersonalPlaylistBlocks = client.landing(blocks=['personalplaylists']).blocks[0] DailyPlaylist = next( x.data.data for x in PersonalPlaylistBlocks.entities if x.data.data.generated_playlist_type == 'playlistOfTheDay') # Check if we don't need to update it if DailyPlaylist.play_counter.updated: modifiedDate = datetime.datetime.strptime(DailyPlaylist.modified, "%Y-%m-%dT%H:%M:%S%z").date() if datetime.datetime.now().date() == modifiedDate: print('\x1b[6;30;43m' + 'Looks like it has been already updated today' + '\x1b[0m')
import datetime import logging import sys from typing import List from yandex_music import Playlist from yandex_music.client import Client from yandex_music.utils.difference import Difference logger = logging.getLogger() logger.setLevel(logging.DEBUG) params = [sys.argv[1], sys.argv[2]] client = Client.from_credentials(params[0], params[1]) #listType = ['PlayListDaily','PlayListMissed', 'PlayListPremiere', 'PlayListDejavu', 'PlayListFamily'] listType = ['PlayListPremiere'] allPlaylists = client.usersPlaylistsList() fullPlayLists = [pl for pl in allPlaylists if pl.title in listType] for pl in fullPlayLists: tracks = pl.fetch_tracks() uniqueTracks = set() for i, track in enumerate(tracks): dirName = '.\\' + pl.title + '.\\' + track.track.track.track.title track.track.download() client.users_playlists_change(pl.kind, diff.to_json(), pl.revision) print("pl: %10s (%10s) - tracks: %3d deleted: %3d" % (pl.title, datetime.datetime.fromisoformat( pl.modified).strftime('%d/%m/#%Y'), pl.track_count,
await ctx.voice_client.disconnect() @play.before_invoke async def ensure_voice(self, ctx): if ctx.voice_client is None: if ctx.author.voice: await ctx.author.voice.channel.connect() else: await ctx.send("Вы не подключены к голосовому каналу.") raise commands.CommandError( "Author not connected to a voice channel.") bot = commands.Bot(command_prefix=commands.when_mentioned_or("m."), description='Relatively simple music bot example') @bot.event async def on_ready(): print('Logged in as {0} ({0.id})'.format(bot.user)) print('------') if cfg['YANDEX'].getboolean('use_token'): client = Client(cfg['YANDEX']['token']) else: client = Client.from_credentials(cfg['YANDEX']['login'], cfg['YANDEX']['password']) bot.add_cog(Music(bot)) bot.run(cfg['DISCORD']['token'])
class ArtistData: def __init__(self): self.artist = '' self.albums = [] self.brief_bio = '' self.genres = [] self.country = '' self.key = 0 NUM_ARTISTS = 1 ARTIST_IDS = [68227, 13002, 9367] countries = ['Великобритания', 'Германия', 'Швеция'] # Your login and password client = Client.from_credentials('', '') data = [] for i, ARTIST_ID in enumerate(ARTIST_IDS): obj = ArtistData() obj.key = i + 1 obj.country = countries[i] # artist, albums and genres collecting artists = client.artists(ARTIST_ID) for artist in artists: print(artist) obj.artist = artist.name albums_id = []
def execute_cmd(cmd): if cmd == 'ctime': # сказать текущее время locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8') now = datetime.datetime.now() speak("Сегодня "+str(now.day)+" "+ str(now.strftime('%B'))+" " + str(now.hour) + ":" + str(now.minute)) elif cmd == 'weather': gorod = 'Оренбург' owm = pyowm.OWM('165f33386df06f97d19787e3d780273a') observation = owm.weather_at_place(gorod) w = observation.get_weather() temperature = w.get_temperature('celsius')['temp'] speak("В городе " + gorod + " сейчас " + str(temperature) + "°С") elif cmd == 'browsing': text = r.recognize_google(audio, language='ru-RU') f_text = ('https://yandex.ru/search/?text=' + text()) webbrowser.open(f_text) elif cmd == 'organiser': url = 'https://calendar.yandex.ru/' webbrowser.open(url) elif cmd == 'alert': if re.search(r'\минут\b', r.recognize_google(audio, language='ru-RU')): dur = int(''.join(filter(str.isdigit, r.recognize_google(audio, language='ru-RU')))) dur *= 60 for i in range(dur, 0, -1): time.sleep(1) easygui.msgbox(r.recognize_google(audio,language='ru-RU')); if re.search(r'\секунд\b', r.recognize_google(audio, language='ru-RU')): dur = int(''.join(filter(str.isdigit, r.recognize_google(audio, language='ru-RU')))) for i in range(dur, 0, -1): time.sleep(1) easygui.msgbox(r.recognize_google(audio, language='ru-RU')); else: dur = int(''.join(filter(str.isdigit, r.recognize_google(audio, language='ru-RU')))) dur *= 3600 for i in range(dur, 0, -1): time.sleep(1) easygui.msgbox(r.recognize_google(audio, language='ru-RU')); elif cmd == 'music': mus = r.recognize_google(audio, language='ru-RU').lower() mus = mus.replace("включи музыку", "") mus = mus.replace("включи песню", "") mus = mus.replace("включи трек ", "") client = Client.from_credentials('*****@*****.**', 'roguedeal100ki11') client.search(mus).best.result.download('audio.mp3') os.system('audio.mp3') elif cmd =='video': url = r.recognize_google(audio, language= 'ru-RU').lower() url = url.replace("включи видео","") url = url.replace("открой видео", "") url = url.replace("поставь видео", "") webbrowser.open("www.youtube.com/results?search_query="+url) else: res.configure(text='Команда не распознана, повторите!')
async def yaplay(self, ctx, arg: str = None): if arg == None: if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title=f"Вы должны указать название трэка", color=0xff7606) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title=f"You must indicate the name of the track.", color=0xff7606) await ctx.send(embed=embed) return vol = 50 self.vol = vol voice = get(self.bot.voice_clients, guild=ctx.guild) try: channel = ctx.author.voice.channel except: if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title=f"**{ctx.author.name} Вы не в голосовом канале**", color=0xff7606) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title= f"**{ctx.author.name} You are not in the voice channel**", color=0xff7606) await ctx.send(embed=embed) return if voice and voice.is_connected(): await voice.move_to(channel) else: voice = await channel.connect() #Логирование (отключение) logger = logging.getLogger() logger.setLevel(logging.CRITICAL) #Подключенеи к акку request = Request(proxy_url="https://*****:*****@217.29.62.232:6333") client = Client(token=MusicBot.YANDEX_TOKEN, request=request) #Делаем поисковой запрос search = client.search(arg) #Получаем треки tracks = search.tracks #Сортируем треки в list results = tracks.results #Получаем первый трек track = results[0] #Получаем всю инфу по загрузке info = track.get_download_info(get_direct_links=True) #get_direct_links=True - обязательно надо, а то х*йня получается!!!!!!!!! try: #Получаем полный путь к музыкальному файлу (поток) self.playurl = info[0].direct_link self.voice = voice self.voice.play(discord.FFmpegPCMAudio(self.playurl)) self.voice.source = discord.PCMVolumeTransformer(voice.source) self.voice.source.volume = self.vol except: if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title= f"**{ctx.author.name} На данный момент песня уже играет**", color=0xff7606) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title= f"**{ctx.author.name} At the moment the song is already playing**", color=0xff7606) await ctx.send(embed=embed) return #Вызываем плеер if await MusicBot.langueg(ctx) == "RUS": embed = discord.Embed( title=f"**{track.title}**", description= f":white_small_square: **ID: {track.id} :game_die:**\n\n" f":white_small_square: **Регион: {track.regions[0]} :globe_with_meridians:**\n\n" f":white_small_square: **[Поделится](https://music.yandex.ru/track/{track.id}) :trumpet:**\n\n", color=0xf2a20d) # ~ embed.set_thumbnail(url=f"{cover_uri}") # ~ embed.set_image(url=f'{track.og_image}') embed.set_thumbnail( url= f"https://cdn.dribbble.com/users/851627/screenshots/2270820/record-player.gif" ) embed.set_footer( text= f"•Длительность трека: {int((track.duration_ms)/1000/60)} минут\n•Исполнитель: {track.artists[0].name}" ) elif await MusicBot.langueg(ctx) == "ENG": embed = discord.Embed( title=f"**{track.title}**", description= f":white_small_square: **ID: {track.id} :game_die:**\n\n" f":white_small_square: **Region: {track.regions[0]} :globe_with_meridians:**\n\n" f":white_small_square: **[Share](https://music.yandex.ru/track/{track.id}) :trumpet:**\n\n", color=0xf2a20d) # ~ embed.set_thumbnail(url=f"{cover_uri}") # ~ embed.set_image(url=f'{track.og_image}') embed.set_thumbnail( url= f"https://cdn.dribbble.com/users/851627/screenshots/2270820/record-player.gif" ) msg = await ctx.send(embed=embed) await msg.add_reaction(str("▶")) await msg.add_reaction(str("⏸")) await msg.add_reaction(str("🔊")) await msg.add_reaction(str("🔉")) await msg.add_reaction(str("⏹")) await msg.add_reaction(str("❤️")) self.msg_play = msg