Ejemplo n.º 1
0
    def addFriends(self):
        requester = HRequester()

        for item in self.chil:
            getUrl = UrlAPI(item.token)
            requester(getUrl.friends.getRequests(count=1000, out=0), item.session, item)

        response = requester.request()

        for r in response:

            try:
                j = json.loads(r[0].text)['response']
                item = r[2][0]
                masReceived = [received for received in j['items']]
                self.listRecived.append([item, masReceived])
            except Exception as e:
                print(e)

        widgetList = [w for w in self.listRecived if len(w[1]) > 0]

        for w in widgetList:
            item, masReceived = w
            getUrl = UrlAPI(item.token)
            added_user_id = self.getAddedUser(masReceived)

            if added_user_id != None:
                requester(getUrl.friends.add(user_id=added_user_id), item.session)

        requester.request()
Ejemplo n.º 2
0
    def filing(self):
        requester = HRequester()

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)

            urlAvatars = getUrl.users.get(fields='photo_200')
            requester(urlAvatars, acc.session, acc)

        response = requester.request()

        for r in response:
            acc = r[2][0]

            try:
                dataAvatars = json.loads(r[0].text)['response'][0]

                if dataAvatars[
                        'photo_200'] != 'https://vk.com/images/camera_200.png':
                    requester(dataAvatars['photo_200'], acc.session, acc)
                else:
                    photo = Photo(self, None, acc)
                    self.mainLayout.addWidget(photo, alignment=Qt.AlignLeft)

            except Exception as e:
                print(repr(e))

        response = requester.request()

        for r in response:
            acc = r[2][0]
            photoByte = r[0]
            photo = Photo(self, photoByte, acc)
            self.mainLayout.addWidget(photo, alignment=Qt.AlignLeft)
Ejemplo n.º 3
0
    def getResult(self, session, captcha_id):
        requester = HRequester()

        dataGet = {
            'key': self.token,
            'action': 'get',
            'id': captcha_id,
            'json': '1'
        }

        time.sleep(5)

        requester(self.urlGet, session, params=dataGet)
        requester(
            self.urlGet,
            session,
        )
        response = requester.request()

        for r in response:
            j = json.loads(r[0].text)

            if j['request'] == 'CAPCHA_NOT_READY':
                return 'CAPCHA_NOT_READY'

            elif j['status'] == 1:
                return j['request']

            elif j['request'] == 'ERROR_ZERO_BALANCE':
                print('Нет денег на балансе')
                return 'error'

            else:
                print(j)
                return 'error'
Ejemplo n.º 4
0
    def solve(self, session, captcha_url):
        captcha_id = 0
        captcha_result = ''
        captcha_url = re.sub('[\\\]', '', captcha_url)
        requester = HRequester()
        requester(captcha_url, session)
        response = requester.request()

        for r in response:

            with tempfile.NamedTemporaryFile(suffix='.jpg') as temp:
                temp.write(r[0].content)
                temp.flush()
                # Отправляем на рукапча изображение капчи
                captcha_id = self.postCaptcha(session, temp.name)
                break

        while True:
            captcha_result = self.getResult(session, captcha_id)

            if captcha_result == 'CAPCHA_NOT_READY':
                print('captcha_class', captcha_result)
                pass

            elif captcha_result == 'error':
                print('captcha_class', captcha_result)
                return 'error'

            else:
                print('captcha_class', captcha_result)
                return captcha_result
Ejemplo n.º 5
0
    def sendRequest(self):
        getUrl = UrlAPI(self.item.token)
        requester = HRequester()

        for i in range(3):
            user = random.choice(self.parent.members['items'])
            requester(getUrl.friends.add(user_id=user['id']), self.item.session)

        response = requester.request()
        for r in response:
            j = json.loads(r[0].text)

            if 'error' in j:

                if j['error']['error_code'] == 14:
                    print('КАПЧА-----')
                else:
                    print(j)

            elif 'response' in j:

                if j['response'] == 1:
                    print('Запрос отправлен')
                    self.countSendedRequests.setText(str(int(self.countSendedRequests.text()) + 1))
                else:
                    print(j)

            else:
                print(j)
Ejemplo n.º 6
0
    def chekAcc(self):
        errorListAcc = []
        requester = HRequester()
        chil = [
            item for item in self.itemList
            if item.b.checkState() == 2 and item.frozen == 0
        ]

        for acc in chil:
            getUrl = UrlAPI(acc.token)

            requester(getUrl.account.setOnline(), acc.session, acc)

        requests = requester.request()
        for r in requests:
            acc = r[2][0]
            j = json.loads(r[0].text)

            if 'response' in j:

                if j['response'] == 1:
                    pass
                else:
                    print(j)
                    return

            elif 'error' in j:
                acc.responseError = j
                errorListAcc.append(acc)

        if len(errorListAcc) == 0:
            self.statusBar.showMessage('Обновленно')
        else:
            self.widgetsConductor(SurveyForm(self, errorListAcc), show=True)
Ejemplo n.º 7
0
    def lineRepostDownload(self):
        self.group_list_repost = []

        post_str = self.gui.lineRepost.text().strip('https://vk.com/wall')

        requester = HRequester()
        acc = random.choice(self.chil)
        getUrl = UrlAPI(acc.token)
        url = getUrl.wall.getById(posts=post_str, extended=1)
        requester(url, acc.session)

        response = requester.request()

        for r in response:

            try:
                j = json.loads(r[0].text)
            except:
                continue

            if 'response' in j:

                for group in j['response']['groups']:
                    self.group_list_repost.append(group['id'])

                self.signal.emit()
            else:
                print(j)
