Example #1
0
def main():
    inputLogin = input('Login: '******'Password: ')
    vk = login_vk(login=inputLogin, password=inputPassword)
    vk_tools = vk_api.VkTools(vk)
    albums = get_albums(vk, vk_tools)
    print(json.dumps(albums))
Example #2
0
def admins_find(api, vk_session, group_id):
    tools = vk_api.VkTools(vk_session)
    group_members = get_group_members(tools, group_id)
    avatars = get_all_photos(api, group_id)

    if not avatars:
        print('group has no avatars.')
        return

    digits = get_digits(avatars)
    matching = find_matching(group_members, digits)
    if len(digits) == 1:
        print(
            f'only 1 avatar loader found. printing all possible candidates: \n{matching}'
        )
        return

    matching_with_friends = get_friends(matching, vk_session)
    matching_pairs = []

    for user in matching:
        for user2 in matching_with_friends:
            if user in matching_with_friends[user2]['items'] and str(
                    user)[-3:] != str(user2)[-3:] and {user, user2
                                                       } not in matching_pairs:
                matching_pairs.append({user, user2})

    matching_pairs = [list(item) for item in matching_pairs]
    if matching_pairs:
        for item in matching_pairs:
            print(item)
    else:
        print(f'several unconnected avatar uploaders found: \n{matching}')
Example #3
0
def wallGet(gr_id, event):
    print("2: ", captcha_sid)
    try:
        int(gr_id)
    except:
        send("Вам нужен именно айди группы, взять его можно, например, отсюда: https://regvk.com/id/", '', event.chat_id)
    login, password = getFake(0)
    vk_session = vk_api.VkApi(login, password)
    wall = '1'
    i = 0
    while (wall == '1') and (i <= 9):
        try:
            try:
                vk_session.auth(token_only=True)
                tools = vk_api.VkTools(vk_session)
                wall = tools.get_all('wall.get', 100, {'owner_id': int('-'+gr_id)})
                idW = wall['items'][random.randint(0, len(wall['items']))]['id']
                owner_id = int(gr_id)
                wall_id = f'wall-{owner_id}_{idW}'
                send('', wall_id, event.chat_id)
                break
            except vk_api.exceptions.Captcha as captcha:
            	return captchaSolver(captcha, event)
        except vk_api.AuthError as error_msg:
            i += 1
            login, password = getFake(i)
            vk_session = vk_api.VkApi(login, password)
Example #4
0
def main():
    """ Пример: получение всех постов со стены """

    login, password = '******', 'mypassword'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.authorization()
    except vk_api.AuthorizationError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)
    """
        VkTools.get_all позволяет получить все итемы, например со стены или
        получить все диалоги, или сообщения. При использовании get_all
        сокращается количество запросов к API за счет метода execute в 25 раз.
        Например за раз со стены можно получить 100 * 25 = 2500, где
        100 - максимальное количество постов, которое можно получить за один
        запрос.
    """

    wall = tools.get_all('wall.get', 100, {'owner_id': 1})
    print('Posts count:', wall['count'])

    if wall['count']:
        print('First post:', wall['items'][0], '\n')

    if wall['count'] > 1:
        print('Last post:', wall['items'][-1])
Example #5
0
    def __init__(self, login, password):
        """
        Allows to get simple statistics of messages in VK
        :param login: VK login
        :type login: str
        :param password: VK password
        :type password: str
        """

        # Create session
        self.__vk_session = vk_api.VkApi(login, password)

        #Problems flag
        self.noProblem = True

        self.__toPrint = ""

        try:
            #Try to authorize
            self.__vk_session.authorization()
            self.__tools = vk_api.VkTools(self.__vk_session)
            self.__vk = self.__vk_session.get_api()

        except vk_api.AuthorizationError as error_msg:
            self.noProblem = False
