示例#1
0
 def __init__(self,
              post,
              domain,
              session,
              sign_posts=False,
              what_to_parse=None):
     self.session = session
     try:
         self.audio_session = VkAudio(session)
     except IndexError:
         self.audio_session = None
     self.sign_posts = sign_posts
     self.pattern = "@" + sub(DOMAIN_REGEX, "", domain)
     self.raw_post = post
     self.post_url = "https://vk.com/wall{owner_id}_{id}".format(
         **self.raw_post)
     self.text = ""
     self.user = None
     self.repost = None
     self.repost_source = None
     self.reply_markup = None
     self.media = []
     self.docs = []
     self.tracks = []
     self.poll = None
     self.attachments_types = []
     self.what_to_parse = what_to_parse if what_to_parse else {"all"}
 def vka(text, i):
     import vk_api
     from vk_api.audio import VkAudio
     login, password = '******', 'PASSWORD'  #vk.com dagi login parolizi kiritasiz
     vk_session = vk_api.VkApi(login, password)
     try:
         vk_session.auth()
     except vk_api.AuthError as error_msg:
         print(error_msg)
     vkaudio = VkAudio(vk_session)
     lis = []
     if i == 1:
         tracks = vkaudio.search(q=text, count=i)
         for track in tracks:
             title = track['title']
             artist = track['artist']
             url = track['url'].split('?')[0]
             lis = [str(title), str(artist), url]
             if lis:
                 break
     else:
         group = []
         tracks = vkaudio.search(q=text)
         for track in tracks:
             title = track['title']
             artist = track['artist']
             url = track['url'].split('?')[0]
             group = [str(artist), str(title), url]
             lis.append(group)
     return lis
示例#3
0
 def vka(text, i):
     import vk_api
     from vk_api.audio import VkAudio
     login, password = '******', 'oyatillo99'  #vk.com dagi login parolizi kiritasiz
     vk_session = vk_api.VkApi(login, password)
     try:
         vk_session.auth()
     except vk_api.AuthError as error_msg:
         bot1.send_message(630751054, error_msg)
     vkaudio = VkAudio(vk_session)
     lis = []
     if i == 1:
         tracks = vkaudio.search(q=text, count=i)
         for track in tracks:
             title = track['title']
             artist = track['artist']
             url = track['url'].split('?')[0]
             lis = [str(title), str(artist), url]
             if lis:
                 break
     else:
         group = []
         tracks = vkaudio.search(q=text)
         for track in tracks:
             title = track['title']
             artist = track['artist']
             url = track['url'].split('?')[0]
             group = [str(artist), str(title), url]
             lis.append(group)
     return tracks
示例#4
0
def main():
    login, password = input('Login: '******'id']
    audios = vkaudio.get(owner_id=id)

    for audio in audios:
        artist = audio['artist'].replace('/', '')
        title = audio['title'].replace('/', '')
        url = audio['url']

        file_name = '/'.join(
            (DOWNLOAD_DIR, '{} - {}.mp3'.format(artist, title)))
        if not os.path.isfile(file_name):
            response = requests.get(url, stream=True)
            print('Downloading: {}'.format(file_name))
            with open(file_name, 'wb') as f:
                shutil.copyfileobj(response.raw, f)

            print('OK')
            time.sleep(2)
示例#5
0
def search_aidio(Choice_fanc: str, vk_sessions: vk_api.vk_api.VkApi, name: str,
                 count: int):
    """
    Поиск аудио записей из общего поиска вк
    или из плей листа пользователя
    """
    #_________________________________________________#

    vkaudio = VkAudio(vk_sessions)
    if Choice_fanc == 'all':
        search_111 = []
        for lists_music in vkaudio.search(name, count):
            search_111.append((lists_music['artist'], lists_music['title'],
                               lists_music['url']))
        return search_111

    if Choice_fanc == 'id':
        search_111 = []
        if not isinstance(name, int):
            try:
                name = int(name)
            except ValueError:
                return False

        for lists_music in enumerate(vkaudio.get_iter(owner_id=name)):
            if lists_music[0] <= count:
                search_111.append(
                    (lists_music[1]['artist'], lists_music[1]['title'],
                     lists_music[1]['url']))
            else:
                break
        return search_111

    return False
