def get_wall(session, backup_dir): path = backup_dir if backup_dir else ROOT_DIR create_backup_dir(path) tools = VkTools(session) wall = tools.get_all('wall.get', 100, {'owner_id': session.token['user_id']}) print(wall) create_json(wall, path)
def get_user_groups(session, backup_dir): path = backup_dir if backup_dir else ROOT_DIR tools = VkTools(session) groups = tools.get_all('groups.get', 1000, { 'owner_id': session.token['user_id'], 'extended': 1 }) write_json(groups, path)
def get_all_album(session, id, backup_dir, title=None): if title is None: title = id tools = VkTools(session) photos = tools.get_all('photos.get', 1000, { 'owner_id': session.token['user_id'], 'album_id': id, 'photo_sizes': 1 }) extractes_photo = extract_photos_to_tmp(photos, title, backup_dir) print('Saved photos: %d, downloaded: %d' % (photos['count'], len(extractes_photo))) return extractes_photo
def __init__(self, *args, filename=None, directory=None, leave_chats=False, delete_dialogs=False, proxies=None, **kwargs): super().__init__(*args, **kwargs) self.http.proxies = proxies if not self.token['access_token']: logger.info('Авторизация') self.auth() self.vk = self.get_api() self.tools = VkTools(self) logger.info('Получение информации о пользователе') with VkRequestsPool(self) as pool: user = pool.method('users.get') dialogs = pool.method('messages.getDialogs') self.leave_chats = leave_chats self.delete_dialogs = delete_dialogs self.user_id = user.result[0]['id'] dialog_count = dialogs.result['count'] logger.info('Получение диалогов') self.dialogs = [] for dialog in tqdm(self.get_all_dialogs(), total=dialog_count, leave=False): self.dialogs.append(dialog) self.alias = {} if directory: self.output = 'dir' self.directory = directory else: self.output = 'zip' if not filename: filename = 'vk-dialog-backup-{}.zip'.format( datetime.now().strftime('%d-%m-%Y-%H-%M-%S')) elif os.path.splitext(filename)[1] != '.zip': filename += '.zip' logger.info('Открытие файла ' + filename) self.zipf = ZipFile(filename, 'w')
def get_albums_comments(session, id, backup_dir, title=None): if title is None: title = id tools = VkTools(session) comments = tools.get_all('photos.getAllComments', 100, { 'owner_id': session.token['user_id'], 'album_id': id }) path = get_album_dir_path(title, backup_dir) file = codecs.open('%s/comments.json' % (path), 'w', 'utf-8') file.write(json.dumps(comments, ensure_ascii=False)) file.close() print('Save comments for: %s' % (title))
def main(): vk_session = VkApi(settings.LOGIN, settings.PASSWORD, scope='wall') vk_session.auth(token_only=True) tools = VkTools(vk_session) input_url = input('Введите ссылку на пост: ') all_comments = get_all_comments(input_url, tools) print('\n'.join(all_comments))
def photos_iter(session, owner_id, limit): tools = VkTools(session) photos = tools.get_all_slow_iter('photos.get', 100, values={ 'owner_id': owner_id, 'photo_sizes': 1, 'rev': 1, 'album_id': 'wall' }, limit=limit) for photo in photos: src = extract_photos(photo) if src is None: continue yield { 'big': src['big'], 'small': src['small'], 'date': photo['date'], 'id': photo['id'], 'owner_id': photo['owner_id'], 'album_id': photo['album_id'] }
def get_user_matches(self, user_data, offset=0): birth_year = int(user_data.bdate.split('.')[2]) age = time.localtime().tm_year - birth_year need_fields = ['sex', 'bdate', 'city', 'relation'] result = VkTools(self.user_session).get_all_iter( 'users.search', 1000, { 'sex': user_data.sex == 1 and 2 or 1, 'has_photo': 1, 'hometown': user_data.city, 'age_from': age - 2, 'age_to': age + 2, 'fields': ','.join(need_fields), "offset": offset*1000 }) return result
def auth(): global vk global vk_group global vk_tools global my_id global vk_longpoll global vk_group_longpoll global vk_group_id vk_login, vk_pass = ('логин', 'пароль') vk_session = vk_api.VkApi(vk_login, vk_pass) vk_session.auth() vk = vk_session.get_api() vk_tools = VkTools(vk_session) vk_group_session = vk_api.VkApi( token= 'токен группы, выступающей в качестве бота, помогающего разбирать диалоги' ) vk_group = vk_group_session.get_api() my_id = int(vk_session.token['user_id']) vk_longpoll = VkLongPoll(vk_session) vk_longpoll = VkLongPoll(vk_session) vk_group_longpoll = VkLongPoll(vk_group_session) vk_group_id = -00000000 # ID группы
class VkDialogBackuper(VkApi): def __init__(self, *args, filename=None, directory=None, leave_chats=False, delete_dialogs=False, proxies=None, **kwargs): super().__init__(*args, **kwargs) self.http.proxies = proxies if not self.token['access_token']: logger.info('Авторизация') self.auth() self.vk = self.get_api() self.tools = VkTools(self) logger.info('Получение информации о пользователе') with VkRequestsPool(self) as pool: user = pool.method('users.get') dialogs = pool.method('messages.getDialogs') self.leave_chats = leave_chats self.delete_dialogs = delete_dialogs self.user_id = user.result[0]['id'] dialog_count = dialogs.result['count'] logger.info('Получение диалогов') self.dialogs = [] for dialog in tqdm(self.get_all_dialogs(), total=dialog_count, leave=False): self.dialogs.append(dialog) self.alias = {} if directory: self.output = 'dir' self.directory = directory else: self.output = 'zip' if not filename: filename = 'vk-dialog-backup-{}.zip'.format( datetime.now().strftime('%d-%m-%Y-%H-%M-%S')) elif os.path.splitext(filename)[1] != '.zip': filename += '.zip' logger.info('Открытие файла ' + filename) self.zipf = ZipFile(filename, 'w') def auth_handler(self): logger.info('Необходимо подтверждение авторизации') code = input('Введите код из личного сообщения от Администрации: ') remember = ask_yes_or_no('Запомнить этот аккаунт?') return code, remember def get_all_dialogs(self): return self.tools.get_all_iter('messages.getDialogs', 200) def get_all_messages(self, **kwargs): return self.tools.get_all_iter('messages.getHistory', 200, kwargs) def run(self): try: self._run() finally: self._write('alias.json', self._dumps(self.alias)) if self.output == 'zip': self.zipf.close() def _run(self): for dialog in self.dialogs: preview = dialog['message'] chat_id = preview.get('chat_id') if chat_id: peer_id = 2_000_000_000 + chat_id filename = 'chat_{}.json'.format(chat_id) logger.info('Обработка беседы {} ({})'.format( chat_id, preview['title'])) else: peer_id = preview['user_id'] filename = 'user_{}.json'.format(preview['user_id']) logger.info('Обработка диалога с пользователем {}'.format( preview['user_id'])) if self.leave_chats: if chat_id and not (preview['action'] == 'chat_kick_user' and preview['action_mid'] == self.user_id): self.vk.messages.remove_chat_user(chat_id=chat_id, user_id=self.user_id) logger.info('Выход из беседы {}'.format(chat_id)) total_messages = self.vk.messages.get_history( peer_id=peer_id)['count'] + 1 logger.info('Сохранение {} сообщений'.format(total_messages)) messages = [] members = set() for message in tqdm(self.get_all_messages(peer_id=peer_id), total=total_messages, leave=False): messages.append(message) members.add(str(message['from_id'])) users = self.vk.users.get(user_ids=','.join(members)) names = { u['id']: u['first_name'] + ' ' + u['last_name'] for u in users } self._write(filename, self._dumps({ 'names': names, 'items': messages })) self.alias[filename] = preview['title'] if chat_id else names[ preview['user_id']] if self.delete_dialogs: self.vk.messages.delete_dialog(peer_id=peer_id) def _dumps(self, obj): return json.dumps(obj, indent=4, ensure_ascii=False) def _write(self, filename, content): logger.info('Сохранение файла ' + filename) if self.output == 'zip': with self.zipf.open(filename, 'w') as file: file.write(content.encode()) elif self.output == 'dir': with open(os.path.join(self.directory, filename), 'w') as file: file.write(content)
def print_posts(posts): for p in posts: print(f'- https://vk.com/wall{p["owner_id"]}_{p["id"]}') # Авторизация vk_session = vk_api.VkApi('логин', 'пароль') vk_session.auth() vk = vk_session.get_api() # Скачивание temp = vk.wall.get(count=1, filter='owner') count = temp['count'] print(f'Найдено {count} постов. Загрузка всех постов..') tools = VkTools(vk_session) posts = tools.get_all('wall.get', 100, {'filter': 'owner'})['items'] print('Загрузка завершена') # Фильтрация def is_lottery(post, threshold=7): scores = { 'лот': 7, 'лотере': 10, 'розыгрыш': 8, 'подписк': 5, 'репост': 6, 'победител': 9, 'приз': 2, 'место': 1
import itertools import random from pprint import pprint import sqlite3 import requests import time import vk_api from vk_api import VkTools, VkUpload from polling_user import auth HUMORESKI = -92876084 PESY = -134182185 vk, vk_session = auth('me') upload = VkUpload(vk_session) tools = VkTools(vk_session) def get_full_wall(id): return tools.get_all('wall.get', 100, {'owner_id': id}) def get_single_random_post(id): pic = '' session = requests.Session() try: posts_count = vk.wall.get(owner_id=id)['count'] offset = random.randint(0, posts_count - 1) while True: response = vk.wall.get(owner_id=id, offset=offset, count=1)['items'][0]
def main() -> int: """ Точка входа. :return: код выхода (сейчас не используется) :rtype: int """ # Prepare home dir if not os.path.exists(config.BOT_HOME): os.makedirs(config.BOT_HOME) os.makedirs(logs_path) os.makedirs(saves_path) os.makedirs(tmp_path) elif not os.path.isdir(config.BOT_HOME): os.remove(config.BOT_HOME) os.makedirs(config.BOT_HOME) os.makedirs(logs_path) os.makedirs(saves_path) os.makedirs(tmp_path) # Prepare logger global log log = prepare_logger() log.info("-=-=-= NEW LAUNCH =-=-=-") # Init inline queries try: log.info("inline init...") global soundboard_sounds response = requests.get(config.SERVER_ADDRESS + "/index.json") json_arr = response.json() for sound in json_arr: soundboard_sounds.append(InlineSound(sound)) global inline_disabled inline_disabled = False log.info("...success!") except: log.error("...failure, inline disabled!", exc_info=True) # Init VK API try: log.info("vk init...") vk_session = vk_api.VkApi(login=config.VK_LOGIN, password=config.VK_PASSWORD, config_filename=os.path.join( saves_path, 'vk_config.v2.json'), api_version=str(VK_VER)) vk_session.auth() global vk vk = vk_session.get_api() log.info("...success!") log.info("vk tools init...") global vk_tools vk_tools = VkTools(vk_session) log.info("...success!") log.info("vk test...") response = vk.groups.getById(group_id="team", fields="id", version=VK_VER) log.info("...success!") log.debug("With response: {}".format(response)) global vk_disabled vk_disabled = False except: log.error("...failure, VK disabled!", exc_info=True) # Init whatanime.ga API try: log.info("whatanime init...") global whatanime whatanime = whatanime_ga.WhatAnimeClient(config.WHATANIME_TOKEN) log.info("...success! UID: {}".format(whatanime.user_id)) global whatanime_disabled whatanime_disabled = False except: log.error("...failure, whatanime disabled!", exc_info=True) # Init iqdb.org API try: log.info("iqdb init...") global iqdb iqdb = iqdb_org.IqdbClient() log.info("...success! Boorus:\n{}".format(iqdb.boorus_status)) global iqdb_disabled iqdb_disabled = False except: log.error("...failure, iqdb disabled!", exc_info=True) # Init neuroshit try: log.info("neuroshit init...") test_str = run_neuroshit(2, "b") log.info(f"...success! Test str: {test_str}") global neuroshit_disabled neuroshit_disabled = False except subprocess.CalledProcessError as exc: log.error( f"...failure, neuroshit disabled (procerr)!\n" f"stdout: {exc.stdout}\n" f"stderr: {exc.stderr}", exc_info=True) except subprocess.TimeoutExpired: log.error(f"...failure, neuroshit disabled (proctimeout)!", exc_info=True) except: log.error(f"...failure, neuroshit disabled (unknown)!", exc_info=True) # Load info from disk states_save_path = os.path.join(saves_path, "states.pkl") users_save_path = os.path.join(saves_path, "users.pkl") retry_count = 1 while retry_count < 6: log.info(f"loading info from {saves_path} (try #{retry_count})...") try: with open(states_save_path, "rb") as states_file: global chat_states chat_states = pickle.load(states_file) with open(users_save_path, "rb") as users_file: global users_dict users_dict = pickle.load(users_file) log.info("...success!") break except: log.error(f"(try #{retry_count}) SHIT! Load failed!", exc_info=True) time.sleep(retry_count) # Not a bug too retry_count += 1 telebot.logger.setLevel(config.LOG_LEVEL) telebot.apihelper.proxy = { 'http': config.PROXY, 'https': config.PROXY, } # Start log.info("Starting polling") bot.polling(none_stop=True) # Block thread! log.info("Stopped!") return EXIT_SUCCESS