def _requestToken(self): token = None count = 5 while not token and count > 0: count -= 1 login, password = self._askLogin() token = auth(login, password, APP_ID, "KUPNPTTQGApLFVOVgqdx", 'friends,groups,photos,audio,video,offline',"0") if token == "-1": code = self._askCode() token = auth(login, password, APP_ID, "KUPNPTTQGApLFVOVgqdx", 'friends,groups,photos,audio,video,offline',code) if token: __settings__.setSetting('auth_token', token) return token
def _requestToken(self): token = None count = 5 while not token and count > 0: count -= 1 login, password = self._askLogin() token = auth(login, password, APP_ID, "KUPNPTTQGApLFVOVgqdx", 'friends,groups,photos,audio,video,offline', "0") if token == "-1": code = self._askCode() token = auth(login, password, APP_ID, "KUPNPTTQGApLFVOVgqdx", 'friends,groups,photos,audio,video,offline', code) if token: __settings__.setSetting('auth_token', token) return token
def __init__(self, app_id, login, password): self.access_token = vk_auth.auth(login, password, app_id, "offline,messages")[0] print(self.access_token) self.layer = "" self.uid = "" self.section = ""
def initialize(self): if self.token is None or self.user_id is None: # trying to auth with login and password if self.login is None or self.password is None: # ask user to authorize in browser sys.stdout.write("You need to authorize this script to access your private messages on vk.com.\n" "To do it, you need to:\n1. Open the following url in your browser:\n" + vk_auth.get_auth_url(self.app_id, 'messages') + "\n2. Give access to the application.\n" "3. Copy access_token and user_id from the url of next page and paste it into config.ini file\n" "4. Start this script again.\n" ) input("Now press Enter to open auth page in your default browser, or Ctrl+C to exit") vk_auth.auth_in_browser(self.app_id, 'messages') return False try: sys.stdout.write('Trying to authenticate with your login and password...\n') self.token, self.user_id = vk_auth.auth(self.login, self.password, self.app_id, 'messages') except RuntimeError: sys.stdout.write("Authentication failed, maybe login/password are wrong?\n") return False sys.stdout.write("Authentication successful\n") else: sys.stdout.write("Authenticating with given token and user_id\n") return True
def __init__(self, app_id, login, password): self.acces_token = vk_auth.auth(login, password, app_id, "offline,messages")[0] self.layer = "" self.uid = "" self.section = "" print("Connected!") print("Enter help for see helplist")
def initialise(self): login, password = self.account.get() self.token, self.user_id = vk_auth.auth(login, password, APP_ID, "audio,friends") if len(self.token) == 0: self.show_login_ctrls() else: self.show_search_ctrls()
def no_configs(configs_filename): configs = {} print "Vkontakte authorization:" email = raw_input("E-mail: ") password = getpass.getpass("Password: "******"album title: ") if album_title == "": print "using default album title:", ALBUM_TITLE album_title = ALBUM_TITLE album_desc = raw_input("album description: ") if album_desc == "": print "using default album desc:", ALBUM_DESCRIPTION album_desc = ALBUM_DESCRIPTION client_id = raw_input("client id (application id), " + ENTER_DEFAULT + "(" + CLIENT_ID + ")") if not (client_id.isdigit() and client_id != ""): print "using default client id:", CLIENT_ID client_id = CLIENT_ID token, user_id = vk_auth.auth(email, password, client_id, "photos,offline") configs['album_title'] = album_title configs['album_desc'] = album_desc configs['client_id'] = client_id configs['token'] = token configs['user_id'] = user_id save_configs(configs_filename, configs) return configs
def on_login_button_clicked(self, button): login, password = self.login_entry.get_text(), self.password_entry.get_text() self.token, self.user_id = vk_auth.auth(login, password, APP_ID, "audio,friends") if len(self.token) > 0: self.account.update(login, password) for child in self.get_children(): child.destroy() self.show_search_ctrls()
def on_login_button_clicked(self, button): login, password = self.login_entry.get_text( ), self.password_entry.get_text() self.token, self.user_id = vk_auth.auth(login, password, APP_ID, "audio,friends") if len(self.token) > 0: self.account.update(login, password) for child in self.get_children(): child.destroy() self.show_search_ctrls()
def _auth(self, app_id, login, password, scope): """Авторизация клиентских приложений :return: access_token """ try: access_token, _ = vk_auth.auth(login, password, app_id, ','.join(scope), timeout=self.TIMEOUT) except Exception as e: print 'Error in vk_auth.auth function' raise e return access_token
def login_and_save(): email = raw_input("Email: ") password = getpass.getpass() client_id = "2951857" # Vk application ID token, user_id = vk_auth.auth(email, password, client_id, "audio") f = open('token', 'w') f.write(token) f.close() f = open('user_id', 'w') f.write(user_id) f.close()
def auth(): scope = LAST_SCOPETS if not USE_API_RELAY: (token, uid, secret) = vk_auth.auth(LOGIN, PASS, APPID, scope+",nohttps") agent = vkontakte.API(token=token, api_secret=secret) else: rsf = RELAY_SOCK_FILE rsf.write('LOG1\n%s %s %s\n'%(LOGIN, PASS, APPID)) rsf.flush() rsf.write(scope+'\n') rsf.flush() rld = rsf.readline().strip() token, uid, secret = rld.split(' ') agent = vkontakte.API() return token, uid, secret, agent
def enter(self, object): global client_id self.login = builder.get_object('login').get_text() self.password = builder.get_object('password').get_text() try: token, user_id = vk_auth.auth(self.login, self.password, client_id, "messages") db.update("token = '%s', user_id = '%s'" % (token, user_id)) self.auth = True; window.close() except Exception: builder.get_object('error').show() builder.get_object('error').set_text("Ошибка авторизации")
def auth(): scope = LAST_SCOPETS if not USE_API_RELAY: (token, uid, secret) = vk_auth.auth(LOGIN, PASS, APPID, scope + ",nohttps") agent = vkontakte.API(token=token, api_secret=secret) else: rsf = RELAY_SOCK_FILE rsf.write('LOG1\n%s %s %s\n' % (LOGIN, PASS, APPID)) rsf.flush() rsf.write(scope + '\n') rsf.flush() rld = rsf.readline().strip() token, uid, secret = rld.split(' ') agent = vkontakte.API() return token, uid, secret, agent
def get(self, film): (token,user_id) = vk_auth.auth( _vk['login'], _vk['password'], _vk['key'], 'video,offline') vk = vkontakte.API(token=token) data = vk.get( 'video.search', q=film, count=count, filters='long', extended=1, v=5.45); return data['items']
def main(): # directory = None email = input("Login: "******"4906664" token, user_id = vk_auth.auth(email, password, client_id, "photos") albums = get_albums(user_id, token) print("\n".join("{}. {}".format(num, album["title"]) for num, album in enumerate(albums))) choice = -1 while choice not in range(len(albums)): choice = int(input("Choose album number: ")) if len(sys.argv) == 2: directory = sys.argv[1] else: directory = albums[choice]["title"] photos_urls = get_photos_urls(user_id, albums[choice]["aid"], token) save_photos(photos_urls, directory)
def no_configs(configs_filename): configs = {} print "Vkontakte authorization:" email = raw_input("E-mail: ") password = getpass.getpass("Password: "******"album title: ") if album_title == "": print "using default album title:", ALBUM_TITLE album_title = ALBUM_TITLE album_desc = raw_input("album description: ") if album_desc == "": print "using default album desc:", ALBUM_DESCRIPTION album_desc = ALBUM_DESCRIPTION client_id = raw_input( "client id (application id), " + ENTER_DEFAULT + "(" + CLIENT_ID + ")" ) if not (client_id.isdigit() and client_id != ""): print "using default client id:", CLIENT_ID client_id = CLIENT_ID token, user_id = vk_auth.auth( email, password, client_id, "photos,offline" ) configs['album_title'] = album_title configs['album_desc'] = album_desc configs['client_id'] = client_id configs['token'] = token configs['user_id'] = user_id save_configs(configs_filename, configs) return configs
def session(sock, addr): sock.send("\n") cf = sock.makefile() while 1: c = cf.readline().strip() if c == 'LOG1': logstr = cf.readline().strip() uid, passwd, appid = logstr.split(' ') scope = cf.readline().strip()+',nohttps' token, uid, secret = vk_auth.auth(uid, passwd, appid, scope) cf.write('%s\n'%(' '.join((token, uid, secret)))) cf.flush() vk_api = vkontakte.API(token=token, api_secret=secret) elif c == 'REQE': method = cf.readline().strip() cf.write('OK\n') cf.flush() kwargs = {} while 1: c2 = cf.readline().strip() if c2 == 'PARA': key = cf.readline().strip() leng = int(cf.readline().strip()) value = cf.read(leng).strip() kwargs[key]=value elif c2 == 'ENDP': kwargs['method']=method kwargs['raw']=1 resp = json.dumps(vk_api.__call__(**kwargs)) cf.write('ANSW\n') cf.write('%d\n'%len(resp)) cf.write(resp) cf.flush() break elif c == 'QUIT': sock.close() return sock.close()
def main(): global user_id global token user_id = None token = None li = None email = user_params['email'] #raw_input("Email: ") password = user_params['password'] #getpass.getpass() client_id = "2951857" # Vk application ID print 'Checking conection....' if checkConnection(): print 'Connecting to vk.com...' token, user_id = auth(email, password, client_id, "users,offline,friends,audio") else: print 'Failed to connect google.com' print 'Loading chache' print 'Getting playlist...' li = MusicList(token, user_id) print 'Creating daemon...' global player player = VKPlayer(li) player.start() prlist = MusicListTitle(li) print prlist inputthread = Thread(target=InputCycle) inputthread.start() inputthread.join() player.Exit() player.join()
def main(): global user_id global token user_id = None token = None li = None email = user_params['email']#raw_input("Email: ") password = user_params['password']#getpass.getpass() client_id = "2951857" # Vk application ID print 'Checking conection....' if checkConnection(): print 'Connecting to vk.com...' token, user_id = auth(email, password, client_id, "users,offline,friends,audio") else: print 'Failed to connect google.com' print 'Loading chache' print 'Getting playlist...' li = MusicList(token, user_id) print 'Creating daemon...' global player player = VKPlayer(li) player.start() prlist = MusicListTitle(li) print prlist inputthread = Thread(target=InputCycle) inputthread.start() inputthread.join() player.Exit() player.join()
def get_links(login, password): ''' Returns a links of posts, which have an audio attachment. Structure: [(URL, TITLE)] NOTE: Title is a part of post's text. ''' token, user_id = vk_auth.auth(login, password, "4398787", "wall") #Authenticate, get token and uid vk = vkontakte.API(token=token) screen_name = vk.users.get(uids=user_id, fields='screen_name')[0]['screen_name'] res = vk.wall.get(count=100) # Get posts links = [] for post in res[1:]: # Get posts only with audio attachment attachments = post.get('attachments') if attachments is not None: for att in attachments: if 'audio' in att.values(): author_id, post_id = str(post['from_id']), str(post['id']) title = post['text'][:100] links.append(('http://vk.com/%s?w=wall%s_%s' % (screen_name, author_id, post_id), title)) break return links
def update_task(): sid, _ = vk_auth.auth(settings['email'], settings['password'], settings['api_id'], "audio") data = get_user_friends(sid, settings['user_id']) with open('latest_data.pkl', 'r+b') as _file: old_data = pickle.load(_file) diff = { 'deletions': set(old_data['friends']) - set(data['friends']), 'insertions': set(data['friends']) - set(old_data['friends']) } diff.update({ 'ins_len': len(diff['insertions']), 'insertions': '{ ' + ', '.join([str(item) for item in diff['insertions']]) + ' }', 'del_len': len(diff['deletions']), 'deletions': '{ ' + ', '.join([str(item) for item in diff['deletions']]) + ' }' }) logger.info('', extra=diff) _file.seek(0) pickle.dump(data, _file)
messages_type = Config.get("messages", "chat_type") app_id = Config.get("application", "app_id") # some chat preparation if messages_type == "interlocutor": is_chat = False elif messages_type == "chat": is_chat = True else: sys.exit("Messages type must be either interlocutor or chat.") # auth to get token try: token, user_id = vk_auth.auth(login, password, app_id, 'messages') except RuntimeError: sys.exit("Incorrect login/password. Please check it.") sys.stdout.write('Authorized vk\n') # get some information about chat selector = "chat_id" if is_chat else "uid" messages = _api("messages.getHistory", [(selector, messages_id)], token) out = codecs.open( 'vk_exported_dialogue_%s%s.txt' % ('ui' if not is_chat else 'c', messages_id), "w+", "utf-8") human_uids = [messages[1]["uid"]]
return result def save_audios(url, directory): if not os.path.exists(directory): os.mkdir(directory) names_pattern = "%s.mp3" % name.encode('ascii', 'ignore') filename = os.path.join(directory, names_pattern) print "Downloading %s" % filename open(filename, "wb").write(urllib2.urlopen(url).read()) directory = None if len(sys.argv) == 2: directory = sys.argv[1] #email = raw_input("Email: ") #password = getpass.getpass() email = "*****@*****.**" password = "******" client_id = "5534383" # Vk application ID token, user_id = vk_auth.auth(email, password, client_id, "audio") audios = get_audios(user_id, token) print "\n".join("%d. %s" % (num + 1, audio["title"]) for num, audio in enumerate(audios)) choice = -1 while choice not in xrange(len(audios)): choice = int(raw_input("Choose audio number: ")) - 1 if not directory: directory = audios[choice]["title"] name = audios[choice]["title"] #aid = str(audios[choice]["aid"]) + ',' audios_url = get_audio_url(user_id, audios[choice]["aid"], token) save_audios(audios_url, directory) print "Completed"
f.write(str(msg['attachment']['photo'][j]) + "\n") except: pass else: break else: continue except: pass if __name__ == "__main__": email = input("Email: ") password = getpass.getpass() APP_ID = "4589651" token, user_id = vk_auth.auth(email, password, APP_ID, "messages") dumpMore = 'y' while dumpMore == 'y': UID = input("Target user ID: ") first200 = callApi("messages.getHistory", [("uid", UID), ("count", "200"), ("rev", "1"), ("offset", "0")], token) fullCount = int(first200[0]) Folder = ("dump_dialog_%s" % UID) #Создаем папку "dump_dialog_№№" if Folder and not os.path.exists(Folder): os.makedirs(Folder) dia_path = os.path.join(Folder or "", "dump_dialog_%s.txt" % UID)
# -*- coding: utf-8 -*- import urllib import json from time import sleep from datetime import datetime, timedelta import vk_auth def get_json(url): getjson = urllib.request.urlopen(url).readall().decode('utf-8') getjson = json.loads(getjson) sleep(0.3) return getjson app_id = '5397060' access_token = vk_auth.auth('*****@*****.**', 'vkpassvk', app_id, 'offline')[0] #access_token = 'ab73388da5be5f3b7966188d10471c031d6ff78c7b54ee92293d4f102d02f09808b6a40d46d4b87ee52f4' print (access_token) publics_list = open('../config/config.json').read() publics_list = json.loads(publics_list) title = ['<?xml version="1.0" encoding="UTF-8" standalone="no"?>', '<graphml xmlns="http://graphml.graphdrawing.org/xmlns"', ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', ' xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"', ' xmlns:y="http://www.yworks.com/xml/graphml"', ' xmlns:yed="http://www.yworks.com/xml/yed/3">', ' <key for="node" id="d1" yfiles.type="nodegraphics"/>', ' <graph edgedefault="directed" id="G">'] graph_people = open("../results/graphml/friends_graph.graphml", 'w') graph_groups = open("../results/graphml/groups_graph.graphml", 'w') for line in title: graph_people.write(line+'\n') graph_groups.write(line+'\n') users=[]
### #email = 'email' #password = '******' bitrate = 230 usersmusic = raw_input("Download users playlist? ( yes/no ): ") if usersmusic.lower() == "n" or usersmusic.lower() == "no": # different search can be splitted by '|'. search = download.firstLetter(raw_input("What do want to find: ")).decode('utf-8') scount = raw_input("How many songs do want to download: ") offset = raw_input("Put offset: ") start_time = time.time() for s in search.split('|'): searching = urllib2.quote(s.encode('utf-8')) s = download.remSym(s) access_token, user_id = vk_auth.auth(email, password, "3164037", "10") download.doSearch(access_token, user_id, scount, searching, dpath + s, offset, False, bitrate) bq = open(dpath + s + "/Bad Quality Songs.txt" + searching, 'r') bqlist = bq.readlines() bq.close() for i in bqlist: download.doSearch(access_token, user_id, 7, urllib2.quote(i.strip()), dpath + s, 0, i.split(" - ")[0], bitrate) if os.path.exists(dpath + s): for i in os.listdir(dpath + s + '/'): if i.startswith("Bad Quality Songs.txt"): os.remove(dpath + s + "/" + i) print "Finish" else: if usersmusic.lower() == "y" or usersmusic.lower() == "yes": access_token, user_id = vk_auth.auth(email, password, "3164037", "10") download.usersMusic(access_token, user_id, 'myplaylist', dpath + 'myplaylist', False, bitrate)
from urllib import urlencode import Common as c import vk_auth c.log('debug', 'Init Api') # Session start time _START_TIME = long(time.time()) # Vk application ID _CLIENT_ID = '4603710' # Get token & user_id by login (_TOKEN, _USER_ID) = vk_auth.auth(c.cfg('user'), c.cfg('password'), _CLIENT_ID, "messages,audio,docs,video,photos,wall,friends") # Last time api call to prevent service overloading _LAST_API_CALL = 0 def request(method, params): global _TOKEN, _LAST_API_CALL diff = time.time() - _LAST_API_CALL if diff < 0.4: time.sleep(0.4) _LAST_API_CALL = time.time() for retry in xrange(3): try: params['access_token'] = _TOKEN
import vkontakte import vk_auth import getpass snob_parser_id = '5161360' snob_group_id = '-101947002' my_login = '' my_password = getpass.getpass() access_token = vk_auth.auth(my_login, my_password, snob_parser_id, "audio,status")[0] vk = vkontakte.API(token=access_token) all_tunes_in_public = vk.audio.get(owner_id=snob_group_id) # for tune in all_tunes_in_public: # for tune_field in tune
print captcha time.sleep(90.0) # print "Введи капчу!" # captcha = sys.stdin.readline() # captcha = captcha.split('\n')[0] # print captcha params += [('captcha_sid ', response['captcha_sid']), ('captcha_key', captcha)] method = '' for para in response['request_params']: if para['key'] == 'method': method = para['value'] else: pass r = call_api(method, params, current['token']) print r return r else: print "Дело не в капче!\n", response['error_msg'] return photos_with_comments = open('/Users/Alexandret/Desktop/Programs/workat/VK/vk-edit-photos/errors.txt', 'w') for current in config.clubs: current['token'], user_id = vk_auth.auth(current['email'], current['password'], config.client_id, "photos") print "auth done!" process_photos(current) print "procession done!" # print current # # Если тут всплыло "raise RuntimeError("Expected success here")" скорее всего всплыла капча, апи не умеет это обрабатывать
def main(): sid, user_id = vk_auth.auth(settings['email'], settings['password'], settings['api_id'], "audio") get_songs_by_album_id(sid, settings['album_id'])
# only_eng: 1 – возвращать только зарубежные аудиозаписи. 0 – возвращать все аудиозаписи. (по умолчанию) # genre_id: идентификатор жанра из списка жанров. # offset: смещение, необходимое для выборки определенного подмножества аудиозаписей. # count: количество возвращаемых аудиозаписей. # положительное число, максимальное значение 1000, по умолчанию 100 # # Результат: # # После успешного выполнения возвращает список объектов audio. def audio_getPopular(self, only_eng, genre_id, offset, count): pass if __name__ == '__main__': import vk_auth import settings auth = vk_auth.auth(settings.VK_AUTH['email'], settings.VK_AUTH['password'], settings.VK_AUTH['application'], 'audio') print auth api = VkApi(auth[0], auth[1]) # auto_complete, lyrics, performer_only, sort, offset, count r = api.audio_search(u'Король и Шут - Лесник', 1, 0, 0, count=10) print r
print 'token not loaded' token = None # auth if token is None: import vk_auth # check user and password if len(cfg_email) < 1 or len(cfg_password) < 1: import sys xbmcgui.Dialog().ok(__addonname__, 'Emtpy email or password') sys.exit() # auth try: token, user_id = vk_auth.auth(cfg_email, cfg_password, cfg_app_id, 'offline,video,wall') token_updated = True except: xbmcgui.Dialog().ok(__addonname__, 'Invalid login or password') sys.exit() # load cache urls = [] cache = [] #if not vk_load_cache(xbmc.translatePath(profile + 'cache.json'), cache): # print 'cache not loaded' # load wall if not vk_load_wall(token, cfg_source, cfg_depth, cache, urls):
except: pass else: break else: if msg['attachment']['photo']: for j in qual: try: f.write(str(msg['attachment']['photo'][j]) + "\n") except: pass else: break else: continue except: pass if __name__ == "__main__": email = input("Email: ") password = getpass.getpass() APP_ID="4589651" token, user_id = vk_auth.auth(email, password, APP_ID, "messages") dumpMore = 'y' while dumpMore == 'y': UID = input("Target user ID: ") first200 = callApi("messages.getHistory", [("uid", UID), ("count", "200"), ("rev", "1"), ("offset", "0")], token) fullCount = int(first200[0]) Folder = ("dump_dialog_%s" % UID) #Создаем папку "dump_dialog_№№" if Folder and not os.path.exists(Folder): os.makedirs(Folder) dia_path = os.path.join(Folder or "", "dump_dialog_%s.txt" % UID) with open(dia_path, "w") as f: #В файл "dump_dialog_№№.txt" записываем ссылки на фотографии dumpMessages(f, first200)
return result def save_photos(urls, directory): if not os.path.exists(directory): os.mkdir(directory) names_pattern = "%%0%dd.jpg" % len(str(len(urls))) for num, url in enumerate(urls): filename = os.path.join(directory, names_pattern % (num + 1)) print "Downloading %s" % filename open(filename, "w").write(urllib2.urlopen(url).read()) directory = None if len(sys.argv) == 2: directory = sys.argv[1] email = raw_input("Email: ") password = getpass.getpass() client_id = "2951857" # Vk application ID token, user_id = vk_auth.auth(email, password, client_id, "photos") albums = get_albums(user_id, token) print "\n".join("%d. %s" % (num + 1, album["title"]) for num, album in enumerate(albums)) choice = -1 while choice not in xrange(len(albums)): choice = int(raw_input("Choose album number: ")) - 1 if not directory: directory = albums[choice]["title"] photos_urls = get_photos_urls(user_id, albums[choice]["aid"], token) save_photos(photos_urls, directory)
def save_photos(urls, directory): if not os.path.exists(directory): os.mkdir(directory) names_pattern = "%%0%dd.jpg" % len(str(len(urls))) for num, url in enumerate(urls): filename = os.path.join(directory, names_pattern % (num + 1)) print "Downloading %s" % filename open(filename, "w").write(urllib2.urlopen(url).read()) email = user_params['email']#raw_input("Email: ") password = user_params['password']#getpass.getpass() client_id = "2951857" # Vk application ID token, user_id = vk_auth.auth(email, password, client_id, "offline,photos,status,friends,audio") #print token #print call_api('status.set', [('text', 'First Using VK.api')], token) ''' li = call_api('friends.get', [('uid', user_id), ('fields', 'first_name')], token) for x in li: #print x['first_name'], x['uid'] try: print x['uid'], len(call_api('audio.get', [('uid', x['uid'])], token)) except: print 'unable', x['uid'] #time.sleep(1) albums = get_albums(user_id, token) #print "\n".join("%d. %s" % (num + 1, album["title"]) for num, album in enumerate(albums))
url = photo["src_big"] result.append(url) return result def save_photos(urls, directory): if not os.path.exists(directory): os.mkdir(directory) names_pattern = "%%0%dd.jpg" % len(str(len(urls))) for num, url in enumerate(urls): filename = os.path.join(directory, names_pattern % (num + 1)) print "Downloading %s" % filename open(filename, "w").write(urllib2.urlopen(url).read()) directory = None if len(sys.argv) == 2: directory = sys.argv[1] email = raw_input("Email: ") password = getpass.getpass() client_id = "2951857" # Vk application ID token, user_id = vk_auth.auth(email, password, client_id, "photos") albums = get_albums(user_id, token) print "\n".join("%d. %s" % (num + 1, album["title"]) for num, album in enumerate(albums)) choice = -1 while choice not in xrange(len(albums)): choice = int(raw_input("Choose album number: ")) - 1 if not directory: directory = albums[choice]["title"] photos_urls = get_photos_urls(user_id, albums[choice]["aid"], token) save_photos(photos_urls, directory)
def login(self, user): self.token, self.current_user_id = vk_auth.auth(user, self.client_id, self.scope) user.user_id = self.current_user_id
def CreateOwnConfig(email, password): client_id = "2951857" # Vk application ID token, user_id = auth(email, password, client_id, "users,offline,friends,audio") return template % (email, token, client_id, user_id)
def ensure_login(self): if self.token is None or self.user_id is None: self.token, self.user_id = vk_auth.auth( self.email, self.password, client_id=self.client_id, scope=self.scope)
def __init__(self,app_id,login,password): self.access_token = vk_auth.auth(login, password, app_id, "offline,messages")[0] print(self.access_token) self.layer = "" self.uid = "" self.section = ""
#!/usr/bin/python # -*- coding: UTF-8 -*- import vk_auth import math import time import datetime from app_conf import * from app_func import * # authenticate to vk.com token, user_id = vk_auth.auth(email, password, client_id, scope) # determin count of requests to VK reqs = int(math.ceil(p_count / 100.0)) print "[INFO] Count of requests to VK: {}".format(reqs) # get posts' JSON representation wall_posts = [] offset = 0 for i in xrange(reqs): if by_tags is 1: posts = call_api("wall.search", [("domain", domain), \ ("count", 100), ("offset", offset), ("query", "#" + " #".join(tags_req))], token) else: posts = call_api("wall.get", [("domain", domain), \ ("count", p_count), ("offset", offset)], token) wall_posts += posts[1:] offset += 100
def __init__(self, email, password, permissions): #("*****@*****.**", "password", "messages,photos") self.email = email self.password = password self.token, self.user_id = vk_auth.auth(email, password, "2951857", permissions)
url = "https://api.vk.com/method/%s?%s" % (method, urlencode(params)) payload = urllib2.urlopen(url).read() payload_json = json.loads(payload) if not "response" in payload_json: sys.exit("Request failed:\nURL = %s\nPAYLOAD = %s" % (url, payload)) return payload_json["response"] config = read_config() reporter = Reporter.std_reporter() downloader = Downloader(reporter, directory=config["export"]["output_directory"]) # auth to get token try: reporter.progress("Authenticating as %s" % config["auth"]["username"], pad=True) token, user_id = vk_auth.auth(config["auth"]["username"], config["auth"]["password"], config["app"]["id"], 'messages') reporter.line("OK") except RuntimeError: reporter.line("FAILED") sys.exit("Cannot authenticate, please check your credentials in .auth.ini") # get some information about chat selector = "chat_id" if config["export"]["is_group_chat"] else "uid" messages = _api("messages.getHistory", [(selector, config["export"]["chat_id"])], token) # prepare output if config["export"]["output_directory"] is not None: if not os.path.exists(config["export"]["output_directory"]): os.makedirs(config["export"]["output_directory"])
print "Downloading %s" % filename open(filename, "w").write(urllib2.urlopen(url).read()) numbers = numbers + 1 if (numbers == 10): return def save_on_disk(albums, user_id): choise = -1 count = 0 global numbers while choise not in xrange(len(albums)): count = count + 1 photos_urls = get_photos_urls(user_id, albums[choise]["aid"], token) save_photos(photos_urls, count, user_id) if (numbers == 10): return email = raw_input("Email: ") password = getpass.getpass() email = '' password = '' token, user_id = vk_auth.auth(email, password, "2951857", "photos") user_id = 20020126 #res = search.search_people() albums = get_albums(user_id, token) save_on_disk(albums, user_id)
def ensure_login(self): if self.token is None or self.user_id is None: self.token, self.user_id = vk_auth.auth(self.email, self.password, client_id=self.client_id, scope=self.scope)
def __init__(self,app_id,login,password): self.access_token = vk_auth.auth(login, password, app_id, "offline,messages")[0] print(self.access_token)
#email = 'email' #password = '******' bitrate = 230 usersmusic = raw_input("Download users playlist? ( yes/no ): ") if usersmusic.lower() == "n" or usersmusic.lower() == "no": # different search can be splitted by '|'. search = download.firstLetter( raw_input("What do want to find: ")).decode('utf-8') scount = raw_input("How many songs do want to download: ") offset = raw_input("Put offset: ") start_time = time.time() for s in search.split('|'): searching = urllib2.quote(s.encode('utf-8')) s = download.remSym(s) access_token, user_id = vk_auth.auth(email, password, "3164037", "10") download.doSearch(access_token, user_id, scount, searching, dpath + s, offset, False, bitrate) bq = open(dpath + s + "/Bad Quality Songs.txt" + searching, 'r') bqlist = bq.readlines() bq.close() for i in bqlist: download.doSearch(access_token, user_id, 7, urllib2.quote(i.strip()), dpath + s, 0, i.split(" - ")[0], bitrate) if os.path.exists(dpath + s): for i in os.listdir(dpath + s + '/'): if i.startswith("Bad Quality Songs.txt"): os.remove(dpath + s + "/" + i) print "Finish" else:
url = "https://api.vk.com/method/%s?%s" % (method, urlencode(params_list)) return json.loads(urllib2.urlopen(url).read())["response"] def get_songs(user_id, token): return call_api("audio.get", ("oid", user_id), token) def save_music(songList, directory): if not os.path.exists(directory): os.mkdir(directory) for song in enumerate(songList[1::]): file = (song[1])["artist"]+" - " + (song[1])["title"]; file = file.replace("/", "") filename = os.path.join(directory, ( file+ ".mp3")) if not os.path.exists(filename): print "Downloading %s" % filename open(filename, "w").write(urllib2.urlopen((song[1])["url"]).read()) else: print "Exist %s" % filename directory = raw_input("File Directory: ") # email = raw_input("Email: ") # password = getpass.getpass() email = "" password = "" token, user_id = vk_auth.auth(email, password, "3714507", "audio") oid = raw_input("Please enter userId or grope Id, feel free if you want download music from your profile:\n") if oid == "": oid = user_id songsList = get_songs(oid, token) save_music(songsList, directory)
def main(): if (options.gid == None): print "set group id ( use -h for help) " exit(1) if (options.email == None): print "set Email ( use -h for help ) " exit(1) if (options.passwd == None): options.passwd = getpass.getpass("Enter your password:"******"*" * len(options.passwd), options.app_id) print greeting (token, user_id) = vk_auth.auth(options.email, options.passwd, options.app_id, 'friends') vk = vkontakte.API(token=token) server_time = vk.getServerTime() #check working if (server_time): group_info = groups_getById(vk, group_ids=options.gid) name = group_info[0]["name"] print "Auth is success, for ", name try: os.mkdir(FOLDER_RESULT + name) # make the directory with the name of the publick except (OSError): print "Directory Exist" ava = "ava.jpg" vk_link = "vk_link.png" vk_audio = "vk_audio.jpg" vk_video = "vk_video.jpg" shutil.copyfile(FOLDER_SERVICE + ava, FOLDER_RESULT + "%s/%s" % (name, ava)) shutil.copyfile(FOLDER_SERVICE + vk_link, FOLDER_RESULT + "%s/%s" % (name, vk_link)) shutil.copyfile(FOLDER_SERVICE + vk_video, FOLDER_RESULT + "%s/%s" % (name, vk_video)) shutil.copyfile(FOLDER_SERVICE + vk_audio, FOLDER_RESULT + "%s/%s" % (name, vk_audio)) if (options.count == None): temp = get_posts(vk, -int(options.gid), 0, 1) print "Post count = ", temp[0] count = temp[0] else: count = int(options.count) tom_count = int(options.split) offset = int( options.offset ) # frow where gell posts. This value will be chaged by iterations posts_by_tom = count / tom_count iteration = 0 #global iteration curr_tom = 0 iteration = 1 tom_iteration = 0 # curr count of posts in current tom step = 90 downloaded = 0 print posts_by_tom name_tom = "%s_%i.html" % (name, curr_tom) tom_file = open(FOLDER_RESULT + "%s/%s" % (name, name_tom), 'w+') # open first tom file tom_file.write(page_begin.encode('utf-8')) while (iteration * step < count): if (tom_iteration * step >= posts_by_tom): tom_file.close() tom_iteration = 0 curr_tom += 1 name_tom = "%s_%i.html" % (name, curr_tom) tom_file = open(FOLDER_RESULT + "%s/%s" % (name, name_tom), 'w+') # open cur tom file tom_file.write(page_begin.encode('utf-8')) posts = get_posts(vk, -int(options.gid), offset, step) downloaded += len(posts) - 1 print "Скачано:", downloaded posts_html = posts_to_html(vk, posts) tom_file.write(posts_html.encode('utf-8')) iteration += 1 tom_iteration += 1 offset += step tom_file.close() if (options.download_all == '1'): for i in range(curr_tom + 1): name_cur = "%s_%i.html" % (name, i) long_name = FOLDER_RESULT + "%s/%s" % (name, name_cur) folder = "%s_%sdata/" % (name, i) long_folder = FOLDER_RESULT + "%s/%s" % (name, folder) tom_file = codecs.open(long_name, "r", "utf-8") converted = FOLDER_RESULT + "%s/%s_%s_converted.html" % ( name, name, i) print converted converted = open(converted, 'w+') data = tom_file.read() download_media(long_name, FOLDER_RESULT + "%s/%s" % (name, folder)) new_data = convert_links(data, "./%s" % folder) #tom_file.seek(0) converted.write(new_data.encode("utf-8")) tom_file.close() converted.close() return 0
def _api(method, params, token): params.append(("access_token", token)) url = "https://api.vk.com/method/%s?%s" % (method, urlencode(params)) return json.loads(urllib2.urlopen(url).read())["response"] # read config values Config = ConfigParser.ConfigParser() Config.read("config.ini") login = Config.get("auth", "username") password = Config.get("auth", "password") app_id = Config.get("application", "app_id") # auth to get token try: token, user_id = vk_auth.auth(login, password, app_id, 'notes') except RuntimeError: sys.exit("Incorrect login/password. Please check it.") sys.stdout.write('Authorized vk\n') # get the list of notes notes = _api("notes.get", [("count", "100")], token) print len(notes) print notes[0]