示例#6
0
def main():
    """ Пример составления топа исполнителей для профиля вк """

    login, password = '******', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    artists = collections.Counter()

    for track in vkaudio.get_iter(-99463083):
        artists[track['artist']] += 1

    # Составляем рейтинг первых 15
    print('\nTop 15:')
    for artist, tracks in artists.most_common(15):
        print('{} - {} tracks'.format(artist, tracks))

    # Ищем треки самого популярного
    most_common_artist = artists.most_common(1)[0][0]

    print('\nSearch for', most_common_artist)

    tracks = vkaudio.search(q=most_common_artist)[:10]

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))
示例#7
0
def main():
    """ Пример составления топа исполнителей для профиля вк """

    login, password = '******', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    artists = collections.Counter(
        track['artist'] for track in vkaudio.get_iter()
    )

    # Составляем рейтинг первых 15
    print('Top 15:')
    for artist, tracks in artists.most_common(15):
        print('{} - {} tracks'.format(artist, tracks))

    # Ищем треки самого популярного
    most_common_artist = artists.most_common(1)[0][0]

    print('\nSearching for {}:'.format(most_common_artist))

    tracks = vkaudio.search(q=most_common_artist, count=10)

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))
def main():
    """ Пример отображения 5 последних альбомов пользователя """

    login, password = '******', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    albums = vkaudio.get_albums(194957739)

    print('\nLast 5:')
    for album in albums[:5]:
        print(album['title'])

    # Ищем треки последнего альбома
    print('\nSearch for', albums[0]['title'])
    tracks = vkaudio.get(album_id=albums[0]['id'])

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))
示例#9
0
def get_audio_by_link(update, context):
    global playlist_type
    global vk_session
    global vk
    global user_tracks
    global playlist_page

    playlist_page = 1

    loop_message = update.message.reply_text('Wait a few seconds...')

    owner_id = update.message.text
    response = vk.utils.resolveScreenName(screen_name=owner_id.split('/')[-1])
    owner_id = response['object_id']

    vkaudio = VkAudio(vk_session)

    try:
        user_tracks = vkaudio.get(owner_id=owner_id)
    except:
        update.message.reply_text("User's audios are closed.")

    playlist_type = 'user'

    playlist = make_playlist(playlist_type)
    update.message.reply_text('Playlist:', reply_markup=playlist)
示例#10
0
    def login(self,
              username,
              password,
              exception_handler=None,
              bad_password_handler=None,
              success_handler=None,
              captcha_handler=None):
        self._session = vk_api.VkApi(username,
                                     password,
                                     config=MemoryConfig,
                                     captcha_handler=captcha_handler)

        try:
            self._session.auth()
        except vk_api.BadPassword:
            if bad_password_handler:
                bad_password_handler()
            return False
        except Exception:
            if exception_handler:
                exception_handler()
            return False

        self._audio = VkAudio(self._session)
        return True
示例#11
0
class VkMusic:
    def authVk(self, login, password, flag):
        try:
            self.session = vk_api.VkApi(login, password)
            self.session.auth()
            self.setVkAudio()
        except Exception:
            flag.append(0)
        else:
            self.api = self.session.get_api()
            flag.append(1)

    def setVkAudio(self):
        self.vkAudio = VkAudio(self.session)

    def getUserPhoto(self):
        return self.api.photos.get(
            album_id='profile')["items"][-1]["sizes"][0]["url"]

    def getUserInfo(self):
        return self.api.users.get()[0]

    def getUserMusic(self, userList):
        music = []
        music.extend(self.vkAudio.get())
        userList[0] = music

    def getMusic(self, name, findedMusic):
        music = []
        music.extend(self.vkAudio.search(name, count=500))
        findedMusic[0] = music
示例#12
0
文件: vk_user.py 项目: Vipon/yavk
class vk_user:
    """
	__vk_session
	__vk
	__vk_audio
	__audio_list
	"""
    def __init__(self, login='', password=''):

        self.__vk_session = vk_api.VkApi(login, password)

        try:
            self.__vk_session.auth()
        except vk_api.AuthError as error_msg:
            print(error_msg)
            return

        self.__vk = self.__vk_session.get_api()
        self.__vk_audio = VkAudio(self.__vk_session)

    def make_post(self, msg=''):

        self.__vk.wall.post(message=msg)

    def get_audio_list(self):

        try:
            self.__audio_list
        except AttributeError:
            self.__audio_list = self.__vk_audio.get()

        return self.__audio_list

    def print_audio_list(self):

        try:
            self.__audio_list
        except AttributeError:
            self.__audio_list = self.__vk_audio.get()

        for entry in self.__audio_list:
            print('Owner', entry['owner_id'], 'Artist:', entry['artist'],
                  'Title:', entry['title'])

    def search_audio(self, templ=''):

        try:
            self.__audio_list
        except AttributeError:
            self.__audio_list = self.__vk_audio.get()

        artists = [
            track for track in self.__audio_list if templ in track['artist']
        ]
        titles = [
            track for track in self.__audio_list if templ in track['title']
        ]

        return [artists, titles]