Ejemplo n.º 8
0
    def resevedOneFriend(self):
        requester = HRequester()
        countCaptcha = 0
        countLimitRequests = 0
        countSuccessfully = 0

        widgetList = [w for w in self.widgetList if len(w.masReceived) > 0]

        for w in widgetList:
            getUrl = UrlAPI(w.item.token)
            added_user_id = w.masReceived.pop(0)

            requester(getUrl.friends.add(user_id=added_user_id), w.item.session, w, added_user_id)

        response = requester.request()
        for r in response:
            w = r[2][0]
            added_user_id = r[2][1]
            j = json.loads(r[0].text)

            if 'error' in j:

                if j['error']['error_code'] == 14:
                    countCaptcha += 1

                elif j['error']['error_code'] == 6:
                    countLimitRequests += 1

                elif j['error']['error_code'] == 177:
                    getUrl = UrlAPI(w.item.token)
                    rDel = w.item.session.get(getUrl.friends.delete(user_id=added_user_id),
                                              proxies=w.item.session.proxies)
                    countSuccessfully += 1

                else:
                    print(j)

            elif 'response' in j:

                if j['response'] > 1:
                    countSuccessfully += 1
                    w.countReceivedRequests.setText(str(int(w.countReceivedRequests.text()) - 1))

                else:
                    print(j)

            else:
                print(j)

        if countSuccessfully / len(response) == 1:
            self.parent.statusBar.showMessage('Успешно добавлено у всех')
            print('Успешно добавлено у всех')
        else:
            self.parent.statusBar.showMessage('Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(
                countCaptcha) + ' Кол-во лимитов:' + str(countLimitRequests))
            print('Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(
                countCaptcha) + ' Кол-во лимитов:' + str(countLimitRequests))
Ejemplo n.º 9
0
    def refreshName(self):
        errorListAcc = []
        requester = HRequester()
        chil = [(item.session, item.token, item.user_id)
                for item in self.itemList
                if item.b.checkState() == 2 and item.frozen == 0]
        error = 0

        for acc in chil:
            session = acc[0]
            token = acc[1]
            user_id = acc[2]
            getUrl = UrlAPI(token)

            requester(getUrl.account.getProfileInfo(), session, user_id)

        with self.con:
            cur = self.con.cursor()
            cur.execute("SELECT name, last_name, user_id FROM accaunt")
            rows = cur.fetchall()

        requests = requester.request()
        for r in requests:
            user_id1 = r[2][0]
            j = json.loads(r[0].text)

            if 'response' in j:
                name = j['response']['first_name']
                lastName = j['response']['last_name']

                nameG, lastNameG, user_idG = [
                    m for m in rows if user_id1 == m[2]
                ].pop()

                if name == nameG and lastName == lastNameG:
                    pass
                else:
                    with self.con:
                        cur = self.con.cursor()
                        cur.execute(
                            "UPDATE accaunt SET name=?, last_name=? WHERE user_id=?",
                            (name, lastName, user_id1))
                        self.con.commit()

            elif 'error' in j:
                error += 1
                acc.responseError = j
                errorListAcc.append(acc)

        if error == 0:
            self.statusBar.showMessage('Обновленно')
        else:
            self.statusBar.showMessage('Обновленно. Проблемных аккаунтов:' +
                                       str(error))
            self.widgetsConductor(SurveyForm(self, errorListAcc), show=True)
Ejemplo n.º 10
0
    def unsubscribeEverything(self):
        requester = HRequester()
        countCaptcha = 0
        countLimitRequests = 0
        countSuccessfully = 0

        for w in self.widgetList:
            getUrl = UrlAPI(w.item.token)

            for i in range(5):
                try:
                    user = w.masSended.pop(0)
                    requester(getUrl.friends.delete(user_id=user), w.item.session, w)
                except:
                    break

        response = requester.request()
        for r in response:
            w = r[2][0]
            j = json.loads(r[0].text)

            if 'error' in j:

                if j['error']['error_code'] == 14:
                    countCaptcha += 1

                elif j['error']['error_code'] == 6:
                    countLimitRequests += 1

                else:
                    print(j)

            elif 'response' in j:

                if j['response']['success'] == 1:
                    countSuccessfully += 1
                    w.countSendedRequests.setText(str(int(w.countSendedRequests.text()) - 1))

                else:
                    print(j)

            else:
                print(j)

        if countSuccessfully / len(response) == 1:
            self.parent.statusBar.showMessage('Успешно удалено у всех')
            print('Успешно удалено у всех')
        else:
            self.parent.statusBar.showMessage('Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(
                countCaptcha) + ' Кол-во лимитов:' + str(countLimitRequests))
            print('Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(
                countCaptcha) + ' Кол-во лимитов:' + str(countLimitRequests))
Ejemplo n.º 11
0
    def save(self):
        requester = HRequester()
        dic = {}

        if self.lineName.text() == '':
            pass
        else:
            dic.update(first_name=self.lineName.text())

        if self.lineLastName.text() == '':
            pass
        else:
            dic.update(last_name=self.lineLastName.text())

        if self.lineBD.text() == '':
            pass
        else:
            dic.update(bdate=self.lineBD.text())

        if self.lineCityId.text() == '':
            pass
        else:
            dic.update(city_id=self.lineCityId.text())

        if self.lineStatus.text() == '':
            pass
        else:
            dic.update(status=self.lineStatus.text())

        if self.lineVisibleBD.checkState() == 2:
            dic.update(bdate_visibility=1)
        else:
            dic.update(bdate_visibility=0)

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)

            # Close coments under wall post and display walls record
            url1 = getUrl.account.setInfo(name='own_posts_default', value=0)
            url2 = getUrl.account.setInfo(name='no_wall_replies', value=1)

            requester(url1, acc.session)
            requester(url2, acc.session)
            requester(getUrl.account.saveProfileInfo(**dic), acc.session)

        response = requester.request()
        for r in response:
            j = json.loads(r[0].text)

            print(j)
Ejemplo n.º 12
0
    def setPhotos(self, acc, dataPhotos):
        requester = HRequester()

        for item in dataPhotos['items']:
            urlPhoto = item['photo_604']
            requester(urlPhoto, acc.session, item['id'])

        response = requester.request()

        for r in response:
            photoByte = r[0]
            photoId = r[2][0]

            photo = Photo(self, photoByte, photoId, acc)
            self.mainLayout.addWidget(photo, alignment=Qt.AlignLeft)
Ejemplo n.º 13
0
    def mouseDoubleClickEvent(self, QMouseEvent):
        requester = HRequester()
        getUrl = UrlAPI(self.acc.token)

        requester(getUrl.photos.delete(photo_id=self.id), self.acc.session)
        response = requester.request()

        for r in response:
            j = json.loads(r[0].text)

            try:
                if j['response'] == 1:
                    self.deleteLater()
            except Exception as e:
                print(repr(e))
