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.ERROR)

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]
#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"%(pl.title, datetime.datetime.fromisoformat(pl.modified).strftime('%d/%m/#%Y'), pl.track_count))  # .encode().decode('cp1251')
Example #2
0
# не забывать добавлять все через yandex аккаунт (не через авторизацию через google)
from yandex_music.client import Client
print('Start')
print('\n----------\n')

client = Client.from_credentials('*****@*****.**', '281987hillhald')

box = client.users_likes_playlists()[0]
box2 = client.users_playlists(kind=1000, user_id=785279921)
for ind, music in enumerate(box2[0].tracks):
    find_track = client.tracks(
        ['{}:{}'.format(music['id'], music['album_id'])])[0]
    name_track = "{ind}.{artists} - {title}".format(
        ind=ind + 1,
        artists=find_track['artists'][0]['name'],
        title=find_track['title'])
    music.track.download('The Walking Dead Album/{name_track}.mp3'.format(
        name_track=name_track))
    print('Download {name_track}, success'.format(name_track=name_track))

# box[11].track.download('{artist_name} - {music_name}.mp3'.format(artist_name=box[11].track['artists'][0]['name'], music_name=box[11].track['title']))
# text = ''
# for ind, item in enumerate(box):
#     music_name = '{ind}.{artist_name} - {music_name}\n'.format(ind=ind, artist_name=box[ind].track['artists'][0]['name'], music_name=box[ind].track['title'])
#     text += music_name
print('\n----------\n')
print('Done')
Example #3
0
 def get_auth(self):
     self.client = Client.from_credentials(self.login, self.password)
from yandex_music.client import Client
import requests
from lxml.html import fromstring

client = Client.from_credentials('login', 'password')

url_1 = ("https://music.yandex.ru/album/")
url_2 = ("/track/")

for tracks in client.users_likes_tracks():
    track = tracks.track_id.split(":")
    url = url_1 + track[1] + url_2 + track[0]
    r = requests.get(url)
    tree = fromstring(r.content)
    list_track = tree.findtext('.//title').split(".")
    tracks.track.download(list_track[0] + ".mp3")
    
# Если делать GUI, то для ProgressBar требуется знать конечное количество треков
# Тогда можно в отдельном цикле добавить их в список не скачивая и получить количество треков - длина списка
# Далее len(list) будет крайним значением для ProgressBar
# Но для этого надо сначала прогнать цикл подсчета в GUI с растущим числом и потом активировать кнопку "скачать"
# Также можно сделать динамическое отображение найденных треков в специальном окне формы
            axis=1)  # удаляем получающуюся после импорта лишнюю колонку
        new_csv = pd.concat([old_csv, yandex_daily_avg],
                            ignore_index=True,
                            sort=False)
        new_csv.reset_index(inplace=True)
        new_csv.drop(new_csv.columns[[0]], axis=1, inplace=True)
        new_csv.to_csv("all_yandex.csv", encoding="utf-8")


# In[ ]:

# создаем словарь жанров
try:
    from yandex_music.client import Client
    client = Client()
    client = Client.from_credentials('*****@*****.**',
                                     'aintthateasy')

    gs = client.genres()

    keys = []
    values = []

    # создаем полный словарь
    for i in range(0, len(gs)):
        if len(gs[i].sub_genres) == 0:
            values.append(gs[i].titles["ru"]["title"])
            keys.append(gs[i].id)
        else:
            values.append(gs[i]["title"])
            keys.append(gs[i].id)
            for j in range(0, len(gs[i].sub_genres)):
Example #6
0
 def __init__(self, login: str, password: str):
     self.client = Client.from_credentials(login, password)
Example #7
0
def get_ya_music_client(user=None) -> Client:
    login = user or input(color.y('Yandex login: '******'Password / One time password (from Yandex.Key): '))
    echo.y('logging...', end='\r')
    return Client.from_credentials(login, password)
        return json.load(config_file)


config = open_config()

# Параметры для входа.
vk_id = config[0]["vk_id"]
vk_token = config[0]["vk_token"]

# Команды.
statusUpdate = config[2]["statusUpdate"]
startSymbolUpdate = config[2]["startSymbolUpdate"]
endSymbolUpdate = config[2]["endSymbolUpdate"]

# Авторизация в Яндекс Музыке
client = Client.from_credentials(config[0]["yandexLogin"],
                                 config[0]["yandexPassword"])

# Авторизация во вконтакте.
vkSession = vk_api.VkApi(token=vk_token)
longpoll = VkLongPoll(vkSession)
vk = vkSession.get_api()

# Временные переменные (нужны для обхода капчи и смены статуса на обычный, если музыка осталась той же).
lastSong = 0
lastSongName = ""
afk = False


# Обработчик команд в вк.
def commandChecker():
    for event in longpoll.listen():
Example #9
0
                else:
                    time.sleep(20)
            except:
                time.sleep(5)
                print(traceback.format_exc())

    def unfreeze(self):
        self.freezed = False
        self.pause()


if __name__ == "__main__":
    assert LOGIN and PASSWORD and DOWNLOADS_FOLDER, "SETTINGS ARE NOT CORRECT"
    while True:
        try:
            client = Client.from_credentials(LOGIN, PASSWORD)
            break
        except:
            print(traceback.format_exc())
            time.sleep(30)
    player = Player(DOWNLOADS_FOLDER, client)

    schedule.every().day.at(TIME_OF_DOWNLOAD).do(
        player.download_playlist,
        client_obj=client,
        downloads_folder=DOWNLOADS_FOLDER)
    schedule.every().day.at(TIME_OF_DELETE).do(player.delete_playlist)
    schedule.every().day.at(TIME_OF_PREPARE).do(player.prepare_playlist)

    schedule.every().day.at(TIME_OF_WAKE_UP).do(player.wake_me_up)
    schedule.every().day.at(TIME_OF_WAKE_UP_UNTIL).do(player.unfreeze)
Example #10
0
from yandex_music.client import Client
from TOKEN import mail, password
import discord

user = Client.from_credentials(mail, password)


class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        print('Message from {0.author}: {0.content}'.format(message))


client = MyClient()
client.run('my token goes here')
Example #11
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
from yandex_music.client import Client
import datetime
import re

client = Client.from_credentials(os.environ['LOGIN'], os.environ['PASSWORD'])

# get previous day
yesterday = datetime.date.today() - datetime.timedelta(days=1)

# get liked tracks for selected month and year
tracks = []
for track in client.users_likes_tracks():
    date = datetime.datetime.fromisoformat(track.timestamp)
    if date.year == yesterday.year and date.month == yesterday.month:
        tracks.append(track)
    else:
        break

# create a new playlist if needed
if len(tracks) == 0:
    print('No tracks')
else:
    months = [
        'январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август',
        'сентябрь', 'октябрь', 'ноябрь', 'декабрь'
    ]
    playlist = client.usersPlaylistsCreate("Лайки за {} {}".format(