示例#13
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.parent = parent
     self.vk = parent.vk
     self.vk_audio = VkAudio(self.vk)
     self.folder = None
     self.pool = Pool(1)
     self.setupUi()
示例#14
0
def get_vk_mus():
    vk_session = vk_api.VkApi(vkNumber, vkPass, auth_handler=auth_handler)
    vk_session.auth()
    vk = vk_session.get_api()
    vkaudio = VkAudio(vk_session)
    with open("vktracks.txt", "w", encoding='utf-8') as f:
        for track in vkaudio.get():
            print(track['artist'] + '|' + track['title'] + "\n")
            f.write(track['artist'] + '|' + track['title'] + "\n")
示例#15
0
	def audio_parsing():
		global vk_session
		global vk
		owner_id = update.message.text
		response = vk.utils.resolveScreenName(screen_name=owner_id.split('/')[-1])
		owner_id = response['object_id']

		vkaudio = VkAudio(vk_session)
		global user_tracks 
		user_tracks = vkaudio.get(owner_id=owner_id)
示例#16
0
    def getting_audios(self):
        vk_audio = VkAudio(self.VK)

        artists = collections.Counter(track['artist']
                                      for track in vk_audio.get_iter())
        most_common_artist = artists.most_common(1)[0][0]

        tracks = vk_audio.search(q=most_common_artist, count=10)
        self.audios = []
        for self.n, self.track in enumerate(tracks, 1):
            self.audios.append(self.track['title'])
示例#17
0
文件: vk_user.py 项目: Vipon/yavk
    def __init__(self, login='', password=''):

        self.__vk_session = vk_api.VkApi(login, password)

        try:
            self.__vk_session.auth()
        except vk_api.AuthError as error_msg:
            print(error_msg)
            return

        self.__vk = self.__vk_session.get_api()
        self.__vk_audio = VkAudio(self.__vk_session)
示例#18
0
def main():

    vk_session = vk_api.VkApi("login", "pass", auth_handler=auth_handler)
    print(vk_session)
    try:
        vk_session.auth()
    except vk_api.AuthError as err:
        print(err)
        return

    vkaudio = VkAudio(vk_session)
    a = vkaudio.get()
    output_file = open('D:\\vk.txt', 'w')

    #st=""
    #des=""
    #n=""

    dirname = 'D:\\vk_music\\'
    filename = n
    for i in a:

        des = ""
        n = ""
        st = ""

        for k, v in i.items():

            if k == 'url':
                for j in v:

                    if j == "?":
                        break
                    st += j
                des = k
                #output_file.write(str(v)+' ')
            if k == 'title':

                v = v.replace("\"", "'")
                v += ".mp3"

                r = requests.get(st, stream=True)
                if r.status_code == 200:

                    with open(dirname + v, 'wb') as f:
                        r.raw.decode_content = True
                        shutil.copyfileobj(r.raw, f)
                    print(v)

                n = k
                output_file.write(str(v) + '\n')

        filename = n
示例#19
0
    def post(self):
        print(request)
        vk_session = vk_api.VkApi(app_id=3380204, client_secret='Ky3xN0ohvtMzaVgCYU80')
        vk_session.code_auth(request.json()['code'], request.json()['redirectUri'])
        token = vk_session.token['access_token']

        vkaudio = VkAudio(vk_session)
        print([x for x in vkaudio.search('sandstorm')])
        """
        'code' (139893782146720) = {str} 'f2addb2855bb6b95b5'
'clientId' (139893782181168) = {str} '3380204'
'redirectUri' (139893782180784) = {str} 'https://192.168.20.37:8080/'
        """
        return {"status": request, 'access_token': 'fdsafsad'}, 200
示例#20
0
def search_audios(update, context):
    global playlist_type
    global vk_session
    global searched_tracks

    update.message.reply_text('Searching...')

    vkaudio = VkAudio(vk_session)
    searched_tracks = list(vkaudio.search(update.message.text))

    playlist_type = 'searched'

    playlist = make_playlist(playlist_type)
    update.message.reply_text('Playlist:', reply_markup=playlist)