Ejemplo n.º 14
0
    def mouseDoubleClickEvent(self, QMouseEvent):
        requester = HRequester()
        getUrl = UrlAPI(self.acc.token)

        requester(getUrl.photos.deleteAlbum(album_id=self.albumId),
                  self.acc.session)
        response = requester.request()

        for r in response:
            j = json.loads(r[0].text)

            try:
                if j['response'] == 1:
                    self.deleteLater()
            except KeyError:
                print(KeyError, 'Ошибка удаления альбома', r[0])
Ejemplo n.º 15
0
    def settingPrivacy(self):
        requester = HRequester()
        con = sql.connect('db/db.sqlite3')
        cur = con.cursor()

        #Login
        responseLoginPage = self.session.get('https://m.vk.com',
                                             proxies=self.session.proxies)

        soup = BeautifulSoup(responseLoginPage.text)
        urlLogin = soup.find('form').get('action')

        with con:
            cur.execute(
                'SELECT login, pass, user_id FROM accaunt WHERE token = ?',
                (self.token, ))
            row = cur.fetchone()
            login = row[0]
            password = row[1]
            user_id = row[2]

            self.session.params.update(email=login)
            self.session.params.update({'pass': password})

            responseLogin = self.session.get(urlLogin,
                                             allow_redirects=False,
                                             proxies=self.session.proxies)

            params = ['mail_send', 'profile', 'audios', 'gifts', 'wall_send']

            for param in params:
                self.setting(param)

        # Close coments under wall post and display walls record
        url1 = self.createApi.account.setInfo(name='own_posts_default',
                                              value=0)
        url2 = self.createApi.account.setInfo(name='no_wall_replies', value=1)
        requester(url1, self.session)
        requester(url2, self.session)
        response = requester.request()
        for r in response:
            j = json.loads(r[0].text)
            if j['response'] == 1:
                print(
                    'Успешно включено отображение записей на стене пользователя и закрыты коментарии на стене'
                )
Ejemplo n.º 16
0
    def sendRequestEverything(self):
        requester = HRequester()
        countCaptcha = 0
        countSuccessfully = 0

        for w in self.widgetList:
            getUrl = UrlAPI(w.item.token)

            for i in range(3):
                user = random.choice(self.members['items'])
                requester(getUrl.friends.add(user_id=user['id']), w.item.session, w)

        response = requester.request()
        for r in response:
            w = r[2][0]
            j = json.loads(r[0].text)

            if 'error' in j:

                if j['error']['error_code'] == 14:
                    countCaptcha += 1
                else:
                    print(j)

            elif 'response' in j:

                if j['response'] == 1:
                    countSuccessfully += 1
                    w.countSendedRequests.setText(str(int(w.countSendedRequests.text()) + 1))

                elif j['response'] == 2:
                    print('Добавлен ранее')

                else:
                    print(j)

            else:
                print(j)

        if countSuccessfully / len(self.widgetList) == 3:
            self.parent.statusBar.showMessage('Успешно отправлено у всех')
            print('Успешно отправлено у всех')
        else:
            self.parent.statusBar.showMessage(
                'Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(countCaptcha))
            print('Кол-во успешных:' + str(countSuccessfully) + ' Кол-во капч:' + str(countCaptcha))
Ejemplo n.º 17
0
    def deleteAll(self):
        requester = HRequester()

        for post in self.gui.allPost:
            getUrl = UrlAPI(post.token)
            requester(getUrl.wall.delete(post_id=post.post_id), post.session,
                      post)

        response = requester.request()
        for r in response:
            j = json.loads(r[0].text)
            post = r[2][0]

            if j['response'] == 1:
                post.deleteLater()
            else:
                print('Error Response by delete post', r[0].text)
Ejemplo n.º 18
0
class HAddGroup(QWidget):
    def __init__(self, parent=None, mas=None):
        super().__init__(parent, Qt.Window)
        self.ui()
        self.masSessions = mas
        self.requester = HRequester()

        self.btn_send.clicked.connect(self.leaveGroup)

        self.show()

    def ui(self):

        mainLayout = QVBoxLayout(self)

        self.btn_send = QPushButton('Send')
        self.btn_send.setFocus()
        self.line = QLineEdit()

        mainLayout.addWidget(self.btn_send)
        mainLayout.addWidget(self.line)

        self.line.setFocus()

    def leaveGroup(self):

        for mas in self.masSessions:
            session = mas[0]
            token = mas[1]
            getUrl = UrlAPI(token)
            url = getUrl.groups.leave(group_id=self.line.text())
            self.requester(url, session)

        response = self.requester.request()
        for item in response:
            try:
                res = json.loads(item[0].text)

                if res['response'] == 1:
                    print('Успешно')
                else:
                    print(res)
            except:
                print('Ошибка', item[0].text)
Ejemplo n.º 19
0
    def filing(self, acc):
        requester = HRequester()
        getUrl = UrlAPI(acc.token)
        urlAlbums = getUrl.photos.getAlbums(need_system=1)
        requester(urlAlbums, acc.session, 'albums')
        requester(
            getUrl.photos.getAll(no_service_albums=0, skip_hidden=1,
                                 count=200), acc.session, 'photos')

        response = requester.request()

        for r in response:

            if r[2][0] == 'photos':
                dataPhotos = json.loads(r[0].text)['response']
                self.setPhotos(acc, dataPhotos)

            elif r[2][0] == 'albums':
                dataAlbums = json.loads(r[0].text)['response']
                self.setAlbums(acc, dataAlbums)
Ejemplo n.º 20
0
    def addVideo(self):
        requester = HRequester()
        chil = [
            item for item in self.itemList
            if item.b.checkState() == 2 and item.frozen == 0
        ]
        randomAcc = random.choice(chil)
        getMainUrl = UrlAPI(randomAcc.token)

        responseMain = requests.get(getMainUrl.video.get(owner_id='-29573241',
                                                         count=5),
                                    proxies=randomAcc.session.proxies)
        responseJson = json.loads(responseMain.text)['response']['items']

        for video in responseJson:
            owner_id = video['owner_id']
            video_id = video['id']

            for acc in chil:
                getUrl = UrlAPI(acc.token)
                requester(
                    getUrl.video.add(video_id=video_id, owner_id=owner_id),
                    acc.session, acc.user_id)

            responseAdd = requester.request()

            for r in responseAdd:
                j = json.loads(r[0].text)
                user_id = r[2][0]

                if 'response' in j:
                    if j['response'] == 1:
                        pass
                    else:
                        print('Не добавленно', user_id, r[0].text)

                else:
                    print('Ошибка', user_id, r[0].text)

        print('----------')
Ejemplo n.º 21
0
    def settingPrivacy(self, acc):
        requester = HRequester()
        con = sql.connect('db/db.sqlite3')
        cur = con.cursor()

        #Login
        responseLoginPage = acc.session.get('https://m.vk.com',
                                            proxies=acc.session.proxies)

        soup = BeautifulSoup(responseLoginPage.text)
        urlLogin = soup.find('form').get('action')

        acc.session.params.update(email=acc.login)
        acc.session.params.update({'pass': acc.password})

        responseLogin = acc.session.get(urlLogin,
                                        allow_redirects=False,
                                        proxies=acc.session.proxies)

        params = ['mail_send', 'profile', 'audios', 'gifts', 'wall_send']

        for param in params:
            self.setting(acc, param)

        # Close coments under wall post and display walls record
        getUrl = UrlAPI(acc.token)
        url1 = getUrl.account.setInfo(name='own_posts_default', value=0)
        url2 = getUrl.account.setInfo(name='no_wall_replies', value=1)
        requester(url1, acc.session)
        requester(url2, acc.session)
        response = requester.request()
        for r in response:
            j = json.loads(r[0].text)
            if j['response'] == 1:
                print(
                    'Успешно включено отображение записей на стене пользователя и закрыты коментарии на стене'
                )

        con.close()
Ejemplo n.º 22
0
    def filing(self):
        requester = HRequester()

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)
            urlAvatars = getUrl.users.get(fields='photo_50')
            requester(urlAvatars, acc.session, acc)

        response = requester.request()

        for r in response:
            acc = r[2][0]

            try:
                dataAvatars = json.loads(r[0].text)['response'][0]

                if dataAvatars[
                        'photo_50'] != 'https://vk.com/images/camera_50.png':
                    acc.b.setChecked(True)
                else:
                    acc.b.setChecked(False)

            except Exception as e:
                print(repr(e))