Example #6
0
    def __init__(self, login, password, proxy=None):
        proxy_dict = {
            'http': proxy,
            'https': proxy,
        }

        login_hash = hashlib.sha256(login.encode("utf-8")).hexdigest()
        vk_session = vk_api.VkApi(login,
                                  password,
                                  config_filename="vk_config." + login_hash +
                                  ".json")
        vk_session.http.proxies = proxy_dict

        try:
            vk_session.auth()
            print("auth_success")
        except vk_api.AuthError as error:
            print(error)
            raise error
        except vk_api.exceptions.Captcha as error:
            print("ERROR: Captcha required for user {}".format(login))
            raise error

        self.tools = vk_api.VkTools(vk_session)
        self.vk = vk_session.get_api()
        self.user_fields = self.user_fields.replace(" ", "").replace("\n", "")
def vk_craw(login, password):
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth(token_only=True)
    except vk_api.AuthError as error_msg:
        print(error_msg)

    tools = vk_api.VkTools(vk_session)

    wall = tools.get_all('wall.get', 8, {'domain': 'itis_kfu'}, limit=25)
    answer = {}
    for i in range(200):
        words = wall['items'][i]['text'].split(' ')
        for word in words:
            word = deEmojify(word)
            if answer.get(word):
                answer[word] = answer[word] + 1
            else:
                answer[word] = 1

    answer = {
        k: v
        for k, v in sorted(answer.items(), key=lambda item: item[1])
    }

    return answer
Example #8
0
def main():
    login, password = '******', 'mypassword'
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.authorization()
    except vk_api.AuthorizationError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)
    start_time = time.time()
    wall = tools.get_all_iter('messages.getHistory', 200, {'user_id': 1})  # идентификатор пользователя
    # wall = tools.get_all_iter('messages.getHistory', 200, {'peer_id': 2000000001})  # для беседы

    wall = list(wall)
    with open('messages.txt', 'w') as f:
        list(map(lambda i: f.write(i['body'] + " \n"), wall))

    d = path.dirname(__file__)
    text = open(path.join(d, 'messages.txt')).read()
    wordcloud = WordCloud(max_words=300, width=1920, height=1080).generate(text)
    print("--- %s time ---" % (time.time() - start_time))
    plt.imshow(wordcloud)
    plt.axis("off")
    manager = plt.get_current_fig_manager()
    manager.resize(*manager.window.maxsize())
    plt.show()
