def test_send_request_with_custom_api_version(self, mock_request): """Steps: * Check default api version value per api request * Check custom default api version per api request * Check overriden api version within request """ # Expect default version to being passed api = vk_requests.create_api() api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], BaseAuthAPI.DEFAULT_API_VERSION) mock_request.reset_mock() # Expect predefined version version = '3.00' api = vk_requests.create_api(api_version=version) api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version) mock_request.reset_mock() # Override version in the requests version = '5.8' api.users.get(user_id=1, v=version) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version)
def test_send_request_with_custom_api_version(self, mock_request): """Steps: * Check default api version value per api request * Check custom default api version per api request * Check overridden api version within request """ # Expect default version to being passed api = vk_requests.create_api() api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], BaseAuthAPI.DEFAULT_API_VERSION) mock_request.reset_mock() # Expect predefined version version = '3.00' api = vk_requests.create_api(api_version=version) api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version) mock_request.reset_mock() # Override version in the requests version = '5.8' api.users.get(user_id=1, v=version) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version)
def test_send_request_with_custom_api_version(self, mock_request): """Steps: * Check default api version value per api request * Check custom default api version per api request * Check overridden api version within request """ http_resp_mock = mock.Mock() http_resp_mock.configure_mock(text='{}') mock_request.return_value = http_resp_mock # Expect default version to being passed api = vk_requests.create_api() api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], api.version) mock_request.reset_mock() # Expect predefined version version = '3.00' api = vk_requests.create_api(api_version=version) api.users.get(user_id=1) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version) mock_request.reset_mock() # Override version in the requests version = '5.8' api.users.get(user_id=1, v=version) url_data, params = tuple(mock_request.call_args_list[0]) self.assertEqual(params['data']['v'], version)
def post_to_vk_via_api(new_post, msg): post_url = 'https://' + service_db[ new_post['service']]['post_url'] + new_post['post_id'].split('_p')[0] # Авторизация post_msg = f"{msg}\nОригинал: {post_url}" api = vk_requests.create_api(service_token=VK_TOKEN, api_version=5.71) # Загрузка картинки на сервер with open(f"{QUEUE_FOLDER}{new_post['pic_name']}", 'rb') as pic: current_album = get_current_album() upload_url = api.photos.getUploadServer( group_id=VK_GROUP_ID, album_id=current_album)['upload_url'] img = {'file1': (new_post['pic_name'], pic)} response = requests.post(upload_url, files=img) result = response.json() result['server'] = int(result['server']) uploaded_photo = api.photos.save(group_id=VK_GROUP_ID, album_id=current_album, caption=post_url, **result) photo_link = 'photo' + str(uploaded_photo[0]['owner_id']) + '_' + str( uploaded_photo[0]['id']) wall_id = api.wall.post(message=post_msg, owner_id='-' + VK_GROUP_ID, attachments=(photo_link, )) with session_scope() as session: num_photos = session.query(Setting).filter_by( setting='num_photos').first() num_photos.value = str(int(num_photos.value) + 1) return wall_id['post_id']
def send(login, password, voice_input, user_id, is_chat=False): api = vk_requests.create_api(app_id=_CLIENT_ID, client_secret=_CLIENT_SECRET, login=login, password=password, scope=['messages' 'docs']) upload_url = api.docs.getMessagesUploadServer(type='audio_message', peer_id=_make_peer_id( user_id, is_chat))['upload_url'] response = requests.post(upload_url, files=dict(file=voice_input)) response.raise_for_status() response_file = json.loads(response.text)['file'] doc_response = api.docs.save(file=response_file) message = { 'attachment': 'doc{0}_{1}'.format(doc_response['audio_message']['owner_id'], doc_response['audio_message']['id']), 'random_id': _make_random_id() } if is_chat: message['chat_id'] = user_id else: message['user_id'] = user_id api.messages.send(**message)
def _create_api(**kwargs): return vk_requests.create_api( app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, **kwargs )
def __init__(self, service_token): if not service_token: raise ValueError('service_token is required') import vk_requests self.api = vk_requests.create_api(service_token=service_token) self._params = self.api.streaming.getServerUrl()
def vksearch(text): api = v.create_api(app_id="5584212", login="******", password="******") a = api.users.get(user_ids="%s" % text, fields=["bdate ", "city", "music"]) #86691410 print(a)
def main(): config = Config.Instance() account = VKAccount() api = vk_requests.create_api(app_id=config.app_id, login=account.login, password=account.password) vk_user = VKUser(api)
def with_login(login, password): api = vk_requests.create_api(app_id=APP_ID, login=login, password=password, scope=SCOPE, api_version=API_VERSION) return VkWrap(api)
def __init__(self): print('Bot instance was initialized.') self.vk_api = vk_requests.create_api(login=Config.LOGIN, password=Config.PASSWORD, app_id=Config.APP_ID, api_version='5.80', scope='messages,offline') self.vk_id = self.vk_api.users.get()[0]['id'] logging.info('Created VK API session. Bot`s ID = {}'.format( self.vk_id)) print('Created VK API session. Bot`s ID = {}'.format(self.vk_id)) self.db = Database('data/bot_db.sqlite3') self.dict_feature_chats = self.db.get_feature_chats_dict() self._chats = self.db.get_chats() print('Database loaded.') logging.debug( 'Database loaded. chats = {chats}; dict_feature_chats = {d_f_c}'. format(chats=self._chats, d_f_c=self.dict_feature_chats)) self.logger = logging self.features = self.import_features() self.key, self.server, self.ts = self.get_long_poll_server()
def main(): # Assigned token var token = 'aa34d59868d72a146a250d1832c2b08519e79a34fdfc2b6f27d5ad44b2b100e0d5492c26166c5a6aed028' # Creating session using vk_requests api = vk_requests.create_api(service_token=token, scope=['friends', 'photos', 'groups', 'offline'], api_version='5.92') # Getting number of members count = api.groups.getMembers(group_id='hseofficial')['count'] # Filling the database with the users # Only 1000 at a time, thus I use offset to get all members i = 0 while i < count: g_users = api.groups.getMembers(group_id='hseofficial', sort='id_asc', offset=i, fields=['sex', 'photo_max_orig'], count=1000) db_upload(g_users) sleep(0.1) i += 1000 # Uploading the rest of members db_upload(api.groups.getMembers(group_id='hseofficial', sort='id_asc', offset=(i - 1000), fields=['sex', 'photo_max_orig'], count=(count - i + 1000))) # Cleaning the database cleanup()
def _create_api(**kwargs): return vk_requests.create_api(app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, stored_token=VkTestCase.STORED_TOKEN, session_cls=StoredVKSession, **kwargs)
def init_api(self, login, password, app_id): try: self.api = vk_requests.create_api(app_id = app_id, login = login, password = password) return True except: print('Error init api') return False
def __init__(self, *args): try: if len(args) == 1: token = args[0] self.token = token self.api = vk_requests.create_api(access_token=token) else: app_id = args[0] login = str(args[1]) password = str(args[2]) self.api = vk_requests.create_api(app_id=app_id, login=login, password=password) except Exception as e: print(e) sys.exit()
def get_online_friends(login, password): api = vk_requests.create_api(app_id=APP_ID, login=login, password=password, scope=['friends']) id_friends_online = api.friends.getOnline() name_friends_online = api.users.get(user_ids=id_friends_online) return name_friends_online
def get_user_info(self, id): """ Getting user information """ try: api = vk_requests.create_api(service_token=self.app_token) user = api.users.get(user_ids=id) return user[0]['first_name'] except Exception as e: print("[Get user info] :: ", e)
def connect_vk_api(login, password): api = vk_requests.create_api( app_id=APP_ID, login=login, password=password, api_version='5.101', scope='friends', ) return api
def creat_api(vk_config, type): tree=ET.parse(vk_config) root= tree.getroot() data=[] for child in root: data.append(child.text) return vk_requests.create_api(app_id=data[0],login=data[1],password=data[2], scope=type)
def test_create_api_with_token(self): api = vk_requests.create_api( app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, phone_number=PHONE_NUMBER) self.assertIsInstance(api, API) # Check that we have got access token on init self.assertIsInstance( api._session.auth_api._access_token, six.string_types)
def scan_vk(self, query): if not self.credentials['vk_app_id'] or not self.credentials[ 'vk_login'] or not self.credentials['vk_pass']: return output('VK credentials not founded') logging.getLogger('vk-requests').setLevel(logging.ERROR) api = vk_requests.create_api(app_id=self.credentials['vk_app_id'], login=self.credentials['vk_login'], password=self.credentials['vk_pass']) return output_vk(api.users.search(q=query, fields='domain'))
def test_create_api_with_token(self): api = vk_requests.create_api(app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, phone_number=PHONE_NUMBER) self.assertIsInstance(api, API) # Check that we have got access token on init self.assertIsInstance(api._session._access_token, six.string_types)
def pars_posts_api_init(): conf = file_handler.pars_secure_config() login = conf.get('account', 'login') password = conf.get('account', 'password') api_id = conf.get('account', 'api_id') api = vk_requests.create_api(app_id=api_id, login=login, password=password, interactive=True) return api
def __init__(self): try: self.vk = vk_requests.create_api( app_id=6666569, login=Config.vk_login, password=Config.vk_pass, scope='status,offline', api_version='5.92', ) except KeyError: self.vk = vk_requests.create_api(service_token=Config.vk_token) logging.info('Initialized VK API instance') try: self.status_str = Config.status_str logging.info('Using user-defined status string: %s', self.status_str) except KeyError: self.status_str = 'Госдолг США: $%s' logging.info('Using default status string: %s', self.status_str)
async def process_request(update) -> str: api = vk_requests.create_api(service_token=VK_TOKEN, api_version="5.80") if update.get("type") == "confirmation": await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize(":white_heavy_check_mark: Получен запрос от VK")) return 'ad9b6a46' elif update.get("type") == "message_new": await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize(":envelope: В сообществе новое личное сообщение."), reply_markup=messages_link()) return 'ok' elif update.get("type") == "photo_comment_new": user_data = await in_thread(get_user_data, api=api, update=update) await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize( f":sunrise_over_mountains: Новый комментарий к фотографии.\n\n{user_data['first_name']} " f"{user_data['last_name']}:\n{update['object']['text']}"), reply_markup=photo_link(update)) return 'ok' elif update.get("type") == "wall_repost": await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize( f":loudspeaker: Новый репост\nhttps://vk.com/wall" f"{update['object']['owner_id']}_{update['object']['id']}"), reply_markup=post_link(update)) return 'ok' elif update.get("type") == "wall_reply_new": user_data = await in_thread(get_user_data, api=api, update=update) await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize( f":page_with_curl: Новый комментарий на стене.\n\n{user_data['first_name']} " f"{user_data['last_name']}:\n{update['object']['text']}"), reply_markup=comment_link(update)) return 'ok' elif update.get("type") == "wall_post_new": await bot.send_message(TELEGRAM_CHANNEL_VKUPDATES, emojize( f":information: Новая запись на стене:\n\n" f"{update['object']['text']}"), reply_markup=post_link(update)) return 'ok' else: await bot.send_message( TELEGRAM_CHANNEL_VKUPDATES, emojize( f":question_mark: Необработанный апдейт:\n\n{repr(update)}")) print( emojize( f":question_mark: Необработанный апдейт:\n\n{repr(update)}")) return 'ok'
def test_customize_http_params(): http_resp_mock = mock.Mock() http_resp_mock.configure_mock(text='{}') with fake_request() as req: api = vk_requests.create_api( http_params={'timeout': 15, 'verify': False}) api.users.get(user_id=1) url_data, params = tuple(req.call_args_list[0]) assert params['verify'] is False assert params['timeout'] == 15
def get_random_photo(token): api = vk_requests.create_api(service_token=token) last_albums = [ album['id'] for album in api.photos.getAlbums(owner_id=owner_id)['items'][:2] ] album_id = random.choice(albums_id + last_albums) photos_wall_parkrun_kuzminki = api.photos.get(owner_id=owner_id, album_id=album_id) random_photo = random.choice(photos_wall_parkrun_kuzminki['items']) return sorted(random_photo['sizes'], key=lambda x: -x['height'])[2]['url']
def init_vk(self): self.api = vk_requests.create_api( app_id=self.app_id, login=self.login, password=self.password, scope=['offline', 'status', 'messages', 'docs', 'photos'], api_version=self.api_version) if self.api: print('Сессия создана') self.self = self.api.users.get()[0] print(self.self)
def test_create_api_with_client_secret(self): """Test direct authorization, it requires approved app id, user login, password, and secret code, more about it: https://vk.com/dev/auth_direct """ api = vk_requests.create_api(app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, client_secret=CLIENT_SECRET) self.assertIsInstance(api, API) # Check that we have got access token on init self.assertIsInstance( api._session._access_token, six.string_types)
def start(): api = vk_requests.create_api(app_id=6480738, service_token="31cc5d6031cc5d6031cc5d604e31\ aebe02331cc31cc5d606b3059678598a91622bc33d3") work_book, sheet = define_workbook() row = 2 for user_id in range(1, 100): if get_info(sheet, row, api, user_id): row += 1 work_book.save("vk_api.xlsx")
def test_create_api_with_user_token(self): """User token can be gotten via oauth flow, commonly via implicit flow It requires user login and password """ api = vk_requests.create_api( app_id=APP_ID, login=USER_LOGIN, password=USER_PASSWORD, phone_number=PHONE_NUMBER) self.assertIsInstance(api, API) # Check that we have got access token on init self.assertIsInstance( api._session._access_token, six.string_types)
def parse_vk_group(): SERVICE_TOKEN = 'ffb24391ffb24391ffb243911fffda3a77fffb2ffb24391a3eac4ce635b403c6ba08f00' group_id = 'XXX' api = vk_requests.create_api(service_token=SERVICE_TOKEN) group = api.groups.getMembers(group_id=group_id, fields=[ 'sex', 'bdate', 'city', 'country', 'photo_max_orig', 'online', 'online_mobile', 'contacts', 'connections', 'site', 'education', 'universities', 'schools' ]) return group
def create_api(login, password): log_stream = LogStream() # Setup basic config logging.basicConfig( stream=log_stream, level=logging.INFO, format='%(asctime)s %(levelname)s [%(name)s] %(message)s', ) # To change log level for the library logger logging.getLogger('vk-requests').setLevel(logging.DEBUG) api = vk_requests.create_api(app_id=7306186, login=login, password=password) return api, log_stream
def make_api(login, password): return create_api(app_id=4171870, login=login, password=password, scope=4096)
def setUp(self): self.vk_api = vk_requests.create_api(lang='ru')
# Авторизация login = '******' pwd = 'password' app_id = 123456 # ID приложения VK scopes = 2097151 # Настройки album_id = ['wall', 'profile', 'saved'] targer_id = 123456 # ID цели # Переменные photos_ids = [] i = 0 # Начало скрипта vkapi = vk_requests.create_api(app_id, login, pwd, api_version='5.44', timeout=10) for album in album_id: photos_list = vkapi.photos.get(owner_id=targer_id, album_id=album, extended=0, count=1000) print(photos_list) for photos in photos_list['items']: photos_ids.append(photos['id']) total = len(photos_ids) print('Count: '+str(total)) print('start') for each_id in photos_ids: try: i+=1 vkapi.likes.add(type='photo', owner_id=targer_id, item_id=each_id) finally:
def test_create_api_with_custom_api_version(self): api = vk_requests.create_api(api_version='5.00') self.assertEqual(api._session.auth_api.api_version, '5.00')
def test_create_api_without_token(self): api = vk_requests.create_api() self.assertIsInstance(api, API) self.assertIsNone(api._session.auth_api._access_token)
print("Do you want move new track's on bottom of all your tracks?") answer = input("Yy/Дд/Nn/Нн") if answer in ("Y", "y", "Д", "д"): print("You accept this option") answer = True else: print("You refused this option") answer = False local_user_login = input("Please insert your login \n") local_user_paswd = input("Please insert your password \n") api = vk_requests.create_api(app_id=str(APP_ID), login=local_user_login, password=local_user_paswd, scope=['audio', ]) cur_alb = api.audio.addAlbum(title=current_pl_name) time.sleep(0.35) last_track = receive_bottom_track() for track in current_pl: if track: time.sleep(0.35) cur_track = choose_track(track) if cur_track: time.sleep(0.35) print(cur_track['artist'], ' - ', cur_track['title']) new_audio = api.audio.add(audio_id=cur_track['id'],