Ejemplo n.º 23
0
class User:
    def __init__(self, name, token, session):
        self.name = name
        self.timeout = 0
        self.interval1 = 75
        self.interval2 = 95
        self.session = session
        self.getUrl = UrlAPI(token)
        self.requester = HRequester()
        self.photoIdsList = []


    def run(self):

        for photo_id in self.photoIdsList:
            self.like(photo_id)
            time.sleep(random.randint(self.interval1, self.interval2))


    def like(self, photo_id):
        captcha = False
        captcha_result = ''
        captcha_sid = ''

        while True:

            owner_id, item_id = photo_id.split('_')

            if captcha == False:
                url = self.getUrl.likes.add(type='photo', owner_id=owner_id, item_id=item_id)
            else:
                url = self.getUrl.likes.add(type='photo', owner_id=owner_id, item_id=item_id, captcha_sid=captcha_sid, captcha_key=captcha_result)

            self.requester(url, self.session)

            response = self.requester.request()
            for r in response:
                j = json.loads(r[0].text)

                try:

                    if 'likes' in j['response']:

                        with open('files/completed', 'a') as file:
                            file.write(str(owner_id) + '\n')

                        print('+', owner_id)
                        return

                except Exception as e:
                    print(e)
                    print(r[0].text)

                    if 'error' in j:

                        if j['error']['error_code'] == 14:
                            print("Решаем капчу")
                            captcha = Captcha()
                            captcha_result = captcha.solve(self.session, j['error']['captcha_img'])
                            captcha_sid = j['error']['captcha_sid']

                            if captcha_result == 'error':
                                self.interval = 2000
                                return
                            else:
                                captcha = True
                                print(self.name, 'Captcha', captcha_result)

                        if j['error']['error_code'] == 15:

                            with open('files/completed', 'a') as file:
                                file.write(str(owner_id) + '\n')

                            print('+', owner_id)
                            return

                        if j['error']['error_code'] == 17:
                            self.interval = 99999
                            return
Ejemplo n.º 24
0
    def cleaningGroup(self):
        chil = [
            item for item in self.itemList
            if item.b.checkState() == 2 and item.frozen == 0
        ]
        requester = HRequester()

        for acc in chil:
            getUrl = UrlAPI(acc.token)
            requester(getUrl.groups.get(extended=1, count=999), acc.session,
                      getUrl)

        responseGroups = requester.request()
        countGroups = [
            len(json.loads(r[0].text)['response']['items'])
            for r in responseGroups
        ]
        curProc = 0

        for c in range(len(countGroups)):
            try:
                countGroups[c] = countGroups[c] + countGroups[c - 1]
            except:
                continue

        countOperationLeft = countGroups[len(countGroups) - 1] * 2012
        countOperationProc = 100 / countOperationLeft
        print('Кол-во операций:', countOperationLeft)

        for r in responseGroups:
            getter = r[2][0]
            session = r[1]
            items = json.loads(r[0].text)['response']['items']

            with open('files/cities', 'r') as f:
                lines = f.readlines()

            for item in items:
                for line in lines:
                    result = re.search(line.lower().strip('\n'),
                                       item['name'].lower())

                    if result:

                        def delete():
                            try:
                                leave = session.get(
                                    getter.groups.leave(group_id=item['id']),
                                    proxies=session.proxies,
                                    timeout=5)
                                j = json.loads(leave.text)
                            except:
                                return

                            if 'response' in j:
                                if j['response'] == 1:
                                    print('Удалено', item['name'])
                                    return
                            elif 'error' in j:
                                if 'error_code' in j['error']:
                                    if j['error']['error_code'] == 6:
                                        print('Повтор удаления')
                                        time.sleep(5)
                                        delete()
                                        return
                                else:
                                    print('Неизвестный error', leave.text)
                            else:
                                print(leave.text)

                        delete()

                    countOperationLeft -= 1
                    curP = round(countOperationProc * countOperationLeft)

                    if curP == curProc:
                        pass
                    else:
                        curProc = curP
                        print('Осталось:', str(curProc) + '%')