def main(login: str, password: str, group_id: int):
    vk = vk_api.VkApi(login, password)
    try:
        vk.authorization()
    except vk_api.AuthorizationError as error_msg:
        print(error_msg)
        return
    tools = vk_api.VkTools(vk)
    wall = tools.get_all('wall.get', 100, {'owner_id': group_id})
    print('Posts count:', wall['count'])
    con = sqlite3.connect('data1.sqllite')
    cur = con.cursor()
    i = 0
    for post in reversed(wall['items']):
        i = i + 1
        print('>', i)
        post_id = post['id']
        poster_id = post['from_id']
        _ = vk.method('users.get', {
            'user_ids': post['from_id'],
            'fields': 'photo_50'
        })
        try:
            date_name = datetime.datetime.utcfromtimestamp(int(post['date'])).strftime('%Y-%m-%d %H:%M:%S') + "  " + \
                        _[0]['first_name'] + " " + _[0]['last_name']
        except Exception:
            date_name = datetime.datetime.utcfromtimestamp(int(
                post['date'])).strftime('%Y-%m-%d %H:%M:%S') + "  Admin"
        date = post['date']
        likes = post['likes']['count']
        text = post['text'].encode("utf-8", errors='ignore')
        try:
            poster_photo = get_vk_image(_[0]['photo_50'])
        except Exception:
            poster_photo = None
        ins = []
        if 'attachments' in post:
            for attachment in post['attachments']:
                if attachment['type'] == 'photo':
                    _3 = sorted(photos_in_attachment(
                        attachment['photo'].keys()),
                                key=int)
                    ins.append(
                        get_vk_image(attachment['photo']["photo_" +
                                                         _3[len(_3) - 1]]))

        table = [
            post_id, poster_id, date_name, date, likes, text, poster_photo
        ]

        for w in range(10):
            if 0 <= w < len(ins):
                table.append(ins[w])
            else:
                table.append(None)

        cur.execute(
            '''INSERT INTO selfharm(post_id, poster_id, date_name, date, likes, text, poster_photo, insert_1, insert_2, insert_3, insert_4, insert_5, insert_6, insert_7, insert_8, insert_9, insert_10)
                  VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', table)
        con.commit()
Example #10
0
def main(login=None, password=None):
    vk_session = vk_api.VkApi(login, password, captcha_handler=captcha_handler)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)
    wall = tools.get_all_slow_iter('wall.get', 1, {'domain': "itis_kfu"})

    print("Starting processing posts")

    count = 0

    for post in wall.__iter__():
        text = post['text']
        word = ""
        for char in split(text):
            if char == " ":
                word_handler(word)
                word = ""
            elif char_checker(char):
                word += char
        post_handler(post_cache)
        post_cache.clear()
        conn.commit()
        print("Post number " + str(count) + " is loaded")
        count += 1

    print("Total " + str(count) + " posts processed")

    conn.close()
Example #11
0
 def get_posts_count(self, id):
     """
         Получаем количество постов в источнике
     """
     tools = vk_api.VkTools(self.vk_session)
     wall = tools.get_all('wall.get', 1, {'owner_id': id})
     return wall['count']
Example #12
0
    def __init__(self, config):

        vk_session = vk_api.VkApi(login=config['login'],
                                  password=config['password'])
        vk_session.auth(token_only=True)
        self.vk = vk_session.get_api()
        self.tools = vk_api.VkTools(vk_session)
Example #13
0
    def __init__(self, group_id, vk_session):
        self.group_id = group_id
        self.vk_session = vk_session
        self.vk = self.vk_session.get_api()
        self.vk_tools = vk_api.VkTools(self.vk_session)

        self.posts = []
Example #14
0
    def __init__(self, u_login, u_password):
        if not u_login:
            self.u_login = input('Ваш номер телефона Вконтакте: ')
        self.u_login = u_login

        if not u_password:
            self.u_password = input('Ваш пароль Вконтакте: ')
        self.u_password = u_password

        self.vk_session = vk_api.VkApi(self.u_login, self.u_password,
                                       scope='friend, photo, '
                                             'offline, groups',
                                       api_version='5.103',
                                       app_id=7219768,
                                       captcha_handler=captcha_handler)

        self.vk_session.auth()

        self.vk = self.vk_session.get_api()
        self.user = self.vk.users.get()
        self.id = self.user[0]['id']
        self.vk_tools = vk_api.VkTools(self.vk_session)

        # Объявляем ключевые переменные для класса
        self.subj_info_dict = {}
        self.search_req = {}
        self.res_list = []
        self.dict_to_json = {}

        print(f'\nПривет, {self.user[0]["first_name"]}')
Example #15
0
def main():
    login, password = '', ''
    vk_session = vk_api.VkApi(
        login, password,
        auth_handler=auth_handler  
    )

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)

    id = []
    dom = []
    with open('filewithlinks.txt', 'r') as f:
        links = f.readlines()
        for link in links:
            link = re.sub('https?:\/\/vk\.com\/[publicevnt]*', '', link).strip()
            if link.isdigit():
                link = str(-1*link)
                wall = tools.get_all('wall.get', 100, {'owner_id': str(link)})
            else:
                wall = tools.get_all('wall.get', 100, {'domain': link})
            print(wall['count'])
            with open('%s.txt' % link, 'a') as f: 
                for post in wall['items']:
                    f.write(post['text'])
            time.sleep(0.5)
Example #16
0
    def __init__(self):
        self.vk_session = vk_api.VkApi('user', 'pass')
        self.vk_session.auth(token_only=True)

        self.vk = self.vk_session.get_api()
        self.tools = vk_api.VkTools(self.vk_session)
        self.user_info_list = []
Example #17
0
def main():
    """ Пример получения всех постов со стены """

    login, password = '', ''
    vk_session = vk_api.VkApi(login, password)

    try:
        vk_session.auth(token_only=True)
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)

    """ VkTools.get_all позволяет получить все объекты со всех страниц.
        Соответственно get_all используется только если метод принимает
        параметры: count и offset.
        Например может использоваться для получения всех постов стены,
        всех диалогов, всех сообщений, etc.
        При использовании get_all сокращается количество запросов к API
        за счет метода execute в 25 раз.
        Например за раз со стены можно получить 100 * 25 = 2500, где
        100 - максимальное количество постов, которое можно получить за один
        запрос (обычно написано на странице с описанием метода)
    """

    wall = tools.get_all('wall.get', 100, {'owner_id': 1})

    print('Posts count:', wall['count'])

    if wall['count']:
        print('First post:', wall['items'][0], '\n')

    if wall['count'] > 1:
        print('Last post:', wall['items'][-1])
def main():
    parsed = []
    filtered = []
    #Берем список груп из файла
    group_list = read_groups()
    # Загружаем конфиг
    conf = configparser.RawConfigParser()
    conf.read('config.cfg')
    login = conf.get('account', 'login')
    password = conf.get('account', 'password')
    print('Loggin into ' + login)
    vk_session = vk_api.VkApi(login, password, captcha_handler=captcha_handler)
    try:
        vk_session.authorization()
    except vk_api.AuthorizationError as error_msg:
        print(error_msg)
        return
    tools = vk_api.VkTools(vk_session)
    #Поочередно собираем все ид с каждой группы
    for group in group_list:
        print('Parsing ' + group)
        parsed = parsed + parse_ids(group, tools)
    #Удаляем дубликаты
    for user in parsed:
        if user not in filtered:
            filtered.append(user)
    #Результат пишем в result.txt и идем пить кофе
    write_ids(filtered)
    print('Done!')
    input('Press Enter...')
Example #19
0
def delete_docs():
    """Удалить документы"""

    vk_session = get_session()

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    vk_tools = vk_api.VkTools(vk_session)

    owner = vk_session.method('users.get')[0]
    print_owner_info(owner)

    docs = vk_tools.get_all('docs.get', 2000)
    cnt = docs["count"]
    if cnt == 0:
        print("У Вас нет документов")
        return
    else:
        print(f"У Вас {cnt:d} "
              f"{pluralize(cnt, 'документ', 'документа', 'документов')}")

    sure = are_you_sure()
    if not sure:
        return

    for doc in docs['items']:
        print('Удаляем %s...' % doc['title'])
        vk_session.method('docs.delete', values={
            'owner_id': owner['id'],
            'doc_id': doc['id']
        })
Example #20
0
def main():

    vk_session = vk_api.VkApi(credentials.login, credentials.password)

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)
    vk = vk_session.get_api()

    group_info = vk.groups.getById(group_id=group_name)
    group_id = group_info[0]['id']

    new_id = ('-' + str(group_id))
    # wall = tools.get_all('wall.get', 100, {'owner_id': new_id})

    left = posts_to_search
    off = 0
    fetch_at_a_time = 100

    while left > 0:
        _count = fetch_at_a_time if left > fetch_at_a_time else left
        left -= _count
        wall = vk.wall.get(owner_id=new_id, count=_count, offset=off)
        off += _count

        print('Fetched', len(wall['items']), 'posts...')

        for post in wall['items']:
            post_id = post['id']
            t = vk.likes.getList(type='post',
                                 owner_id=new_id,
                                 item_id=post_id,
                                 filter='likes',
                                 friends_only=1,
                                 extended='1')
            if t['count'] > 0:
                print("\nUser(s)", end="")
                for i in t['items'][:-1]:
                    print(i['first_name'],
                          ' ',
                          i['last_name'],
                          ', ',
                          sep='',
                          end='')
                print(t['items'][-1]['first_name'],
                      ' ',
                      t['items'][-1]['last_name'],
                      sep='')
                print('Liked this :',
                      'https://vk.com/wall' + str(new_id) + '_' + str(post_id))
                if len(post['text']):
                    print('Text:', post['text'])
                print('-------------------------------')
            else:
                print(".", end="", flush=True)
 def __init__(self, vk_session):
     """
     Конструктор
     :param vk_session: объект сессии класса VK
     """
     self.api = vk_session.get_api()
     self.tools = vk_api.VkTools(vk_session)
     self.logger = logging.getLogger("ActivityAnalysis")
Example #22
0
    def auth(self, vk_session, interface=None):
        self._interface = self._interface or interface
        self._vk_session = vk_session
        self._vk = self._vk_session.get_api()
        self._vk_tools = vk_api.VkTools(self._vk)

        # self._vk.stats.trackVisitor()
        self._account = self._vk.account.getProfileInfo()
Example #23
0
 def autorization_vk(self):
     self.vk_session = vk_api.VkApi(
         token=
         'f9cd411cd4cf479462f9ed4caca84ff29197404e7853e34d43bcaf0de4ec92e152edd12e304a7e0b37392'
     )  #token='58deb4ef05cb9468fb1c108eb24b71c17b8d880c5ad84f241e5df690bf639dd4fc21ec2f9ed3574f0d504'
     #self.vk_session.auth()
     self.vk = self.vk_session.get_api()
     self.tools = vk_api.VkTools(self.vk_session)
Example #24
0
def main():
    """ Пример получения всех постов со стены """

    login, password = '******', 'тут_пароль'
    vk_session = vk_api.VkApi(
        login, password,
        # функция для обработки двухфакторной аутентификации
        auth_handler=auth_handler
    )

    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)

    """ VkTools.get_all позволяет получить все объекты со всех страниц.
        Соответственно get_all используется только если метод принимает
        параметры: count и offset.
        Например может использоваться для получения всех постов стены,
        всех диалогов, всех сообщений, etc.
        При использовании get_all сокращается количество запросов к API
        за счет метода execute в 25 раз.
        Например за раз со стены можно получить 100 * 25 = 2500, где
        100 - максимальное количество постов, которое можно получить за один
        запрос (обычно написано на странице с описанием метода)
        
        
        https://vk.com/dev/wall.get
        
        Обратите внимание, идентификатор сообщества в параметре owner_id 
        необходимо указывать со знаком "-" 
        — например, owner_id=-1 соответствует идентификатору сообщества ВКонтакте API (club1)
        Для людей ставить впереди знаки "-" не нужно
    """

    wall = tools.get_all('wall.get', 100, {'owner_id':-92767252})

    """
    Некоторые сообщества и люди: 
    -92767252   - Подслушано в Тюрьме
    -57536014   - БТ
    26546404    - я сам, хули
    """

    print('Posts count:', wall['count'])

    with open("data_file.json", "w", encoding='utf8') as write_file:
        json.dump(wall, write_file, ensure_ascii=False)

    # На всякий случай напечатаем в конце первый и последний пост, которые мы обработали
    if wall['count']:
        print('First post:', wall['items'][0], '\n')

    if wall['count'] > 1:
        print('Last post:', wall['items'][-1])
Example #25
0
    def to_cache(self, input_):
        global cached_ids
 
        shortname = input_[input_.rfind("/")+1:]
        if "public" in shortname:
            shortname = shortname[6:]
        print(input_)
 
        r = self.vk_session.method("groups.getById", {"group_ids": shortname})
        group_id = r[0]["id"]
 
        if group_id not in self.cached_ids.keys():
 
            """Все сообщества подписчиков сообщества"""
            users = vk_api.VkTools(self.vk_session).get_all("groups.getMembers", 100, {'group_id':group_id})['items']
            k = int(len(users) / 1000)
            if k:
                users = users[::k]
 
            data_for_clustering = []
            users_publicpages = []
            with vk_api.VkRequestsPool(self.vk_session) as pool:
 
                for i in range(0, len(users), 1000):
                    batch = users[i:i+1000]
                    data_for_clustering.append(pool.method('users.get', {
                            "user_ids": batch,
                            "fields": "sex,age,education,universities,schools,interests,music,movies,bdate,city,country"
                        }))
 
                    for user_id in batch[:5]:
                        users_publicpages.append(pool.method('users.getSubscriptions', {
                                    "user_id": user_id
<<<<<<< HEAD

=======
 
>>>>>>> f1cc8e4d061d67968fec0e3fefba831e4cf5253b
                                }))
            u = []
            try:
                for x in data_for_clustering:
                    try:
                        u.append(x.result)
                    except:
                        pass
            except:
                pass
            new_data_for_clustering = [x for x in u]
            t = []
            for user in users_publicpages:
                try:
                    t.append(user.result['groups']['items'])
                except:
                    pass
            users_publicpages = t
 
            wall50 = self.vk_session.method("wall.get", {"owner_id": -group_id, "filter": "owner", "count": 100})['items'][::2]
Example #26
0
def dump_albums():
    """Выгрузить альбомы"""

    vk_session = get_session()
    try:
        vk_session.auth()
    except vk_api.AuthError as error_msg:
        print(error_msg)
        return

    tools = vk_api.VkTools(vk_session)

    owner = vk_session.method('users.get')[0]
    print_owner_info(owner)

    path = os.path.join(get_user_dump_dir(owner), 'albums')
    os.makedirs(path, exist_ok=True)

    albums = tools.get_all('photos.getAlbums', 1000)
    with open(os.path.join(path, 'albums.json'), 'w', encoding='utf-8') as f:
        json.dump(albums, f, separators=(',', ':'), ensure_ascii=False)

    albums['items'] += [
        {'title': 'Сохранённые фотографии', 'id': 'saved'},
        {'title': 'Фотографии со стены', 'id': 'wall'},
        {'title': 'Фотографии профиля', 'id': 'profile'}
    ]

    for album in albums['items']:
        print('Скачиваем альбом ' + album["title"])
        album_photos = tools.get_all('photos.get', 1000, values={
            'album_id': album['id']
        })
        time.sleep(1)

        album_path = os.path.join(path, f'{escape(album["title"])} [{album["id"]}]'.strip())
        os.makedirs(album_path, exist_ok=True)

        with open(os.path.join(album_path, 'album.json'), 'w', encoding='utf-8') as f:
            json.dump(album_photos, f, separators=(',', ':'), ensure_ascii=False)

        download_all_photos(album_path, album_photos, 'альбома')

        print('Получаем комменты для ' + escape(album["title"]))
        album_comments = {}
        for photo in album_photos['items']:
            comments = tools.get_all('photos.getComments', 100, values={
                'photo_id': photo['id'],
                'need_likes': 1,
                'extended': 1
            })
            time.sleep(1)
            album_comments[photo['id']] = comments

        with open(os.path.join(album_path, 'comments.json'), 'w', encoding='utf-8') as f:
            json.dump(album_comments, f, separators=(',', ':'), ensure_ascii=False)
Example #27
0
 def get_info(self, id):
     """ Получаем list всех id доступных в источнике
         Отдаем: list == post_list[]
     """
     post_list = []
     tools = vk_api.VkTools(self.vk_session)
     wall = tools.get_all_slow_iter('wall.get', 1, {'owner_id': id},
                                    'items')
     post_list.append([post['id'] for post in wall])
     return post_list
Example #28
0
def login():
    app_id = 5882810

    login = "******"
    password = "******"

    vk_session = vk_api.VkApi(login=login, password=password, app_id=app_id)
    vk_session.auth()

    return vk_session.get_api(), vk_api.VkTools(vk_session), vk_session.token
Example #29
0
def main():
    vk_session = vk_api.VkApi(token='')

    tools = vk_api.VkTools(vk_session)

    domain = str(input())
    wall = tools.get_all('wall.get', 100, {'domain': domain})
    with open('%s.txt' % domain, 'a') as f:
        for post in wall['items']:
            f.write(post['text'])
Example #30
0
 def __init__(self):
     """Авторизация ВКонтакте, инициализация сессии и инструментов"""
     session = vk_api.VkApi(os.environ['VK_LOGIN'], os.environ['VK_PASSWORD'], app_id=5559651)
     try:
         session.authorization()
     except vk_api.AuthorizationError as error_msg:
         print(error_msg)
     self.session = session
     self.tools = vk_api.VkTools(session)
     self.pool = vk_api.VkRequestsPool(session)