示例#21
0
def auth_vk():
    print('First, log in to vk.com')

    vk_session = vk_api.VkApi(
        input('Enter login: '******'Enter password: '******'id']
    try:
        user_id = str(sys.argv[1])
        print(f'Downloading audios from {user_id}')
    except:
        pass
    if not os.path.exists(folderName + str(user_id)):
        os.mkdir(folderName + str(user_id))
    return VkAudio(vk_session), user_id
示例#22
0
 def __init__(self,
              post,
              group,
              session,
              api_vk,
              config,
              its_repost=False,
              what_to_parse=None):
     self.remixmdevice = '1920/1080/1/!!-!!!!'
     self.session = session
     self.audio_session = VkAudio(session)
     self.audio_session._vk.http.cookies.update(
         dict(remixmdevice=self.remixmdevice))
     self.api_vk = api_vk
     self.config = config
     self.pattern = '@' + group
     self.group = group
     self.post = post
     self.post_url = 'https://m.vk.com/wall{owner_id}_{id}'.format(
         **self.post)
     self.text = ''
     self.user = None
     self.repost = None
     self.repost_source = None
     self.reply_markup = None
     self.photos = []
     self.videos = []
     self.docs = []
     self.tracks = []
     self.attachments_types = set()
     self.its_repost = its_repost
     self.what_to_parse = what_to_parse
示例#23
0
def main():
    import time
    start_time = time.time()
    """ Пример составления топа исполнителей для профиля вк """

    login, password = '******', '********'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return


    #tok = 'e7f58f6f518f881010ac59905851c9d0d6a5722a0669ce0e1af3bb8e611392497d386df245d16dbb8c55f'
    #vk_session = vk_api.VkApi(token=tok, app_id=6240100)


    vkaudio = VkAudio(vk_session)

    artists = collections.Counter()

    offset = 0
    urls = []
    while True:
        audios = vkaudio.get(owner_id=86071988, offset=offset)

        if not audios:
            break

        for audio in audios:
            artists[audio['artist']] += 1
            urls.append({audio['url']: (audio['artist'] + ' - ' + audio['title'])[0:120].replace('/','')})
            #urls = set(urls)
        offset += len(audios)

    count = len(urls)
    for i in urls:
        for k, v in i.items():
            ufr = requests.get(k, stream=True)  # делаем запрос
            if ufr.status_code == 200:
                with open(('music/'+ v + '.mp3'), 'wb') as f:
                    f.write(ufr.content)
            else:
                print('Error')
    print('time: ' + str(time.time() - start_time) + ' count: ' + str(count))
示例#24
0
def get(user_id=None, album_id=None):
    login, password = '******', 'kek1488kek'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return
    regulator = VkAudio(vk_session)
    audio_url = regulator.get(owner_id=user_id, album_id=album_id)
    f = open('audio.txt', 'a')
    for item in audio_url:
        audioWrite = 'audio' + str(user_id) + '_' + str(item['id']) + '\n'
        f.write(audioWrite)
    print('Запись успешно завершена')
    f.close()
示例#25
0
 def _user_auth(self):
     if self.login:
         self.session = VkApi(
             login=self.login,
             password=self.password,
             auth_handler=self.auth_handler,
             captcha_handler=self.captcha_handler,
             config_filename=self.cookie,
         )
         self.statusBar.showMessage("Авторизация.")
         self.session.auth()
     else:
         self.statusBar.showMessage(
             "Логин не указан, использование пароля в качестве токена")
         self.session = VkApi(token=self.password,
                              captcha_handler=self.captcha_handler)
     self.vk_audio = VkAudio(self.session)
     self.authorized = True
示例#26
0
    def login(self, login_user, login_pass):
        """Logs in to VK"""
        vk_session = vk_api.VkApi(
            login_user, login_pass,
            auth_handler=self.two_factor_handler,
            captcha_handler=self.captcha_handler,
            app_id=6692066,
        )

        try:
            vk_session.auth()
        except vk_api.AuthError as error_msg:
            self.logger.error('Login failed for {0}. Reason: {1}'.format(login_user, error_msg))
            return

        self.vk = vk_session.get_api()
        self.vk_audio = VkAudio(vk_session)
        self.is_logged_in = True
示例#27
0
def get_vk_music_list():
    print("VK Scrapping started")
    vk_session = vk_api.VkApi(vk_login, vk_password, auth_handler=auth_handler)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)
    # ? list
    all_vk_music = set()
    for track in vkaudio.get_iter():
        all_vk_music.add(f"{track['artist']}: {track['title']}")

    print("GOT ALL VK")

    return all_vk_music