Ejemplo n.º 25
0
    def sendRequests(self):
        otherAccList = []
        requester = HRequester()

        with self.con:
            cur = self.con.cursor()
            cur.execute('SELECT * FROM friends')
            friendsRelation = cur.fetchall()

        # Function to find relation of users and added in requester
        def added(acc1, acc2, amountAdded):

            if acc1.user_id == acc2.user_id:
                return 'next'

            elif str(acc1.user_id) + '_' + str(acc2.user_id) in friendsRelation:
                return 'next'

            elif str(acc2.user_id) + '_' + str(acc1.user_id) in friendsRelation:
                return 'next'

            else:
                getUrl = UrlAPI(acc.token)
                requester(getUrl.friends.add(user_id=acc2.user_id), acc1.session, acc1.user_id, acc2.user_id)
                amountAdded += 1

                if amountAdded < self.number_of_additions:
                    return 'amountAdded'

                if amountAdded == self.number_of_additions:
                    return 'complete'

        # search for accounts that do not have main names
        for acc in self.parent.masAccaunts:

            if acc['name'] in self.mainNames:
                pass
            else:
                otherAccList.append(ItemAcc(self, acc))

        # accounts iterate and call function 'added'
        for acc in self.chil:
            print(acc)
            amountAdded = 0

            for otherAcc in otherAccList:
                result = added(acc, otherAcc, amountAdded)
                print(result)

                if result == 'complete':
                    break

                elif result == 'next':
                    continue

                elif result == 'amountAdded':
                    amountAdded += 1

        response = requester.request()
        successfully = 0
        error = 0

        for r in response:
            j = json.loads(r[0].text)
            user_id1, user_id2 = r[2]
            print(user_id1, user_id2)

            if 'response' in j:

                if j['response'] == 1:
                    successfully += 1

                    with self.con:
                        cur = self.con.cursor()
                        cur.execute('INSERT INTO friends VALUES(?,?)', (user_id1, user_id2))
                        self.con.commit()

                else:
                    print(j)
                    error += 1

            else:
                print(j)
                error += 1

        if error == 0:
            print('Успешно у всех. Кол-во выбранных:', str(len(self.chil)), 'Кол-во удачно отправленных:',
                  str(successfully / 3))
        else:
            print('Кол-во выбранных:', str(len(self.chil)), 'Кол-во удачно отправленных:', str(successfully / 3),
                  'Кол-во ошибок', str(error / 3))
Ejemplo n.º 26
0
class RepostsForm(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent, Qt.Window)

        self.reposts = []
        self.requester = HRequester()

        self.ui()
        self.getRepostsFromBD()
        self.downloadReposts()

        QShortcut(QtGui.QKeySequence(Qt.Key_Escape),
                  self).activated.connect(self.close)

    def getRepostsFromBD(self):
        con = sql.connect('./db/db.sqlite3')
        cur = con.cursor()

        with con:
            cur.execute('SELECT proxy,user_agent,token FROM accaunt')
            random_acc = random.choice(cur.fetchall())
            self.proxy = random_acc[0]
            self.user_agent = random_acc[1]
            self.token = random_acc[2]

            cur.execute('SELECT group_post_id FROM repost')
            reposts = cur.fetchall()
            reposts.reverse()
            [self.reposts.append(r[0]) for r in reposts]

            if not self.reposts:
                self.deleteLater()
                return print('Нет репостов')

    def getLine(self, n):
        self.numberOfCall += 10
        masPosts = []

        for i in range(self.numberOfCall - 500, self.numberOfCall):
            try:
                masPosts.append(self.mas_ids[i])
            except Exception as exeption:
                print(exeption)
                return '''var posts''' + str(
                    n) + '''= API.wall.getById({"posts":"''' + ",".join(
                        self.reposts) + '''", "fields":"photo_id"});'''

        return '''var friends''' + str(
            n) + '''= API.users.get({"user_ids":"''' + ",".join(
                masUsers) + '''"});'''

    def downloadReposts(self):
        con = sql.connect('./db/db.sqlite3')
        cur = con.cursor()

        s = Session()
        s.proxies.update(http=self.proxy, https=self.proxy, all=self.proxy)
        s.headers.update({
            'User-Agent': self.user_agent,
            'Accept': MyData.ACCEPT,
            'Accept-Language': MyData.ACCEPT_LANGUAGE
        })

        getUrl = UrlAPI(self.token)

        for i in range(divmod(len(self.reposts), 20)[0] + 1):

            if i > divmod(len(self.reposts), 20)[0]:
                url = getUrl.wall.getById(posts=','.join([
                    self.reposts[j]
                    for j in range(i * 20, i * 20 +
                                   divmod(len(self.reposts), 20)[1])
                ]))
                self.requester(url, s)
            elif i <= divmod(len(self.reposts), 20)[0]:
                # try:
                url = getUrl.wall.getById(posts=','.join(
                    [self.reposts[j] for j in range(i * 20, i * 20 + 20)]))
                self.requester(url, s)
                # except Exception as e:
                #     print(e)
                print(i, i * 20)

        response = self.requester.request()
        for r in response:

            try:
                records = json.loads(r[0].text)['response']
            except Exception as e:
                print(e)
                print(r[0].text)
                return

            for record in records:
                repostWidget = RepostWidget()
                repostWidget.users = []
                repostWidget.group_post_id = str(
                    record['owner_id']) + '_' + str(record['id'])

                # set information
                if 'views' in record:
                    repostWidget.setInfo(record['likes']['count'],
                                         record['reposts']['count'],
                                         record['views']['count'])
                else:
                    repostWidget.setInfo(record['likes']['count'],
                                         record['reposts']['count'])

                # set text
                repostWidget.setText(record['text'])

                # set attachments
                if 'attachments' in record:

                    for attach in record['attachments']:

                        if attach['type'] == 'photo':
                            self.requester(attach['photo']['photo_604'], s,
                                           repostWidget)

                # Append users in recordWidget
                with con:
                    cur.execute(
                        'SELECT user_id FROM accaunt_repost WHERE group_post_id=?',
                        (str(record['owner_id']) + '_' + str(record['id']), ))
                    [
                        repostWidget.users.append(user[0])
                        for user in cur.fetchall()
                    ]

                self.myForm.addWidget(repostWidget)

            responseImg = self.requester.request()
            for item in responseImg:
                recordWidget = item[2][0]
                recordWidget.setAttachments(item[0].content)

    def ui(self):
        a = QApplication.desktop().availableGeometry()
        self.setGeometry(300, 100, a.width() / 2, a.height() / 2)

        # Create scroll and put in general layout
        self.myForm = QFormLayout()

        scrollWidget = QWidget()
        scrollWidget.setLayout(self.myForm)
        scroll = QScrollArea()
        scroll.setWidget(scrollWidget)
        scroll.setWidgetResizable(True)
        layout = QVBoxLayout(self)
        layout.addWidget(scroll)

        self.show()
