def execute(bot, data, forward=True): args = {"peer_id": data['peer_id'], "v": "5.60"} args['message'] = "Перезапуск всех потоков начат" bot.Replyqueue.put(args) with bot.Checkqueue.mutex: bot.Checkqueue.queue.clear() with bot.Longpool.mutex: bot.Longpool.queue.clear() sleep(3) # del bot.UserApi # del bot.GroupSession # del bot.UserSession # del bot.GroupApi bot.UserSession = SessionCapchaFix(access_token=bot.UserAccess_token) bot.GroupSession = SessionCapchaFix(access_token=bot.GroupAccess_token) bot.GroupApi = API(bot.GroupSession) bot.UserpApi = API(bot.UserSession) t = len(bot.LP_threads) for th in bot.LP_threads: try: th._stop() th.join() bot.LP_threads.pop(th) except: t -= 1 for i in range(t): bot.LP_threads.append(threading.Thread(target=bot.parseLongPool)) bot.LP_threads[i].setDaemon(True) bot.LP_threads[i].start() t = len(bot.EX_threadList) for th in bot.EX_threadList: try: th._stop() th.join() bot.EX_threadList.pop(th) except: t -= 1 for i in range(t): bot.EX_threadList.append(threading.Thread(target=bot.ExecCommands)) bot.EX_threadList[i].setDaemon(True) bot.EX_threadList[i].start() print("Чистим все ответы") with bot.Replyqueue.mutex: bot.Replyqueue.queue.clear() bot.ReplyThread._reset_internal_locks(False) bot.ReplyThread._stop() bot.ReplyThread.join() del bot.ReplyThread bot.ReplyThread = threading.Thread(target=bot.Reply) bot.ReplyThread.setDaemon(True) bot.ReplyThread.start() print("Перезапуск закончен") Reloaded = 'Перезагружены\n' + '\n'.join(bot.MODULES.Reload()) args['message'] = Reloaded + "\nПерезапуск закончен" bot.Replyqueue.put(args)
def test_v_param(service_token, v): """ Missed version on API instance """ api = API(service_token) with raises(VkAPIError, match='8\. Invalid request: v \(version\) is required'): api.getServerTime() assert api.getServerTime(v=v) > time.time() - 10
def download_album(user_id, community_id, album_id, task_id): logger.info(user_id, community_id, album_id, task_id) try: user = Users.objects.get(id=user_id) except (DoesNotExist, ValidationError): raise Exception('User does not exist') api = API(user.access_token, v=5.95) response = api.photos.get(owner_id=f'-{community_id}', album_id=album_id, count=50) items = response['items'] count = response['count'] folder = generate_uuid1() photo_album = PhotoAlbum(folder) photo_album.add(items) path = photo_album.make_archive() try: archive = open(path, 'rb') task = Tasks.objects.get(id=task_id) task.archive.put(archive, content_type='application/zip') task.save() finally: archive.close() return
def __init__(self, token, chat_id, title, cache_url, cache_file, cache_temp, sleep_time, scheduler_interval): """ Конструктор ChatGuard :param token: токен авторизации в VK :param chat_id: ID беседы :param title: ожидаемое название беседы :param cache_url: URL изображения беседы :param cache_file: кеш файл-изображение беседы :param cache_temp: файл для временного хранения :param sleep_time: пауза перед chat_job (в секундах) :param scheduler_interval: интервал chat_job (в секундах) """ self.token = token self.chat_id = chat_id self.chat_title = title self.cache_url = cache_url self.cache_file = cache_file self.cache_temp = cache_temp self.sleep_time = sleep_time self.scheduler_interval = scheduler_interval self.buffer_size = 8192 print('Authorization... ', end='') self.api = API(access_token=self.token) print('READY.')
def create_sessions(tokens): for token in tokens: session = Session(access_token=tokens[token]) vk_api = API(session) tokens[token] = vk_api print('All sessions created successfully.') return tokens
def __init__(self, credentials: dict, api_version='5.68', api_language='ru', api_timeout=10): # Параметры для регистрации super().__init__(credentials) if 'auth_token' in credentials and credentials[ 'auth_token'] is not None: self.auth_token = credentials['auth_token'] self.session = vk.Session(self.auth_token) else: self.user_login = credentials['user_login'] self.user_password = credentials['user_password'] self.scope = credentials['scope'] self.app_id = credentials['app_id'] self.session = vk.AuthSession(self.app_id, self.user_login, self.user_password, self.scope) # Параметры для отправки self.chat_id = credentials.get('chat_id') self.chat_group_id = credentials.get('chat_group_id') self.user_id = credentials.get('user_id') self.api_version = api_version # Внутренние объекты VK self.api = API(self.session, v=self.api_version, lang=api_language, timeout=api_timeout) self.last_message_id = Value('i', self.get_last_message_id())
def __init__(self, owner_id, api=None, start_iteration=0): if not api: from vk import Session, API self.api = API(Session()) else: self.api = api self.owner_id = owner_id self.iteration = start_iteration
def vk_info(id, token): session = Session(access_token=token) vk_api = API(session) result = vk_api.users.get(user_ids=[0], fields=['photo_200'])[0] result['image_url'] = result['photo_200'] return result
def auth_vk(): try: session = Session() api = API(session) except Exception as e: print('vk not authed\n', e) return api
def get_friend_list(user_id): session = Session( access_token= "43cceeb8506f5e63619914ac18aee451be826d70ea833e646fcf22440730aeb27ac8a865b0bfde7a0e776" ) vk_api = API(session, v="5.103") user = vk_api.users.get(user_id=280945440) # vk_session = VkApi("+375293164565", "1ron13branch37") # vk_session.auth() # api = vk_session.get_api() # print(api) print(user) return []
def dispatch(self, request, *args, **kwargs): token = request.user.social_auth.get( provider='vk-oauth2').extra_data['access_token'] self.api = API(Session(), access_token=token) groups = self.api.groups.get(filter='editor', extended=True, fields='is_closed')[1:] self.groups = [( None, '---------', )] + [( str(group['gid']), group['name'], ) for group in groups if group['is_closed'] < 2] return super(CreateEventView, self).dispatch(request, *args, **kwargs)
def __init__(self, config, wall=None): super(VKInterface, self).__init__(name='VK Interface', descr='Interface to VK.com') session = AuthSession(scope='wall', app_id=config['app_id'], user_login=config['user_login'], user_password=config['user_password']) API.access_token = config['access_token'] self._vkapi = API(session=session) self.actions = { 'ooops': OopsAction, 'wallpost': ExperimentalWallPost(api=self._vkapi, wall_id=config['owner_id']) }
def post(self, request, *args, **kwargs): print(self.request.POST) form = VkImageUploaderForm(data=self.request.POST) print(form) if form.is_valid(): token = request.user.social_auth.get( provider='vk-oauth2').extra_data['access_token'] print(token) api = API(Session(), access_token=token) path = form.cleaned_data.get('img') print(path) upload_url = form.cleaned_data.get('upload_url') #r = requests.post(upload_url, files={'file1': open(path, 'rb')}) r = requests.post("http://127.0.0.1:8080/", files={'file1': open(path, 'rb')}) return HttpResponse(r.text, content_type="text/plain", status=200) return HttpResponse('kek', content_type="text/plain", status=500)
def fadd(query): global vectors global utokens if not query: print('https://oauth.vk.com/authorize?client_id=' + APP_KEY + \ '&scope=4667422&display=page&v=5.44&response_type=token') else: for token in query: token = token[token.find('access_token=') + 13:] uid = int(token[token.rfind('=') + 1:]) token = token[:token.find('&')] if uid in vectors: myprint('Токен уже есть в списке!', error=True) else: try: vk = API(access_token=token) except Exception as e: myprint(e, error=True) else: utokens.append((token, uid)) name = methods.names(uid, vk) vectors[uid] = vk myprint('Вектор добавлен: {} ({})'.format(name, uid))
def __init__(self, token): self.token = token self.session = Session(access_token=self.token) self.api = API(self.session)
def api(service_token, v): return API(service_token, v=v, lang='en')
from vk import Session, API from __main__ import myprint, vk_request import target #uid -> obj from pickle import load try: utokens = load(open('vectors', 'rb')) except: utokens = [] vectors = dict() if utokens: for token, uid in utokens: vectors[uid] = API(Session(access_token=token)) import methods def flist(): print('Доступные:') i = 1 for uid, obj in vectors.items(): print('{:>2}. {} ({})'.format(i, methods.names(uid, obj), uid)) i += 1 print('Установленные:') i = 1 for uid, info in target.vectors.items(): print('{:>2}. {} -> {} ({} ур.)'.format(i, info[0], uid, info[1])) i += 1
from vk import API, Session from functools import reduce from json import load, dump with open('result.json', 'w') as result: dump( list((lambda api, groups: set.intersection(*map( lambda g: set( reduce( lambda a, o: a + api.groups.getMembers(group_id=g, offset=o)['users'], range(0, api.groups.getMembers(group_id=g)['count'], 1000), [ ])), groups)))(API(Session()), load(open('groups.json')))), result)
def create_session(token): session = Session(access_token=token) vk_api = API(session) return vk_api
def name_to_id(token_0, long_name_0): session = Session(access_token=token_0) vk_api = API(session) information = vk_api.utils.resolveScreenName(screen_name=long_name_0, v=5.80) return information