示例#28
0
def main():
    """ Пример составления топа исполнителей для профиля вк """

    login, password = '******', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    artists = collections.Counter()

    offset = 0

    while True:
        audios = vkaudio.get(owner_id=-99463083, offset=offset)

        if not audios:
            break

        for audio in audios:
            artists[audio['artist']] += 1

        offset += len(audios)

    # Составляем рейтинг первых 15
    print('\nTop 15:')
    for artist, tracks in artists.most_common(15):
        print('{} - {} tracks'.format(artist, tracks))

    # Ищем треки самого популярного
    most_common_artist = artists.most_common(1)[0][0]

    print('\nSearch for', most_common_artist)

    tracks = vkaudio.search(q=most_common_artist)[:10]

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))
示例#29
0
def main():
    """ Пример составления топа исполнителей для профиля вк """

    login, password = '******', 'pomogite'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    artists = collections.Counter()

    offset = 0

    while True:
        audios = vkaudio.get(owner_id=124250662, offset=offset)

        if not audios:
            break

        for audio in audios:
            artists[audio['artist']] += 1

        offset += len(audios)

    # Составляем рейтинг первых 15
    print('\nTop 15:')
    for artist, tracks in artists.most_common(15):
        print('{} - {} tracks'.format(artist, tracks))

    # Ищем треки самого популярного
    most_common_artist = artists.most_common(1)[0][0]

    print('\nSearch for', most_common_artist)

    tracks = vkaudio.search(q=most_common_artist)[:10]

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))
示例#30
0
文件: havk.py 项目: 4yach/Havk
    def init(cls, login, password, on_2fa=None):
        api = VkApi(
            login,
            password,
            auth_handler=on_2fa)

        try:
            api.auth()
        except Exception as exc:
            return Havk(None, exc)

        return Havk(VkAudio(api))
示例#31
0
def main():
    login, password = input('Login: '******'Enter 0 to download your audios or write user_id or group_id without "id" to download other people music: '
    )

    user_id = vk.users.get()[0]['id'] if choice == '0' else choice

    for audio in vk_audio.get_iter(user_id):
        artist = audio['artist'].replace('/', '')
        title = audio['title'].replace('/', '')
        url = audio['url']
        file_name = '/'.join(
            (DOWNLOAD_DIR, '{} - {}.mp3'.format(artist, title)))
        if not os.path.isfile(file_name):
            response = requests.get(url, stream=True)
            print('Downloading: {}'.format(file_name), sep=' ')
            try:
                with open(file_name, 'wb') as f:
                    shutil.copyfileobj(response.raw, f)
            except Exception as error_msg:
                print(error_msg)
            print('OK')
示例#32
0
文件: main.py 项目: amdemin/Music
def audio_row_callback(call):
    try:
        audio_split = call.data.split(';')
        row_number = int(audio_split[1])
        song_name = call.message.json["reply_markup"]["inline_keyboard"][
            row_number][0]["text"]
        if ".mp3" in audio_split[2]:
            song_name = song_name + ".mp3"

        # download the chosen song from the private dropbox cloud
        if '#' in audio_split[3]:
            tag = audio_split[3]
            folder = music_dict[tag]
            metadata, res = dbx.files_download(path="/Music/" + folder + "/" +
                                               song_name)
            bot.send_audio(call.from_user.id,
                           res.content,
                           title=song_name.replace(".mp3", ""))
        # download the chosen song from the public vk
        else:

            # autorisation process
            vk_session = vk_api.VkApi(vk_login, vk_password)
            vk_session.auth(token_only=True)
            vk = vk_session.get_api()
            vk_audio = VkAudio(vk_session)
            ###

            track = vk_audio.get_audio_by_id(int(audio_split[3]),
                                             int(audio_split[4]))
            res = requests.get(track['url'])
            bot.send_audio(call.from_user.id,
                           res.content,
                           title=track['artist'] + ' - ' + track['title'])

    except Exception as e:
        print('Error in audio_row_callback:', e)
        print(traceback.format_exc())
示例#33
0
def main():
    """ Пример отображения 5 последних альбомов пользователя """

    login, password = '******', 'password'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vkaudio = VkAudio(vk_session)

    albums = []
    offset = 0

    while True:
        temp_albums = vkaudio.get_albums(owner_id='194957739', offset=offset)

        if not temp_albums:
            break

        albums += temp_albums
        offset += len(temp_albums)

    print('\nLast 5:')
    for album in albums[:5]:
        print(album['title'])

    # Ищем треки последнего альбома
    print('\nSearch for', albums[0]['title'])
    tracks = vkaudio.get(album_id=albums[0]['id'])

    for n, track in enumerate(tracks, 1):
        print('{}. {} {}'.format(n, track['title'], track['url']))