Ejemplo n.º 27
0
    def mouseDoubleClickEvent(self, QMouseEvent):
        requester = HRequester()
        con = sql.connect(MyData.CWD + '/db/db.sqlite3')
        cur = con.cursor()

        with con:
            query = '''
                    select
                    accaunt.user_id, accaunt.proxy, accaunt.user_agent, accaunt.token, accaunt_repost.post_id
                    from accaunt, accaunt_repost
                    where
                    accaunt.user_id = accaunt_repost.user_id and accaunt_repost.group_post_id = ?
                    '''
            cur.execute(query, (self.group_post_id, ))
            # query = 'select proxy, user_agent, token from accaunt where user_id in (%s)' % ', '.join(['?'] * len(self.users_posts))
            # cur.execute(query, [user[0] for user in self.users_posts])
            accaunts = cur.fetchall()

        for acc in accaunts:
            user_id = acc[0]
            proxy = acc[1]
            user_agent = acc[2]
            token = acc[3]
            post_id = acc[4]

            session = Session()
            session.proxies.update(http=proxy, https=proxy, all=proxy)
            session.headers.update({'User-Agent': user_agent})

            getUrl = UrlAPI(token)
            requester(getUrl.wall.delete(post_id=post_id), session, user_id,
                      post_id)

        response = requester.request()
        for r in response:
            user_id = r[2][0]
            post_id = r[2][1]
            j = json.loads(r[0].text)

            print(user_id, post_id)

            try:
                if j['response'] == 1:
                    cur.execute(
                        'DELETE FROM accaunt_repost WHERE user_id = ? and post_id = ?',
                        (user_id, post_id))
                    con.commit()
                else:
                    print('Ошибка удаления поста у', user_id, 'post_id',
                          post_id)
            except KeyError:
                print(KeyError, j)

        print('Удаление завершено')

        cur.execute('SELECT * FROM accaunt_repost WHERE group_post_id = ?',
                    (self.group_post_id, ))
        rezult = cur.fetchall()
        print(rezult, rezult)

        if not rezult:
            cur.execute('DELETE FROM repost WHERE group_post_id = ?',
                        (self.group_post_id, ))
            con.commit()
            self.deleteLater()
Ejemplo n.º 28
0
class WorkerObject(QObject):
    signalComplete = pyqtSignal(str)

    def __init__(self, parent=None, chil=None):
        super(self.__class__, self).__init__(parent)

        self.chil = chil
        self.requester = HRequester()
        self.postRequester = HPostRequester()

    @pyqtSlot()
    def startWork(self):
        self.signalComplete.emit()

    def sendComment(self, group_id, post_id, comment_text):
        error = []

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)
            url = getUrl.wall.createComment(owner_id=group_id,
                                            post_id=post_id,
                                            message=comment_text)
            self.requester(url, acc.session, acc)

        response = self.requester.request()
        for item in response:
            acc = item[2][0]

            try:
                res = json.loads(item[0].text)
                if 'comment_id' in res['response']:
                    pass

                else:
                    error.append([res, acc.user_id])

            except:
                error.append([item[0].text, acc.user_id])

        if len(error) == 0:
            print('All comments send')
        else:
            [print(i) for i in error]

        self.signalComplete.emit('comment')

    def repost(self, post_str, group_list, sleep_time, likeCheckState):

        time.sleep(sleep_time)

        if post_str != '':
            con = sql.connect('db/db.sqlite3')
            cur = con.cursor()

            with con:
                cur.execute(
                    'SELECT group_post_id FROM repost WHERE group_post_id=?',
                    (post_str.strip('wall'), ))
                row = cur.fetchone()

                if row:
                    print('Такой репост уже есть')
                    self.signalComplete.emit('existing repost')
                    return

            if likeCheckState == 2:
                self.sendLike(post_str)
            else:
                self.sendRepost(post_str)

        if group_list:
            self.addGroup(group_list)

        self.signalComplete.emit('reposts made')

    def sendRepost(self, post_str):
        error = []
        atLeastOneRepost = False
        con = sql.connect('db/db.sqlite3')
        cur = con.cursor()
        group_post_id = post_str.strip('wall')

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)
            url = getUrl.wall.repost(object=post_str)
            self.requester(url, acc.session, acc.user_id)

        response = self.requester.request()
        for item in response:
            user_id = item[2][0]
            res = json.loads(item[0].text)

            if 'response' in res and 'success' in res['response']:

                post_id = res['response']['post_id']

                if res['response']['success'] == 1:
                    with con:
                        cur.execute(
                            'INSERT INTO accaunt_repost (user_id, group_post_id, post_id) VALUES (?,?,?)',
                            (user_id, group_post_id, post_id))
                        atLeastOneRepost = True
                else:
                    if 'error' in res:
                        error.append([res, user_id])
                    else:
                        error.append([res, user_id])

        if atLeastOneRepost == True:
            with con:
                cur.execute('INSERT INTO repost (group_post_id) VALUES (?)',
                            (group_post_id, ))
                print('Репосты сделаны')

        if len(error) == 0:
            print('Все репосты сделаны удачно')
        else:
            [print(i) for i in error]

        self.signalComplete.emit('reposts')

    def sendLike(self, post_str):
        error = []
        atLeastOneRepost = False

        for acc in self.chil:
            owner_id, item_id = post_str.strip('wall').split('_')
            getUrl = UrlAPI(acc.token)
            url = getUrl.likes.add(type='post',
                                   owner_id=owner_id,
                                   item_id=item_id)
            self.requester(url, acc.session, acc.user_id)

        response = self.requester.request()
        for item in response:
            user_id = item[2][0]
            res = json.loads(item[0].text)

            if 'response' in res and 'likes' in res['response']:
                atLeastOneRepost = True
            else:
                if 'error' in res:
                    error.append([res, user_id])
                else:
                    error.append([res, user_id])

        if atLeastOneRepost == True:
            print('Лайки поставлены')

        if len(error) == 0:
            print('Все лайки поставлены удачно')
        else:
            [print(i) for i in error]

        self.signalComplete.emit('reposts')

    def addGroup(self, group_list):
        error = []

        for group in group_list:

            for acc in self.chil:
                getUrl = UrlAPI(acc.token)
                url = getUrl.groups.join(group_id=group)
                self.requester(url, acc.session, acc)

        response = self.requester.request()
        for item in response:
            acc = item[2][0]

            try:
                res = json.loads(item[0].text)
                if res['response'] == 1:
                    pass

                else:
                    error.append([res, acc.user_id])

            except:
                error.append([item[0].text, acc.user_id])

        if len(error) == 0:
            print('Все группы добавленны удачно')
        else:
            [print(i) for i in error]

        self.signalComplete.emit('groups added')

    def pinPost(self, number_post):
        error = []

        for acc in self.chil:
            getUrl = UrlAPI(acc.token)
            url = getUrl.wall.get(extended=1, count=1, offset=number_post)
            self.requester(url, acc.session, acc, getUrl)

        response = self.requester.request()
        for r in response:
            acc = r[2][0]
            getUrl = r[2][1]

            try:
                res = json.loads(r[0].text)['response']['items'][0]
                post_id = res['id']
                self.requester(getUrl.wall.pin(post_id=post_id), acc.session,
                               acc)

            except Exception as e:
                print(repr(e))
                error.append([r[0].text, acc.user_id])

        response = self.requester.request()
        for r in response:
            acc = r[2][0]

            try:
                res = json.loads(r[0].text)['response']

                if res != 1:
                    error.append([r[0].text, acc.user_id])

            except:
                error.append([r[0].text, acc.user_id])

        if len(error) == 0:
            print('All pined')
        else:
            [print(i) for i in error]
