From f635fe0975641b711ab0978f6d9193e40726990f Mon Sep 17 00:00:00 2001 From: SashaXser <24498484+SashaXser@users.noreply.github.com> Date: Tue, 19 Dec 2023 18:56:07 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=D0=A0=D0=B5=D1=84=D1=80=D0=B0=D0=BA=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=B8=D0=BD=D0=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Рефракторинг на основе новых возможностей Python --- examples/bot_longpoll.py | 13 +-- examples/get_album_audio.py | 2 +- examples/get_all_audio.py | 6 +- examples/messages_bot/user_messages_bot.py | 6 +- examples/requests_pool.py | 14 +-- examples/upload_photo.py | 4 +- vk_api/audio.py | 122 ++++++--------------- vk_api/audio_url_decoder.py | 15 +-- vk_api/bot_longpoll.py | 5 +- vk_api/exceptions.py | 11 +- vk_api/execute.py | 24 ++-- vk_api/keyboard.py | 9 +- vk_api/longpoll.py | 15 +-- vk_api/requests_pool.py | 16 +-- vk_api/streaming.py | 4 +- vk_api/tools.py | 14 +-- vk_api/upload.py | 19 +--- vk_api/utils.py | 9 +- vk_api/vk_api.py | 78 +++++-------- 19 files changed, 120 insertions(+), 266 deletions(-) diff --git a/examples/bot_longpoll.py b/examples/bot_longpoll.py index 63ae410b..7b50bd95 100644 --- a/examples/bot_longpoll.py +++ b/examples/bot_longpoll.py @@ -23,8 +23,6 @@ def main(): print(event.obj.from_id) print('Текст:', event.obj.text) - print() - elif event.type == VkBotEventType.MESSAGE_REPLY: print('Новое сообщение:') @@ -33,8 +31,6 @@ def main(): print(event.obj.peer_id) print('Текст:', event.obj.text) - print() - elif event.type == VkBotEventType.MESSAGE_TYPING_STATE: print('Печатает ', end='') @@ -43,23 +39,18 @@ def main(): print('для ', end='') print(event.obj.to_id) - print() - elif event.type == VkBotEventType.GROUP_JOIN: print(event.obj.user_id, end=' ') print('Вступил в группу!') - print() - elif event.type == VkBotEventType.GROUP_LEAVE: print(event.obj.user_id, end=' ') print('Покинул группу!') - print() - else: print(event.type) - print() + + print() if __name__ == '__main__': diff --git a/examples/get_album_audio.py b/examples/get_album_audio.py index 0b11a9e8..5409ad35 100644 --- a/examples/get_album_audio.py +++ b/examples/get_album_audio.py @@ -29,7 +29,7 @@ def main(): tracks = vkaudio.get(album_id=albums[0]['id']) for n, track in enumerate(tracks, 1): - print('{}. {} {}'.format(n, track['title'], track['url'])) + print(f"{n}. {track['title']} {track['url']}") if __name__ == '__main__': diff --git a/examples/get_all_audio.py b/examples/get_all_audio.py index 9f661030..4ed42c2b 100644 --- a/examples/get_all_audio.py +++ b/examples/get_all_audio.py @@ -26,17 +26,17 @@ def main(): # Составляем рейтинг первых 15 print('Top 15:') for artist, tracks in artists.most_common(15): - print('{} - {} tracks'.format(artist, tracks)) + print(f'{artist} - {tracks} tracks') # Ищем треки самого популярного most_common_artist = artists.most_common(1)[0][0] - print('\nSearching for {}:'.format(most_common_artist)) + print(f'\nSearching for {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'])) + print(f"{n}. {track['title']} {track['url']}") if __name__ == '__main__': diff --git a/examples/messages_bot/user_messages_bot.py b/examples/messages_bot/user_messages_bot.py index 0493367d..804cde9d 100644 --- a/examples/messages_bot/user_messages_bot.py +++ b/examples/messages_bot/user_messages_bot.py @@ -36,7 +36,7 @@ def main(): for event in longpoll.listen(): if event.type == VkEventType.MESSAGE_NEW and event.to_me and event.text: - print('id{}: "{}"'.format(event.user_id, event.text), end=' ') + print(f'id{event.user_id}: "{event.text}"', end=' ') response = session.get( 'http://api.duckduckgo.com/', @@ -64,9 +64,7 @@ def main(): image = session.get(image_url, stream=True) photo = upload.photo_messages(photos=image.raw)[0] - attachments.append( - 'photo{}_{}'.format(photo['owner_id'], photo['id']) - ) + attachments.append(f"photo{photo['owner_id']}_{photo['id']}") vk.messages.send( user_id=event.user_id, diff --git a/examples/requests_pool.py b/examples/requests_pool.py index 7a4edd77..d0be98c7 100644 --- a/examples/requests_pool.py +++ b/examples/requests_pool.py @@ -66,15 +66,13 @@ def main(): """Пример использования пула в виде объекта. Такой пул можно передать в качестве параметра""" - friends = {} - pool = vk_api.VkRequestsPool(vk_session) - for user_id in [1, 183433824]: - friends[user_id] = pool.method('friends.get', { - 'user_id': user_id, - 'fields': 'photo' - }) - + friends = { + user_id: pool.method( + 'friends.get', {'user_id': user_id, 'fields': 'photo'} + ) + for user_id in [1, 183433824] + } pool.execute() for key, value in friends.items(): diff --git a/examples/upload_photo.py b/examples/upload_photo.py index b3cc15a0..ee1c8c45 100644 --- a/examples/upload_photo.py +++ b/examples/upload_photo.py @@ -25,9 +25,7 @@ def main(): group_id=74030368 ) - vk_photo_url = 'https://vk.com/photo{}_{}'.format( - photo[0]['owner_id'], photo[0]['id'] - ) + vk_photo_url = f"https://vk.com/photo{photo[0]['owner_id']}_{photo[0]['id']}" print(photo, '\nLink: ', vk_photo_url) diff --git a/vk_api/audio.py b/vk_api/audio.py index d278edac..86a263c8 100644 --- a/vk_api/audio.py +++ b/vk_api/audio.py @@ -123,9 +123,7 @@ def get_iter(self, owner_id=None, album_id=None, access_hash=None): if not response['data'][0]: raise AccessDenied( - 'You don\'t have permissions to browse {}\'s albums'.format( - owner_id - ) + f"You don\'t have permissions to browse {owner_id}\'s albums" ) ids = scrap_ids( @@ -134,16 +132,12 @@ def get_iter(self, owner_id=None, album_id=None, access_hash=None): if not ids: break - tracks = scrap_tracks( + yield from scrap_tracks( ids, self.user_id, self._vk.http, - convert_m3u8_links=self.convert_m3u8_links + convert_m3u8_links=self.convert_m3u8_links, ) - - for i in tracks: - yield i - if response['data'][0]['hasMore']: offset += offset_diff else: @@ -172,20 +166,14 @@ def get_albums_iter(self, owner_id=None): while True: response = self._vk.http.get( - 'https://m.vk.com/audio?act=audio_playlists{}'.format( - owner_id - ), - params={ - 'offset': offset - }, - allow_redirects=False + f'https://m.vk.com/audio?act=audio_playlists{owner_id}', + params={'offset': offset}, + allow_redirects=False, ) if not response.text: raise AccessDenied( - 'You don\'t have permissions to browse {}\'s albums'.format( - owner_id - ) + f"You don\'t have permissions to browse {owner_id}\'s albums" ) albums = scrap_albums(response.text) @@ -193,9 +181,7 @@ def get_albums_iter(self, owner_id=None): if not albums: break - for i in albums: - yield i - + yield from albums offset += ALBUMS_PER_USER_PAGE def get_albums(self, owner_id=None): @@ -232,9 +218,7 @@ def search_user(self, owner_id=None, q=''): if not json_response['payload'][1]: raise AccessDenied( - 'You don\'t have permissions to browse {}\'s audio'.format( - owner_id - ) + f"You don\'t have permissions to browse {owner_id}\'s audio" ) if json_response['payload'][1][1]['playlists']: @@ -356,16 +340,12 @@ def search_iter(self, q, offset=0): if offset_left < offset: ids = ids[offset - offset_left:] - tracks = scrap_tracks( + yield from scrap_tracks( ids, self.user_id, convert_m3u8_links=self.convert_m3u8_links, - http=self._vk.http + http=self._vk.http, ) - - for track in tracks: - yield track - offset_left += len(ids) response = self._vk.http.post( @@ -404,16 +384,12 @@ def get_updates_iter(self): if not ids: break - tracks = scrap_tracks( + yield from scrap_tracks( ids, self.user_id, convert_m3u8_links=self.convert_m3u8_links, - http=self._vk.http + http=self._vk.http, ) - - for track in tracks: - yield track - if len(updates) < 11: break @@ -447,16 +423,13 @@ def get_popular_iter(self, offset=0): json_response['sectionData']['recoms']['playlist']['list'] ) - tracks = scrap_tracks( + yield from scrap_tracks( ids[offset:] if offset else ids, self.user_id, convert_m3u8_links=self.convert_m3u8_links, - http=self._vk.http + http=self._vk.http, ) - for track in tracks: - yield track - def get_news_iter(self, offset=0): """ Искать популярные аудиозаписи (генератор) @@ -479,16 +452,12 @@ def get_news_iter(self, offset=0): ) if offset_left + len(ids) >= offset: - tracks = scrap_tracks( - ids if offset_left >= offset else ids[offset - offset_left:], + yield from scrap_tracks( + ids if offset_left >= offset else ids[offset - offset_left :], self.user_id, convert_m3u8_links=self.convert_m3u8_links, - http=self._vk.http + http=self._vk.http, ) - - for track in tracks: - yield track - offset_left += len(ids) while True: @@ -511,16 +480,12 @@ def get_news_iter(self, offset=0): break if offset_left + len(ids) >= offset: - tracks = scrap_tracks( - ids if offset_left >= offset else ids[offset - offset_left:], + yield from scrap_tracks( + ids if offset_left >= offset else ids[offset - offset_left :], self.user_id, convert_m3u8_links=self.convert_m3u8_links, - http=self._vk.http + http=self._vk.http, ) - - for track in tracks: - yield track - offset_left += len(ids) def get_audio_by_id(self, owner_id, audio_id): @@ -530,8 +495,7 @@ def get_audio_by_id(self, owner_id, audio_id): :param audio_id: ID аудио """ response = self._vk.http.get( - 'https://m.vk.com/audio{}_{}'.format(owner_id, audio_id), - allow_redirects=False + f'https://m.vk.com/audio{owner_id}_{audio_id}', allow_redirects=False ) ids = scrap_ids_from_html( @@ -539,14 +503,12 @@ def get_audio_by_id(self, owner_id, audio_id): filter_root_el={'class': 'basisDefault'} ) - track = scrap_tracks( + if track := scrap_tracks( ids, self.user_id, http=self._vk.http, - convert_m3u8_links=self.convert_m3u8_links - ) - - if track: + convert_m3u8_links=self.convert_m3u8_links, + ): return next(track) else: return [] @@ -557,34 +519,26 @@ def get_post_audio(self, owner_id, post_id): :param owner_id: ID владельца (отрицательные значения для групп) :param post_id: ID поста """ - response = self._vk.http.get( - 'https://m.vk.com/wall{}_{}'.format(owner_id, post_id) - ) + response = self._vk.http.get(f'https://m.vk.com/wall{owner_id}_{post_id}') ids = scrap_ids_from_html( response.text, filter_root_el={'class': 'audios_list'} ) - tracks = scrap_tracks( + return scrap_tracks( ids, self.user_id, http=self._vk.http, - convert_m3u8_links=self.convert_m3u8_links + convert_m3u8_links=self.convert_m3u8_links, ) - return tracks - def follow_user(self, user_id): data = self._vk.http.get(f"https://vk.com/audios{user_id}") user_hash = RE_USER_AUDIO_HASH.search(data.text) if user_hash is None: - raise AccessDenied( - 'You don\'t have permissions to browse {}\'s audio'.format( - user_id - ) - ) + raise AccessDenied(f"You don\'t have permissions to browse {user_id}\'s audio") user_hash = user_hash.groups()[1] response = self._vk.http.post( @@ -596,20 +550,14 @@ def follow_user(self, user_id): 'hash': user_hash, } ) - json_response = json.loads(response.text.replace('