Ejemplo n.º 29
0
    def filingRecord(self, acc, records, dataWall):
        print('filling record')
        requester = HRequester()

        # mark reckords wall
        for i in range(len(dataWall['items'])):
            print(len(records))
            try:
                record = records[i][0]
            except IndexError:
                continue

            # Set post ID
            record.post_id = dataWall['items'][i]['id']

            # Set name
            if dataWall['items'][i]['from_id'] == dataWall['items'][i][
                    'owner_id']:
                record.setNameLayout('Я', '.', 'src/icon.png')
            else:
                record.setNameLayout(str(dataWall['items'][i]['from_id']), '.',
                                     'src/icon.png')

            # Post source
            if 'data' in dataWall['items'][i]['post_source']:
                record.setPostSource(
                    dataWall['items'][i]['post_source']['data'])

            # Set data
            record.setDateLayout(dataWall['items'][i]['date'])

            # Set text
            record.setText(dataWall['items'][i]['text'])

            # Attechments
            if 'attachments' in dataWall['items'][i]:
                for item in dataWall['items'][i]['attachments']:
                    if item['type'] == 'photo':
                        requester(item['photo']['photo_130'], acc.session,
                                  record.setAttachments)

            # Information
            if 'views' in dataWall['items'][i]:
                record.setInfo(dataWall['items'][i]['likes']['count'],
                               dataWall['items'][i]['reposts']['count'],
                               dataWall['items'][i]['views']['count'])
            else:
                record.setInfo(dataWall['items'][i]['likes']['count'],
                               dataWall['items'][i]['reposts']['count'])

            # Repost
            if 'copy_history' in dataWall['items'][i]:
                repost = records[i][1]
                repost.deleteInformation()
                repost.delButton.deleteLater()
                repost.frame.setFrameShape(QFrame.StyledPanel)

                repost.setText(dataWall['items'][i]['copy_history'][0]['text'])
                repost.setDateLayout(
                    dataWall['items'][i]['copy_history'][0]['date'])
                '''Set attachments'''
                if 'attachments' in dataWall['items'][i]['copy_history'][0]:
                    for item in dataWall['items'][i]['copy_history']:

                        try:
                            for ite in item['attachments']:
                                if ite['type'] == 'photo':
                                    requester(ite['photo']['photo_604'],
                                              acc.session,
                                              repost.setAttachments)
                        except KeyError:
                            continue
                '''Set profile info'''
                for item in dataWall['items'][i]['copy_history']:
                    owner_id = item['owner_id']
                    if owner_id < 0:
                        for group in dataWall['groups']:
                            if group['id'] == (owner_id * -1):
                                requester(group['photo_50'], acc.session,
                                          repost.setNameLayout, group['name'],
                                          '.')

                    elif owner_id > 0:
                        for profile in dataWall['profiles']:
                            if profile['id'] == (owner_id):
                                requester(profile['photo_50'], acc.session,
                                          repost.setNameLayout,
                                          profile['first_name'],
                                          profile['last_name'])

                record.repostLayout.addWidget(repost)

        response = requester.request()

        for r in response:

            if len(r[2]) == 1:
                seter = r[2][0]
                photo = r[0].content
                seter(photo)
            else:
                rList = list(r[2])
                seter = rList.pop(0)
                photo = r[0].content
                args = [i for i in rList]
                seter(*args, photo)
Ejemplo n.º 30
0
class LikeMachine(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.con = sql.connect('db/db.sqlite3')
        self.cur = self.con.cursor()

        self.ui()
        self.parent = parent

        self.btn_avatar.clicked.connect(self.avatar)
        self.btn_numRecord.clicked.connect(self.numRecord)
        self.btn_specificRecord.clicked.connect(self.specificRecord)

        self.chil = [
            item for item in self.parent.itemList
            if item.b.checkState() == 2 and item.frozen == 0
        ]
        self.lenght = len(self.chil)
        self.requester = HRequester()

    def ui(self):
        self.btn_avatar = QPushButton('Аватар')

        self.line_numberRevord = QLineEdit()
        self.btn_numRecord = QPushButton('Запись по счету')
        numRecLay = QHBoxLayout()
        numRecLay.addWidget(self.line_numberRevord)
        numRecLay.addWidget(self.btn_numRecord)

        self.lineType = QLineEdit()
        self.lineEditOwner = QLineEdit()
        self.lineEditItem = QLineEdit()
        self.lineEditOwner.setText('Owner id')
        self.lineEditItem.setText('Item id')
        self.btn_specificRecord = QPushButton('Конкретная запись')
        specRecLay = QHBoxLayout()
        specRecLay.addWidget(self.lineType)
        specRecLay.addWidget(self.lineEditOwner)
        specRecLay.addWidget(self.lineEditItem)
        specRecLay.addWidget(self.btn_specificRecord)

        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(self.btn_avatar)
        mainLayout.addLayout(numRecLay)
        mainLayout.addLayout(specRecLay)

    def numRecord(self):

        for item in self.chil:
            getUrl = UrlAPI(item.token)
            self.requester(
                getUrl.wall.get(count=1, offset=self.line_numberRevord.text()),
                item.session, item)

        response = self.requester.request()
        for r in response:
            record = json.loads(r[0].text)['response']['items'][0]
            acc = r[2][0]
            acc.item_id = record['id']

        self.run('post')

    def avatar(self):
        getMainUrl = UrlAPI(self.chil[0].token)

        url = getMainUrl.users.get(user_ids=','.join(
            [str(item.user_id) for item in self.chil]),
                                   fields='photo_id')
        responseMain = requests.get(url, proxies=self.chil[0].session.proxies)

        data = json.loads(responseMain.text)['response']

        for acc in data:
            try:
                info = acc['photo_id'].strip('photo')
            except KeyError:
                print(acc)

                for i in range(len(self.chil)):
                    if int(self.chil[i].user_id) == int(acc['id']):
                        self.chil.pop(i)
                        break

                self.lenght = len(self.chil)

                continue

            info = re.split('_', info)
            owner_id = info[0]
            item_id = info[1]

            item = [
                item for item in self.chil
                if int(item.user_id) == int(owner_id)
            ]
            item[0].item_id = item_id

        self.run('photo')

    def run(self, type_record):

        for i in range(self.lenght):

            with self.con:
                self.cur.execute('SELECT * FROM like')
                likeTable = self.cur.fetchall()

            for j in range(self.lenght):
                getUrl = UrlAPI(self.chil[j].token)

                if j + i > len(self.chil) - 1:
                    index_owner_id = i - (self.lenght - 1 - j) - 1

                    if index_owner_id < 0:
                        index_owner_id = 0

                else:
                    index_owner_id = j + i

                owner_item_id = str(
                    self.chil[index_owner_id].user_id) + '_' + str(
                        self.chil[index_owner_id].item_id)

                # Проверям есть ли запить о данном юзере с итемом, если нету, то создаем
                if not [row for row in likeTable if row[1] == owner_item_id]:
                    with self.con:
                        self.cur.execute(
                            'INSERT INTO like (user_id, owner_item_id) VALUES (?,?)',
                            (self.chil[index_owner_id].user_id, owner_item_id))
                        self.con.commit()

                #Смотрим есть ли данный лайк, если нето, то продолжаем
                with self.con:
                    self.cur.execute(
                        'SELECT * FROM accaunt_like WHERE owner_item_id=? and liker=?',
                        (owner_item_id, self.chil[j].user_id))
                    rowAL = self.cur.fetchone()

                    if not rowAL:
                        urlLikeAdd = getUrl.likes.add(
                            type=type_record,
                            owner_id=self.chil[index_owner_id].user_id,
                            item_id=self.chil[index_owner_id].item_id)
                        self.requester(urlLikeAdd, self.chil[j].session,
                                       self.chil[j], self.chil[index_owner_id])

            if not self.requester.taskList:
                print('pass')
                continue
            else:
                response = self.requester.request()
                for r in response:
                    countUnsuccessfulLike = 0

                    try:
                        jResponse = json.loads(r[0].text)['response']
                        liker = r[2][0]
                        owner = r[2][1]
                    except KeyError:
                        print(KeyError, r[0].text)
                        countUnsuccessfulLike += 1
                        continue

                    if 'likes' in jResponse:
                        with self.con:
                            cur = self.con.cursor()
                            owner_item_id = str(owner.user_id) + '_' + str(
                                owner.item_id)
                            cur.execute(
                                'INSERT INTO accaunt_like (owner_item_id, liker) VALUES(?,?)',
                                (owner_item_id, liker.user_id))
                    else:
                        countUnsuccessfulLike += 1
                        print(r[0].text)

                if countUnsuccessfulLike == 0:
                    print('Лайки поставлены')
                else:
                    print('Кол-во не поставленных:', countUnsuccessfulLike)

                time.sleep(random.randint(120, 200))

            print('Выполнено:', str(i) + '/' + str(self.lenght))
            if i == 25:
                self.deleteLater()

    def specificRecord(self):
        errorListAcc = []

        for i in range(self.lenght):
            getUrl = UrlAPI(self.chil[i].token)
            urlLikeAdd = getUrl.likes.add(type=self.lineType.text(),
                                          owner_id=self.lineEditOwner.text(),
                                          item_id=self.lineEditItem.text())
            self.requester(urlLikeAdd, self.chil[i].session, self.chil[i])

        response = self.requester.request()
        for r in response:
            acc = r[2][0]
            j = json.loads(r[0].text)

            if 'response' in j:

                if j['response'] == 1:
                    pass
                else:
                    print(j)

            elif 'error' in j:
                print(j)
                acc.responseError = j
                errorListAcc.append(acc)

        if len(errorListAcc) == 0:
            self.parent.statusBar.showMessage('Лайки поставлены')
        else:
            self.parent.statusBar.showMessage('Лайки поставлены с ошибками')
            self.parent.widgetsConductor(SurveyForm(self.parent, errorListAcc),
                                         show=True)