Exemplo n.º 1
0
def auth():
    def check_pass(password, login):
        try:
            resp = requests.get(auth_url.format(login=login,
                                                password=password)).json()
            if 'error' in resp.keys():
                return False
        except:
            return False

        return True

    login = read(s_in='Введите логин: ')
    password = read(
        s_in='Введите пароль: '
    )  #, s_out='Не удалось авторизоваться, попробуй еще раз...',

    #check_fun=check_pass, kwargs={'login': login}, )

    def auth_handler():
        key = input("Введите код авторизации: ")
        remember_device = True
        return key, remember_device

    vk_session = VkApi(login,
                       password,
                       app_id=2685278,
                       auth_handler=auth_handler)
    vk_session.auth()

    api = vk_session.get_api()
    return api, vk_session.token['user_id']
Exemplo n.º 2
0
class User:
    def __init__(self, login, password):

        try:
            print('VK Logging in...')
            self.vk = VkApi(login=login, password=password)
            self.vk.auth(token_only=True)
            self.api = self.vk.get_api()
            self.info = self._get_user_info()
            print('VK Successfully logged in.')

        except Exception as e:
            raise e

    def _get_user_info(self):
        return self.api.users.get()[0]

    def comment_info(self, source_id, comment_id):
        try:
            self.api.wall.getComment(source_id=source_id, comment_id=comment_id, extended=True)

        except ApiError as e:
            print("Couldn't get comment info: %s" % e)

    def remove_comment(self, source_id, comment_id):
        try:
            self.api.wall.deleteComment(owner_id=source_id, comment_id=comment_id)
            print('Comment removed.')
            return True

        except ApiError as e:
            print('Warning! Comment was not removed: %s | %s %s' % (e, source_id, comment_id))
            return False
def connect(login, password):
    try:
        conn = VkApi(login=login, password=password)
        conn.auth()
        return conn
    except Exception as e:
        print(e)
        sys.exit(0)
Exemplo n.º 4
0
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))
Exemplo n.º 5
0
def authorize(login, password):
    print("VK authorization")
    print("Authorization attempt")
    vk_session = VkApi(login=login, password=password)
    try:
        vk_session.auth(reauth=True, token_only=True)
    except AuthError as ae:
        print(ae)
        sys.exit(1)
    print("Success")
    return vk_session
Exemplo n.º 6
0
def setting(login=None, password=None, access_token=None):
    global session, api_vk
    session = VkApi(login=login,
                    password=password,
                    token=access_token,
                    auth_handler=auth_handler,
                    captcha_handler=captcha_handler,
                    config_filename='../vk_config.v2.json')
    if login and password:
        session.auth()
    api_vk = session.get_api()
Exemplo n.º 7
0
Arquivo: havk.py Projeto: 4yach/Havk
    def init(cls, login, password, on_2fa=None):
        api = VkApi(
            login,
            password,
            auth_handler=on_2fa)

        try:
            api.auth()
        except Exception as exc:
            return Havk(None, exc)

        return Havk(VkAudio(api))
Exemplo n.º 8
0
def main():
    """
    Пример использования longpoll
    https://vk.com/dev/using_longpoll
    https://vk.com/dev/using_longpoll_2
    """

    vk_api = VkApi(Bot.LOGIN, Bot.PASSWORD)
    vk_method = vk_api.get_api()

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

    longpoll = VkLongPoll(vk_api)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and not event.from_me:
            # Личное сообщение
            if event.from_user:
                # Добавить логирование
                # print(f'Личное сообщение от {event.user_id}:')
                # print(f'    {event.text}')
                answer = Controller.parse_request(event.text)
                vk_method.messages.send(user_id=event.user_id,
                                        message=answer,
                                        random_id=Model.get_random_int())
            # Упоминание в чате
            elif event.from_chat and hasattr(
                    event, 'mentions') and Bot.BOT_ID in event.mentions:
                # Добавить логирование
                # print(f'Сообщение в чате {event.chat_id} от {event.user_id}:')
                # print(f'    {event.text}')
                # answer = choice(Bot.ANSWERS)
                # print(f'    Ответ: {answer}')
                answer = Controller.parse_request(event.text)
                vk_method.messages.send(chat_id=event.chat_id,
                                        message=answer,
                                        random_id=Model.get_random_int())
            # Остальные сообщения
            else:
                # Добавить логирование
                # print(f'Сообщение в чате {event.chat_id} от {event.user_id}:')
                # print(f'    {event.text}')
                pass
Exemplo n.º 9
0
 def __init__(self):
     self.user = 0
     self.prop_data = {
         "login": "",
         "password": "",
         "multiplier": 1,
         "group": ""
     }
     self.multiplier = 1
     self.group_id = 0
     self.login = ""
     self.password = ""
     try:
         with open("res/properties.json", "r") as read_file_prop:
             self.prop_data = json.load(read_file_prop)
     except FileNotFoundError:
         with open("res/properties.json", "w") as write_file_prop:
             json.dump(self.prop_data, write_file_prop)
     self.set_properties()
     if self.login != "" and self.password != "":
         vk_session = VkApi(self.login, self.password)
         vk_session.auth()
         self.vk = vk_session.get_api()
Exemplo n.º 10
0
def load_avatars():
    login, password = json.load(open('secret.json'))
    vk = VkApi(login, password)
    vk.auth()

    target = 'annndruha'

    members = []
    try:
        id = int(target.replace('id', ''))
    except:
        id = vk.method('users.get', {'user_ids': target})[0]['id']

    members = vk.method('friends.get', {'user_id': id})["items"]

    print(len(members))
    #print(members)

    members_str = ','.join(map(str, members))
    members_data = vk.method('users.get', {
        'user_ids': members_str,
        'fields': 'photo_400_orig'
    })

    for data in members_data:
        try:
            url = data['photo_400_orig']
            id = data['id']
            filename = f'avatars/{id}.jpg'

            response = requests.get(url)
            if response.status_code == 200:
                with open(filename, 'wb') as imgfile:
                    imgfile.write(response.content)
        except:
            pass
Exemplo n.º 11
0
    def initializeTracksCount(self):
        session = VkApi(self.authScreen.loginInput.text,
                        self.authScreen.passInput.text,
                        auth_handler=self.authHandler,
                        captcha_handler=self.captchaHandler)

        try:
            session.auth(reauth=True)
        except Exception as ex:
            self.screenManagement.transition.direction = "left"
            self.screenManagement.current = "auth"

            print(ex)

            return

        audio = vkapi.audio(session)
        self.tracksCount = audio.get_len_user_audio()

        if self.tracksCount != 0:
            self.startScreen.tracksCount.label = "Аудиозаписей: " + str(
                self.tracksCount)
        else:
            self.startScreen.tracksCount.label = "Нет аудиозаписей"

        user = session.method("users.get", {
            "user_ids": audio.user_id,
            "fields": "photo_200"
        })

        self.startScreen.username.text = user[0]["first_name"] + ' ' + user[0][
            "last_name"]
        self.startScreen.avatar.source = user[0]["photo_200"]

        self.screenManagement.transition.direction = "left"
        self.screenManagement.current = "start"
Exemplo n.º 12
0
class Handler:
    def __init__(self, group_token, user_login, user_password):
        self.group_sess = VkApi(token=group_token)
        self.group_api = self.group_sess.get_api()

        self.user_sess = VkApi(login=user_login, password=user_password)
        self.user_sess.auth()
        self.user_api = self.user_sess.get_api()

        self.long_poll = self._get__long_poll()
        self.command_manager = CommandManager()

    def _send_message(self, user_id, text):
        while 1:
            try:
                self.group_api.messages.send(user_id=user_id, message=text)
            except Exception as e:
                logging.exception(e)
                sleep(10)
            else:
                logging.info("Send text: {}".format(text.replace('\n', ' ')))
                break

    def _handle_message(self, event):
        logging.info("Performing message: {}".format(event.text))

        try:
            result = self.command_manager.process(
                self._get_current_user(event.user_id), self.user_api, event)
        except Exception as e:
            logging.exception(e)
            result = 'Произошла внутренняя ошибка. Повторите попытку позже'

        if not result:
            result = 'Готово'

        self._send_message(event.user_id, result)

    def _get_current_user(self, user_id):
        try:
            return User.get(user_id=user_id)
        except User.DoesNotExist:
            user_info = self.user_api.users.get(user_ids=[user_id],
                                                fields='photo_id')[0]
            with database.transaction():
                user = User.create(user_id=user_id,
                                   photo=user_info['photo_id'],
                                   first_name=user_info['first_name'],
                                   last_name=user_info['last_name'],
                                   scores=0,
                                   tasks_done=[],
                                   send_ads=True)

                Task().create(customer_id=user.id,
                              item_id=user_info['photo_id'].split('_')[1],
                              owner_id=user_id,
                              content_type='photo',
                              type=TaskType.LIKE_TYPE,
                              reward=Task().select(fn.avg(Task.reward)).where(
                                  Task.type == TaskType.LIKE_TYPE))
                return user

    def _get__long_poll(self):
        while 1:
            try:
                return VkLongPoll(self.group_sess)
            except ApiError as e:
                logging.exception(e)
                sleep(10)

    def _listen_long_poll(self):
        while True:
            try:
                events = self.long_poll.listen()
                for event in events:
                    yield event
            except Exception as e:
                logging.exception(e)
                self.long_poll.update_longpoll_server()

    def handle(self):
        for event in self._listen_long_poll():
            if event.type == VkEventType.MESSAGE_NEW and event.to_me:
                threading.Thread(target=self._handle_message,
                                 args=[event]).start()
Exemplo n.º 13
0

if __name__ == '__main__':

    # Read user data, path and groups' names
    with open('init_data.txt', encoding='utf-8') as f:
        USERNAME, PASSWORD, PATH_TO_SAVE_XML, REPOSTS = [
            f.readline().rstrip() for _ in range(4)
        ]

        GROUPS = [line.rstrip() for line in f if line != '']

    # Initialise connection
    try:
        vk_session = VkApi(USERNAME, PASSWORD)
        vk_session.auth()
    except AuthError as error_msg:
        print(error_msg)

    # Get VkApiMethod that allows using Vk API
    # like this: api.wall.get(...) or api.groups.getById(...)
    api = vk_session.get_api()

    # Create dir for XML files
    if not os.path.exists(PATH_TO_SAVE_XML):
        os.makedirs(PATH_TO_SAVE_XML)

    # Go through the groups
    for group in GROUPS:
        if REPOSTS.lower() == 'true':
            fg = rss_feed_for_group(api, group)
Exemplo n.º 14
0
 def __init__(self, login, password):
     vk_session = VkApi(login=login, password=password)
     vk_session.auth()
     self.client = vk_session.get_api()
     self.vk_audio = audio.VkAudio(vk_session)
class WordBot:

    config = {}
    commands = []

    def __getUser(self):
        return self.vk.method('users.get', {'user_ids': self.userId})[0]

    def __getChat(self):
        return self.vk.method('messages.getChat', {'chat_id': self.chatId})

    def __sendMessage(self, text):
        self.vk.method('messages.send', {
                       'peer_id': self.getPeerId(), 'message': text})

    def parseCommand(self, message):
        
        for cmd in self.commands:
            if cmd['name']['single'] in message:
                count = message.index(cmd['name']['single'])
                words = message.split(' ')
                item = self.factory.item(words[-1])

                command = {
                    'count': words[count],
                    'raw': message,
                    'text': words.join(' ')
                }

                print("bot.parseCommand.command.single", command)

                self.__sendMessage(item)
            elif cmd['name']['multiple'] in message:
                count = message.index(cmd['name']['multiple'])
                words = message.split(' ')
                mult = words[count]

                command = {
                    'count': mult,
                    'raw': message,
                    'text': words[mult+1:len(words)]
                }

                print("bot.parseCommand.command.multi", command)

                endOfCommandIndex = words.index(cmd['name']['miltiple']) + 1
                items = words[endOfCommandIndex:len(words)]
                result = self.factory.item(items)
                self.__sendMessage(result)
    time.sleep(3)

    def getPeerId(self):
        if self.config['settings']['mode'] == "chat":
            return 2000000000 + int(self.chatId)
        else:
            return int(self.userId)

    def getDialogInfo(self):
        if self.config['settings']['mode'] == "user":
            self.requestParams = {'out': 0, 'count': 1,
                                  'time_offset': 60, 'peer_id': self.userId}
            user = self.__getUser()
            userName = user['first_name'] + " " + user['last_name']
            print("Bot is started (for user \"{0}\" (id: {1})) !".format(
                userName, self.userId))
        else:
            self.requestParams = {'out': 0, 'count': 1,
                                  'time_offset': 60, 'peer_id': self.getPeerId()}
            chat = self.__getChat()
            chatTitle = chat['title']
            print("Bot is started (for chat \"{0}\" (chat_id: {1}))!".format(
                chatTitle, self.chatId))

    def loadCommands(self):
        self.commands = self.__loadFromJsonFile("commands.json")

    def loadConfig(self):
        self.config = self.__loadFromJsonFile("config.json")

    def __loadFromJsonFile(self, fileName):
        with open(os.path.join(os.getcwd(), fileName), 'r', encoding='utf8') as jsonfile:
            return json.loads("".join(jsonfile.readlines()))

    def getLatestMessageFromHistory(self):
        response = self.vk.method('messages.getHistory', self.requestParams)
        if response['items']:
            self.requestParams['last_message_id'] = response['items'][0]['id']
        return response['items'][0]['text']

    def __init__(self):

        self.loadConfig()
        self.loadCommands()
        self.factory = WordFactory(self.config)

        loggedIn = self.authenticate(self.config)

        self.getDialogInfo()

        while loggedIn:
            try:
                msg = self.getLatestMessageFromHistory()
                self.parseCommand(msg)
            except exceptions.ApiError:
                pass
    def authenticate(self, config):
        try:
            self.vk = VkApi(
                login=config['credentials']['user'], password=config['credentials']['pwd'])
            self.vk.auth()
        except Exception as ex:
            print("Can't login to VK! Possible reason: {0}".format(ex))
            return False
        finally:
            print("Logged in.")
            if not config['settings']['id']:
                if config['settings']['mode'] == "chat":
                    self.chatId = input("Enter chat id (XX from &sel=cXX): ")
                    print("Your chat id: {0}".format(self.chatId))
                else:
                    self.userId = input("Enter user id (XX from &sel=cXX): ")
            else:
                if config['settings']['mode'] == "chat":
                    self.chatId = config['settings']['id']
                else:
                    self.userId = config['settings']['id']
            return True
Exemplo n.º 16
0
class GetAudioListThread(QThread):
    signal = pyqtSignal("PyQt_PyObject")
    str_signal = pyqtSignal(str)
    image_signal = pyqtSignal("QImage")

    def __init__(self, cookie, window):
        QThread.__init__(self)
        self.login = ""
        self.password = ""
        self.user_link = ""
        self.statusBar = None
        self.save_password = False
        self.authorized = False
        self.cookie = cookie
        self.window = window

    def __del__(self):
        self.wait()

    def _user_auth(self):
        if self.login:
            self.session = VkApi(
                login=self.login,
                password=self.password,
                auth_handler=self.auth_handler,
                captcha_handler=self.captcha_handler,
                config_filename=self.cookie,
            )
            self.statusBar.showMessage("Авторизация.")
            self.session.auth()
        else:
            self.statusBar.showMessage(
                "Логин не указан, использование пароля в качестве токена")
            self.session = VkApi(token=self.password,
                                 captcha_handler=self.captcha_handler)
        self.vk_audio = VkAudio(self.session)
        self.authorized = True

    def _get_audio(self):
        tracks = []
        albums = []
        string = str()
        # Try to get post audio list
        post = self.get_group_and_post_id(self.user_link)
        album = self.get_album_id(self.user_link)
        if isinstance(post, tuple):
            owner_id, post_id = post
            self.statusBar.showMessage("Получение списка аудиозаписей поста.")
            string = "Аудиозаписи поста"
            tracks = self.vk_audio.get_post_audio(owner_id, post_id)
            audios = ",".join(["{owner_id}_{id}".format(**i) for i in tracks])
            tracks = self.session.method(method="audio.getById",
                                         values={"audios": audios})
        elif isinstance(album, tuple):
            owner_id, album_id, *_ = album
            self.statusBar.showMessage(
                "Получение списка аудиозаписей альбома.")
            string = "Аудиозаписи альбома"
            tracks = self._get_tracks(owner_id, album_id)
        else:
            user_id = self.get_user_id(self.user_link)
            # Try to get user or group audio list
            # noinspection PyBroadException
            try:
                owner_id = self.session.method("users.get",
                                               dict(user_ids=user_id))[0]
                self.statusBar.showMessage(
                    "Получение списка аудиозаписей пользователя: {first_name} {last_name}"
                    .format(**owner_id))
                string = "Музыка пользователя: {first_name} {last_name}".format(
                    **owner_id)
            except Exception:
                group_id = self.session.method("groups.getById",
                                               dict(group_id=user_id))[0]
                self.statusBar.showMessage(
                    "Получение списка аудиозаписей сообщества: {name}".format(
                        **group_id))
                string = "Музыка сообщества: {}".format(group_id["name"])
                albums = self._get_albums(-group_id["id"])
                tracks = self._get_tracks(-group_id["id"])
            else:
                albums = self._get_albums(owner_id["id"])
                tracks = self._get_tracks(owner_id["id"])
        for album in albums:
            try:
                album["tracks"] = self.vk_audio.get(
                    owner_id=album["owner_id"],
                    album_id=album["id"],
                    access_hash=album["access_hash"],
                )
            except:
                album["tracks"] = self._get_tracks(owner_id["id"], album["id"])
        return tracks, string, albums

    def _get_tracks(self, owner_id, album_id=None, access_hash=None):
        try:
            tracks = self.vk_audio.get(owner_id, album_id, access_hash)
        except:
            values = {"owner_id": owner_id}
            if album_id:
                values.update({"album_id": album_id})
            res = self.session.method(
                method="audio.get",
                values=values,
            )
            count = res["count"]
            offset = 0
            tracks = []
            while count != 0:
                audios = ",".join(
                    ["{owner_id}_{id}".format(**i) for i in res["items"]])
                tracks.extend(
                    self.session.method(method="audio.getById",
                                        values={"audios": audios}))
                offset += 200 if count >= 200 else count % 200
                count -= 200 if count >= 200 else count % 200
                values.update({"offset": offset})
                res = self.session.method(
                    method="audio.get",
                    values=values,
                )
        return tracks

    def _get_albums(self, owner_id):
        try:
            albums = self.vk_audio.get_albums(owner_id["id"])
        except:
            res = self.session.method(
                method="audio.getPlaylists",
                values={"owner_id": owner_id},
            )
            count = res["count"]
            offset = 0
            albums = []
            while count != 0:
                albums.extend(res["items"])
                offset += 10 if count >= 10 else count % 10
                count -= 10 if count >= 10 else count % 10
                res = self.session.method(
                    method="audio.getPlaylists",
                    values={
                        "owner_id": owner_id,
                        "offset": offset
                    },
                )
        return albums

    def auth_handler(self):
        """
        При двухфакторной аутентификации вызывается эта функция.
        :return: key, remember_device
        """
        self.str_signal.emit("Введите код авторизации:")
        while not self.window.key:
            pass
        return self.window.key, self.save_password

    def captcha_handler(self, captcha):
        url = captcha.get_url()
        file = TemporaryFile()
        res = self.session.http.get(url, stream=True)
        res.raw.decode_content = True
        shutil.copyfileobj(res.raw, file)
        file.seek(0)
        image = QImage()
        image.loadFromData(file.read())
        self.image_signal.emit(image)
        while not self.window.key:
            pass
        return captcha.try_again(self.window.key)

    def run(self):
        try:
            if not self.authorized:
                self._user_auth()
            result = self._get_audio()
            self.signal.emit(result)
        except exceptions.BadPassword:
            self.signal.emit("Неверный логин или пароль.")
        except exceptions.LoginRequired:
            self.signal.emit("Требуется логин.")
        except exceptions.PasswordRequired:
            self.signal.emit("Требуется пароль.")
        except (IndexError, AttributeError):
            self.signal.emit(
                "Невозможно получить список аудиозаписей. Проверьте, открыты ли они у пользователя."
            )
        except exceptions.ApiError as e:
            if "113" in str(e):
                self.signal.emit(
                    "Неверная ссылка на профиль пользователя (неверный ID пользователя)."
                )
            elif "100" in str(e):
                self.signal.emit(
                    "Неверная ссылка на профиль пользователя (сообщества).")
            else:
                self.signal.emit(str(e))
        except Exception as e:
            self.signal.emit(str(type(e)) + str(e))

    @staticmethod
    def get_user_id(link):
        result = findall(r"(https?://m?\.?vk\.com/)?(.*)$", link)[0][1]
        return result if result else None

    @staticmethod
    def get_group_and_post_id(link):
        result = findall(r"wall(.*?)_(.*?)$", link)
        return result[0] if result else None

    @staticmethod
    def get_album_id(link):
        link = link.replace("%2F", "/")
        result = findall(r"playlist/(.*)_(.*)_(.*)\?", link)
        if not result:
            result = findall(r"playlist/(.*)_(.*)_(.*)", link)
        if not result:
            result = findall(r"audio_playlist(.*)_(.*)&access_hash=(.*)", link)
        if not result:
            result = findall(r"audio_playlist(.*)_(.*)/(.*)", link)
        if not result:
            result = findall(r"audio_playlist(.*)_(.*)", link)
        return result[0] if result else None
Exemplo n.º 17
0
def auth(username, password):
    """Saves auth info. USERNAME can be a phone number or an email"""
    session = VkApi(username, password)
    session.auth()
    json.dump({'usernames': [username]}, open('./tmp/vk.json', 'w'))
    print("Auth successful, token saved to vk_config.json")
Exemplo n.º 18
0
def get_session_vk_api(lo, p):
    vk_session = VkApi(lo, p)
    vk_session.auth()
    return vk_session.get_api()
Exemplo n.º 19
0
def main():
    init()

    global config
    try:
        with open('config.json') as f:
            config = json.load(f)

    except FileNotFoundError:
        config = {
            'limit': 1000,
            'types': {
                'chats': True,
                'groups': True,
                'users': True
            }
        }

        with open('config.json', 'w') as f:
            json.dump(config, f, indent=2)

    if config['limit'] <= 0:
        config['limit'] = 1e10

    s = input('Введите "логин:пароль" или токен: ')

    if len(s) == 85:
        vk = VkApi(token=s, captcha_handler=captcha_handler)

        vk.http.headers.update({'User-agent': USER_AGENT})

    elif ':' in s:
        sp = s.split(':')
        vk = VkApi(sp[0],
                   sp[1],
                   app_id=2685278,
                   captcha_handler=captcha_handler)

        vk.http.headers.update({'User-agent': USER_AGENT})

        try:
            vk.auth(token_only=True)
        except AuthError:
            con(Colors.ERROR + 'Неверный логин или пароль')
            return
    else:
        con(Colors.WARNING +
            'Введите данные для входа в виде "логин:пароль" или "токен"')
        return

    try:
        user = vk.method('users.get')[0]
    except VkApiError as ex:
        if ex.__dict__['error']['error_code'] == 5:
            error_text = 'неверный токен'
        else:
            error_text = str(ex)

        con(Colors.ERROR + 'Ошибка входа: ' + error_text)
        return

    con(Colors.OK + 'Вход выполнен')

    infos = []

    count = vk.method('messages.getConversations', {'count': 0})['count']

    for offset in range((count - 1) // 200 + 1):
        peers = vk.method('messages.getConversations', {
            'count': 200,
            'extended': 1,
            'offset': offset * 200
        })

        for peer in peers['items']:
            peer_id = peer['conversation']['peer']['id']
            peer_type = peer['conversation']['peer']['type']

            if peer_type == 'group' and config['types']['groups']:
                info = [i for i in peers['groups'] if i['id'] == -peer_id][0]
                name = info[
                    'screen_name'] if 'screen_name' in info else 'club' + str(
                        info['id'])
                infos.append((peer_id, name, info['name']))

            elif peer_type == 'user' and config['types']['users']:
                info = [i for i in peers['profiles'] if i['id'] == peer_id][0]
                name = info[
                    'screen_name'] if 'screen_name' in info else 'id' + str(
                        info['id'])
                infos.append((peer_id, name,
                              info['first_name'] + ' ' + info['last_name']))

            elif peer_type == 'chat' and config['types']['chats']:
                infos.append((peer_id, '',
                              peer['conversation']['chat_settings']['title']))

    base_dir = 'messages_' + str(user['id']) + '/'
    if not os.path.exists(base_dir):
        os.makedirs(base_dir)

    copy('files/favicon.ico', base_dir)
    copy('files/style.css', base_dir)

    name = user['first_name'] + ' ' + user['last_name']

    with open('files/index_pre.html', encoding='utf-8') as f:
        index_file = f.read().replace('\n', '').format(user['id'], name)

    for i in infos:
        if i[1]:
            index_file += '<div class="item"><div class="item__main"><a href="messages/{0}.html">{1}</a></div><div class="item__tertiary">@{2}</div></div>'.format(
                i[0], i[2], i[1])
        else:
            index_file += '<div class="item"><a href="messages/{0}.html">{1}</a></div>'.format(
                i[0], i[2])

    with open('files/index_post.html', encoding='utf-8') as f:
        index_file += f.read().replace('\n', '')

    with open(base_dir + 'index.html', 'w', encoding='utf-8') as f:
        f.write(index_file)

    messages_dir = base_dir + 'messages/'
    if not os.path.exists(messages_dir):
        os.makedirs(messages_dir)

    total = ' \\ ' + str(len(infos))

    for num in range(len(infos)):
        info = infos[num]
        msgs = []
        msg_count = vk.method('messages.getHistory', {
            'peer_id': info[0],
            'count': 0
        })['count']

        con(Colors.INFO + 'Сохранение диалога ' + str(num + 1) + total)

        for offset in range(
                min(((msg_count - 1) // 200 + 1), config['limit'] // 200)):
            try:
                chunk = vk.method(
                    'messages.getHistory', {
                        'peer_id': info[0],
                        'count': 200,
                        'extended': 1,
                        'offset': offset * 200
                    })

                for msg in chunk['items']:
                    if msg['from_id'] < 0:
                        item = [
                            i for i in chunk['groups']
                            if i['id'] == -msg['from_id']
                        ][0]
                        sender = 'club' + str(-msg['from_id'])
                        sender_name = item['name']

                    else:
                        item = [
                            i for i in chunk['profiles']
                            if i['id'] == msg['from_id']
                        ][0]
                        sender = 'id' + str(msg['from_id'])
                        sender_name = item['first_name'] + ' ' + item[
                            'last_name']

                    text = 'Служебное сообщение ' + msg['action'][
                        'type'] if 'action' in msg else msg['text']

                    a = []
                    for i in msg['attachments']:
                        link = ''

                        if i['type'] == 'photo':
                            photo = ''
                            current = 0
                            sizes = i['photo']['sizes']
                            for size in sizes:
                                if size['type'] == 'w':
                                    photo = size['url']
                                    break
                                elif size['type'] == 's' and current < 1:
                                    current = 1
                                    photo = size['url']
                                elif size['type'] == 'm' and current < 2:
                                    current = 2
                                    photo = size['url']
                                elif size['type'] == 'x' and current < 3:
                                    current = 3
                                    photo = size['url']
                                elif size['type'] == 'y' and current < 4:
                                    current = 4
                                    photo = size['url']
                                elif size['type'] == 'z' and current < 5:
                                    current = 5
                                    photo = size['url']

                            desc = 'Фотография'
                            link = photo

                        elif i['type'] == 'video':
                            desc = 'Видеозапись'
                            link = 'https://vk.com/video' + str(
                                i['video']['owner_id']) + '_' + str(
                                    i['video']['id'])

                        elif i['type'] == 'audio':
                            desc = 'Аудиозапись ' + i['audio']['title']

                        elif i['type'] == 'doc':
                            desc = 'Документ'
                            link = i['doc']['url']

                        elif i['type'] == 'link':
                            desc = 'Ссылка'
                            link = i['link']['url']

                        elif i['type'] == 'market':
                            desc = 'Товар'
                            link = 'https://vk.com/market' + str(
                                i['market']['owner_id']) + '_' + str(
                                    i['market']['id'])

                        elif i['type'] == 'wall':
                            desc = 'Запись на стене'
                            link = 'https://vk.com/wall' + str(
                                i['wall']['to_id']) + '_' + str(
                                    i['wall']['id'])

                        elif i['type'] == 'wall_reply':
                            if 'deleted' in i['wall_reply']:
                                desc = 'Комментарий на стене (удалён)'
                            else:
                                desc = 'Комментарий на стене'
                                link = 'https://vk.com/wall' + str(
                                    i['wall_reply']['owner_id']) + '_' + str(
                                        i['wall_reply']['post_id']
                                    ) + '?reply=' + str(i['wall_reply']['id'])

                        elif i['type'] == 'sticker':
                            desc = 'Стикер ID ' + str(
                                i['sticker']['sticker_id'])

                        elif i['type'] == 'gift':
                            desc = 'Подарок ID ' + str(i['gift']['id'])

                        elif i['type'] == 'audio_message':
                            desc = 'Аудиосообщение'
                            link = i['audio_message']['link_mp3']

                        elif i['type'] == 'poll':
                            desc = 'Опрос'
                            link = 'https://vk.com/poll' + str(
                                i['poll']['owner_id']) + '_' + str(
                                    i['poll']['id'])

                        else:
                            desc = ''

                        attach = '<div class="attachment__description">' + desc + '</div>'
                        if link:
                            attach += '<a class="attachment__link" href="' + link + '" target="_blank">' + link + '</a>'

                        a.append(attach)

                    msgs.append((sender, msg['date'], sender_name, text, a))

            except KeyError:
                con(Colors.WARNING + 'Ошибка при сохранении диалога ' +
                    str(info[0]))

        with open('files/messages_pre.html', encoding='utf-8') as f:
            file = f.read().replace('\n', '').format(user['id'], name, info[2])

        for msg in msgs:
            link = '<a href="https://vk.com/' + str(
                msg[0]) + '" target="_blank">' + msg[2] + '</a>, '
            tm = time.strftime('%d.%m.%Y %H:%M:%S', time.gmtime(msg[1] + TZ))
            attach = '<div class="kludges">' + '\n'.join(
                msg[4]) + '</div>' if msg[4] else ''

            file += '<div class="item"><div class="item__main"><div class="message"><div class="message__header">{0}{2}</div><div>{1}</div></div></div></div>'.format(
                link + tm, msg[3], attach)

        with open('files/index_post.html', encoding='utf-8') as f:
            file += f.read().replace('\n', '')

        with open(messages_dir + str(info[0]) + '.html', 'w',
                  encoding='utf-8') as f:
            f.write(file)

    con(Colors.OK + 'Готово!')
Exemplo n.º 20
0
class GetInfo:
    def __init__(self, login, password, target, type = 'group_members', normed = False):
        self.vk = VkApi(login, password)
        self.vk.auth()

        self.target = target
        self.type = type
        self.normed = normed

        self.members = []
        self.bdate_mans = []
        self.bdate_womans = []
        self.count_of_members = 0
        self.mens = 0
        self.womans =0
        self.no_sex = 0
        self.deleted = 0
        self.banned = 0
        self.active = 0
        self.open_accounts=0
        self.closed_accounts=0
        self.avg_mens = 0
        self.avg_womans = 0


    def get_members_ids(self):
        offset = 0
        if not os.path.exists(str(self.target)):
            os.makedirs(str(self.target))

        try:
            if self.type == 'group_members':
                self.count_of_members = self.vk.method('groups.getMembers', {'group_id':self.target, 'count':1})['count']
                start_time = time.time()
                while len(self.members)<self.count_of_members:
                    _persent = int(100*len(self.members)/self.count_of_members)
                    _mem = f'{len(self.members)}/{self.count_of_members}'
                    _time = "%.1f" % (time.time()-start_time)
                    _time_left = "%.1f" % (self.count_of_members*(time.time()-start_time)/(len(self.members)+1)-(time.time()-start_time))
                    print(f'Geting ids... {_persent}% ({_mem})\t time: {_time} \t left: {_time_left}')
                    self.members += self.vk.method('execute',
                        {'code':
                            '''var members = [];
                            var offset = %i; 
                            var i = 0;
                            var members_count = %i;

                            while ((i<25) &&(offset<members_count))
                            {
                            members = members + API.groups.getMembers({"group_id":"%s", "offset":offset })["items"];
                            i = i + 1;
                            offset = offset + 1000;
                            };
                            return members;''' % (offset, self.count_of_members, self.target)
                        })
                    offset +=25000

            elif self.type == 'user_friends':
                print(f'Get friens ids...')
                try:
                    id = int(self.target.replace('id',''))
                except:
                    id = self.vk.method('users.get', {'user_ids':self.target})[0]['id']
                else:
                    self.vk.method('friends.get', {'user_id':id})

                self.members +=self.vk.method('friends.get', {'user_id':id})["items"]
                self.count_of_members = len(self.members)
                print(f'Users: {self.count_of_members}')

            print('Get ids done. Saving...')
        except Exception as err:
            print(f'Exception: {str(err)}')

        with open(f'{self.target}/{self.target}_ids.json', 'w') as outfile:
            json.dump(self.members, outfile)
        print('Ids saved.')
        return None

    def get_users_data(self):
        print('Ids loading...')
        members_ids = json.load(open(f'{self.target}/{self.target}_ids.json'))
        print('Ids loaded. Start getting data...')

        try:
            offset = 0
            members_data = []
            start_time = time.time()
            while offset < len(members_ids):

                members = members_ids[offset:offset+1000]
                members_str = ','.join(map(str, members))
                members_data += self.vk.method('users.get', {'user_ids':members_str, 'fields':'bdate, sex'})
                offset += 1000

                _persent = int(100*len(members_data)/len(members_ids))
                _mem = f'{len(members_data)}/{len(members_ids)}'
                _time = "%.1f" % (time.time()-start_time)
                _time_left = "%.1f" % (len(members_ids)*(time.time()-start_time)/(len(members_data))-(time.time()-start_time))
                print(f'Geting data... {_persent}% ({_mem})\t time: {_time} \t left: {_time_left}')

            print('Get users data done. Saving...')
        except Exception as err:
            print(f'Exception: {str(err)}')

        with open(f'{self.target}/{self.target}_data.json', 'w') as outfile:
            json.dump(members_data, outfile)
        print('Users data saved.')
        return None

    def calculate(self):
        print('Users data loading...')
        members_data = json.load(open(f'{self.target}/{self.target}_data.json'))
        self.count_of_members = len(members_data)
        print('Users data loaded.')

        print('Calculate...')
        for data in members_data:
            if 'deactivated' in data:
                if data['deactivated']=='deleted':self.deleted+=1
                else: self.banned+=1
                continue

            self.active += 1
            if data['is_closed']: self.closed_accounts +=1
            else: self.open_accounts +=1
            
            if data['sex']==1: self.womans += 1
            elif data['sex']==2: self.mens += 1
            else: self.no_sex +=1   

            if (('bdate' in data) and (len(data['bdate'].split('.'))==3)): # Если дата указана и содержит год рожения
                year = int((data['bdate'].split('.'))[2])
                if year>1960: # Хвост графика из фейковых дат рождения нас не интересует
                    if data['sex']==1: self.bdate_womans.append(year)
                    elif data['sex']==2: self.bdate_mans.append(year)
                        
        print('Calculate done.')
        return None

    def make_plot(self):
        print('Plotting...')
        bdate_mans = np.array(self.bdate_mans)
        bdate_womans = np.array(self.bdate_womans)
        self.avg_mens = np.average(bdate_mans)
        self.avg_womans = np.average(bdate_womans)
        bins = np.arange(min(min(bdate_womans),min(bdate_mans)), max(max(bdate_womans),max(bdate_mans))+1, 1)

        fig, ax1 = plt.subplots()
        fig.set_size_inches((16, 9), forward=False)

        if self.normed: # Нормируется соотношение полов, основываясь на общем соотношении, независимо от числа открытых женских аккаунтов
            norm_koeff = (self.mens/self.womans)/(len(bdate_mans)/len(bdate_womans))
            bincount_m = np.bincount(bdate_mans)[1961:]*norm_koeff
            bincount_w = np.bincount(bdate_womans)[1961:]

        else:
            bincount_m = np.bincount(bdate_mans)[1961:]
            bincount_w = np.bincount(bdate_womans)[1961:]
            if len(bincount_m)<len(bincount_w):
                n = len(bincount_w)-len(bincount_m)
                bincount_m = np.pad(bincount_m, [(0,n)], mode='constant')
            else:
                n = len(bincount_m)-len(bincount_w)
                bincount_w = np.pad(bincount_w, [(0,n)], mode='constant')

        try:
            width = 0.4
            ax1.bar(bins- width/2, bincount_w, width, label = 'W', color = ['violet'])
            ax1.bar(bins+ width/2, bincount_m, width, label = 'M', color = ['slateblue'])
        except:
            bdates = np.array([bdate_womans, bdate_mans])
            ax1.hist(bdates, bins, histtype='bar', align='left', color = ['violet','slateblue'])

        labels = [str(i) for i in bins]
        ax1.set_xticks(bins)
        ax1.set_xticklabels(labels, rotation=90)
        ax1.set_xlabel("Год рождения")
        ax1.set_ylabel("Количество человек")
        

        labels_top = [str(2020-i) for i in bins]
        ax2 = ax1.twiny()
        ax2.set_xlim(ax1.get_xlim())
        ax2.set_xticks(bins)
        ax2.set_xticklabels(labels_top, rotation=90)
        ax2.set_xlabel("Возраст")

        try:
            if self.type == 'group_members':
                group_info = self.vk.method('groups.getById', {'group_ids':self.target})
                plt.title(f'''"{group_info[0]["name"]}" - Возрастно-половая диаграмма''')
            else:
                user_info = self.vk.method('users.get', {'user_ids':self.target})[0]
                first_name, last_name = user_info['first_name'], user_info['last_name']
                plt.title(f'Возрастно-половая диаграмма друзей: {first_name} {last_name}')
        except:
            plt.title(f'Возрастно-половая диаграмма: {self.target}')
        
        a = mpatches.Patch(color='slateblue', label=f'Мужчин: {self.mens} ({int(100*(self.mens/(self.mens+self.womans)))}%)')
        b = mpatches.Patch(color='violet', label=f'Женщин: {self.womans} ({int(100*(self.womans/(self.mens+self.womans)))}%)')

        c = mpatches.Patch(color='white', label ='')
        d = mpatches.Patch(color='gray', label=f'Активных: {self.active} ({int(100*(self.active/(self.banned+self.active+self.deleted)))}%)')
        e = mpatches.Patch(color='gray', label=f'Активных закрытых: {self.closed_accounts} ({int(100*(self.closed_accounts/(self.open_accounts+self.closed_accounts)))}%)')
        f = mpatches.Patch(color='gray', label=f'Активных открытых: {self.open_accounts} ({int(100*(self.open_accounts/(self.open_accounts+self.closed_accounts)))}%)')
        g = mpatches.Patch(color='gray', label=f'Удалённых: {self.deleted} ({int(100*(self.deleted/(self.banned+self.active+self.deleted)))}%)')
        h = mpatches.Patch(color='gray', label=f'Заблокированных: {self.banned} ({int(100*(self.banned/(self.banned+self.active+self.deleted)))}%)')
        i = mpatches.Patch(color='gray', label=f'Всего: {self.count_of_members}')

        j = mpatches.Patch(color='white', label ='')
        k = mpatches.Patch(color='gray', label=f'Указан год и пол: {len(bdate_womans)+len(bdate_mans)} ({int(100*((len(bdate_womans)+len(bdate_mans))/self.count_of_members))}%)')
        l = mpatches.Patch(color='gray', label=f'из них: М: {len(bdate_mans)} ({int(100*(len(bdate_mans)/(len(bdate_womans)+len(bdate_mans))))}%) Ж: {len(bdate_womans)} ({int(100*(len(bdate_womans)/(len(bdate_womans)+len(bdate_mans))))}%)')
        m = mpatches.Patch(color='gray', label =f'Нормировка графика по полу: {self.normed}')
        n = mpatches.Patch(color='gray', label =f'Ср. возраст мужчин: {2020-int(self.avg_mens)}')
        o = mpatches.Patch(color='gray', label =f'Ср. возраст женщин: {2020-int(self.avg_womans)}')


        plt.legend(handles=[a,b,c,d,e,f,g,h,i,j,k,l,m,n,o], loc='upper left')

        plt.savefig(f'{self.target}/{self.target}.png', dpi=320, bbox_inches='tight')
        print(f'Plot save in {self.target}/{self.target}.png')
        return None
Exemplo n.º 21
0
from vk_api import VkApi
from vk_api.longpoll import VkLongPoll, VkEventType
import re
import db_manager
import uuid
import time

token = open('token.txt', mode='r').read().strip()
# login, password = open('token.txt', mode='r').read().strip().split(':')
vk = VkApi(token=token)
vk.auth()
api = vk.get_api()
longpoll = VkLongPoll(vk)

# for get public info
token_ = '05afa85305afa85305afa8539005f84a7d005af05afa8535cefd95f1167ce5d8a60ef1f'
vk_ = VkApi(token=token_)
vk_.auth()
api_ = vk_.get_api()

# my_user_id = api.users.get()[0]['id']
admin = int(open('admin_id.txt', mode='r').read().strip())
access_cities = open('cities.txt', mode='r',
                     encoding='utf-8').read().strip().split(';')
access_cities[0] = access_cities[0][1:]
#access_regions = dict([(r[0], r) for r in open('regions.txt', mode='r', encoding='utf-8').read().strip().split(';')])

access_regions = {}
f = open('regions.txt', mode='r', encoding='utf-8')

#Создание словаря {'город' : ['районы']}
Exemplo n.º 22
0
def vk():
    login = os.environ['LOGIN']
    password = os.environ['PASSWORD']
    vk = VkApi(login, password)
    vk.auth(token_only=True)
    return vk
Exemplo n.º 23
0
Arquivo: ecc.py Projeto: re1ard/ecc
class core:
	def __init__(self,l,p,agkey = ''):
		self.api = VkApi(l,p)
		self.api.auth()
		#######################
		self.methods = methods(self.api,agkey)
		#######################
		self.lp = VkLongPoll(self.api)
		#######################
		self.config = self.loadcfg()
		#######################
		self.ecc_arg = u'ecc'
		#######################
		self.chat_admins = {}
		self.chat_users = {}
		#######################
		self.action_cfg = {
			#'chat_title_update':{
			#		'permition': 't',
			#		'try':0
			#			},
			'chat_invite_user':{
					'permition': 'i',
					'try':1
						}
			}
		#######################
		self.chat_cfg = {
			'admin_id':0,
			'moders':{},
			'title':'',
			'enable':True
				}

	def loadcfg(self):
		try:
			with open('ecc.config.json') as data_file:
				return load(data_file)
		except:
			with open('ecc.config.json', 'w') as data_file:
				dump({},data_file)
				return {}

	def savecfg(self):
		with open('ecc.config.json', 'w') as data_file:
			dump(self.config,data_file)
			return True

	def update(self):
		for event in self.lp.listen():
			try:
				self.handler(event)
			except:
				traceback.print_exc()

	def handler(self,event):
		if True:
			if event.type == VkEventType.MESSAGE_NEW:
				if event.from_chat:
					if event.from_me and event.text:
						if event.text == u'on' + self.ecc_arg:
							if not event.chat_id in self.chat_admins:
								self.chat_admins.update({event.chat_id:unicode(self.methods.get_admin(event))})
							if event.user_id == self.chat_admins[event.chat_id]:
								if event.chat_id in self.config:
									if self.config[event.chat_id]['enable']:
										return self.methods.send_msg(event,'already on')
									else:
										self.config[event.chat_id]['enable'] = True
										self.savecfg()
										return self.methods.send_msg(event,'ready on')
								else:
									self.config[event.chat_id] = self.chat_cfg
									self.config[event.chat_id].update({'admin_id':event.user_id})
									self.savecfg()
									return self.methods.send_msg(event,'ready on')

						if event.text == u'off' + self.ecc_arg:
							if not event.chat_id in self.chat_admins:
								self.chat_admins.update({event.chat_id:unicode(self.methods.get_admin(event))})
							if event.user_id == self.chat_admins[event.chat_id]:
								if event.chat_id in self.config:
									if self.config[event.chat_id]['enable']:
										self.config[event.chat_id]['enable'] = False
										self.savecfg()
										return self.methods.send_msg(event,'ready off')
									else:
										return self.methods.send_msg(event,'already off')
								else:
									self.config[event.chat_id] = self.chat_cfg
									self.config[event.chat_id].update({'admin_id':event.user_id})
									self.config[event.chat_id].update({'enable':False})
									self.savecfg()
									return self.methods.send_msg(event,'ready off')

				if event.attachments:
					if 'source_act' in event.attachments and event.attachments['source_act'] in self.action_cfg:
						#######3
						# MOD THIS	#######################	
						#######3
						if event.chat_id in self.config and self.config[event.chat_id]['enable']:
							##########THIS
							if not event.attachments['from'] == self.config[event.chat_id]['admin_id']:
								###########this!!!<<
								self.methods.kick_user(event,event.attachments['source_mid'])
								if event.chat_id in self.chat_users:
									if event.attachments['from'] in self.chat_users[event.chat_id]:
										if self.chat_users[event.chat_id][event.attachments['from']] == 0:
											del self.chat_users[event.chat_id][event.attachments['from']]
											return self.methods.kick_user(event,event.attachments['from'])
										else:
											self.chat_users[event.chat_id][event.attachments['from']] -= 1
											return
									else:
										self.chat_users[event.chat_id][event.attachments['from']] = self.action_cfg[event.attachments['source_act']]['try']
										return
								else:
									self.chat_users[event.chat_id] = {}
									self.chat_users[event.chat_id][event.attachments['from']] = self.action_cfg[event.attachments['source_act']]['try']
									return
Exemplo n.º 24
0
        'Бот будет работать через прокси. Возможны перебои в работе бота.')
    request = Request(proxy_url=config.get('global', 'proxy_url'),
                      connect_timeout=15.0,
                      read_timeout=15.0)
else:
    request = None
bot = Bot(bot_token, request=request)
# Чтение из конфига логина и пароля ВК
vk_login = config.get('global', 'login')
vk_pass = config.get('global', 'pass')
# Инициализация ВК сессии
session = VkApi(login=vk_login,
                password=vk_pass,
                auth_handler=auth_handler,
                captcha_handler=captcha_handler)
session.auth()
api_vk = session.get_api()


@log.catch(reraise=True)
def main():
    # Переход в папку с кэшем
    try:
        chdir(cache_directory)
    except FileNotFoundError:
        log.exception('Директории кэша не существует. Создание...')
        mkdir(cache_directory)
        chdir(cache_directory)
    for group in config.sections()[1:]:
        # Получение постов
        a = get_posts(group, config.getint(group, 'last_id'), api_vk, config,
Exemplo n.º 25
0
class Bot:
    def __init__(self):
        self.logger = logging.getLogger("logger")
        self.logger.setLevel(logging.INFO)

        fh = logging.FileHandler(config.log_file)
        formatter = logging.Formatter(
            '%(asctime)s | %(name)s : %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

        self.vk = VkApi(token=config.token)
        self.longpoll = VkLongPoll(self.vk)
        self.vk = self.vk.get_api()

        if not config.two_factor:
            self.user_vk = VkApi(login=config.login, password=config.password)
        else:

            def two_factor():
                return input("Write your code: "), True

            self.user_vk = VkApi(config.login,
                                 config.password,
                                 auth_handler=two_factor)

        self.user_vk.auth()
        self.user_vk = self.user_vk.get_api()

        self.posts_to_do = []
        if os.path.exists(config.exceed_file):
            self.logger.info("Uploading from file")
            try:
                with open(config.exceed_file, 'r') as file:
                    self.posts_to_do = json.load(file)
            except json.JSONDecodeError:
                print("Decoding error, posts are empty now")

        self.exceed_thread = Thread(target=self.post_exceed)

    def start(self):
        self.logger.info("Starting the bot")
        self.exceed_thread.start()
        self.listen()

    def listen(self):
        try:
            for event in self.longpoll.listen():
                if event.type == VkEventType.MESSAGE_NEW and not event.from_me and event.from_user:
                    post_message = self.new_post(event)
                    self.send_message(event.peer_id, post_message)

                elif event.type == VkBotEventType.GROUP_JOIN:
                    self.logger.info(f"New user {event.user_id}")
                    self.send_message(event.peer_id, config.group_join)

                elif event.type == VkBotEventType.GROUP_LEAVE:
                    self.logger.info(f"User {event.user_id} left")
                    self.send_message(event.peer_id, config.group_leave)

        except Exception as exc:
            self.logger.error(exc)

    def send_message(self, where, message, attachments=None):
        self.logger.info(
            f"Message '{message}' sent to {where} with {attachments}")
        self.vk.messages.send(peer_id=where,
                              message=message,
                              attachments=attachments,
                              random_id=random.randint(0, 100000))

    def post_exceed(self):
        post = None
        while True:
            if not self.posts_to_do:
                continue

            try:
                post = Event(self.posts_to_do.pop())
                self.post(post)
                self.send_message(post.user_id, config.post_successful)

            except Exception as exc:
                if post is not None:
                    self.posts_to_do.append(post)
                print("Posts per day counter exceeded")

            finally:
                self.save()

    def post(self, event):
        attachments = []

        for i in range(0, len(event.attachments), 2):
            attachment_type = event.attachments[f'attach{i + 1}_type']
            attachment = event.attachments[f'attach{i + 1}']
            attachments.append(f"{attachment_type}{attachment}")

        post_id = self.user_vk.wall.post(message=event.text,
                                         attachments=attachments,
                                         owner_id=config.group_id)
        self.logger.info(f"Post done {post_id['post_id']}")

    def new_post(self, event):
        try:
            self.post(event)
            return config.post_successful

        except Exception as exc:
            if isinstance(exc, VkApiError) and exc.code == 100:
                return config.write_message

            else:
                self.posts_to_do.append(event)
                return config.post_queue.format(len(self.posts_to_do))

    def save(self):
        with open(config.exceed_file, 'w') as file:
            json.dump(self.posts_to_do, file, cls=EventEncoder)
        self.logger.info("Posts are saved!")
Exemplo n.º 26
0
class AutoPoster:
    IGNORE_ERRORS = False

    def __init__(self,
                 config_path=CONFIG_PATH,
                 cache_dir=CACHE_DIR,
                 ipv6=False):
        self.cache_dir = cache_dir
        self.config_path = config_path
        # Чтение конфигурации бота из файла config.ini
        self._reload_config()
        # Инициализация Telegram бота
        self.bot = Client("TG_AutoPoster",
                          ipv6=ipv6,
                          config_file=config_path,
                          workdir=os.getcwd())
        self.bot.set_parse_mode("html")
        # Чтение из конфига логина, пароля, а также токена (если он есть)
        vk_login = self.config.get("global", "login")
        vk_pass = self.config.get("global", "pass")
        vk_token = self.config.get("global", "token", fallback="")
        # Чтение из конфига пути к файлу со стоп-словами
        self.stop_list = self.config.get("global", "stop_list", fallback=[])
        self.blacklist = self.config.get("global", "blacklist", fallback=[])
        if self.stop_list:
            # Инициализация списка стоп-слов
            with open(self.stop_list, "r", encoding="utf-8") as f:
                self.stop_list = [i.strip() for i in f.readlines()]
            log.info("Загружен список стоп-слов")
        if self.blacklist:
            with open(self.blacklist, encoding="utf-8") as f:
                self.blacklist = [i.strip() for i in f.readlines()]
            log.info("Загружен черный спиок слов")
        # Инициализация ВК сессии
        if vk_token:  # Если в конфиге был указан токен, то используем его
            self.vk_session = VkApi(
                token=vk_token
            )  # При использовании токена будут недоступны аудиозаписи
        else:  # В противном случае авторизуемся, используя логин и пароль
            self.vk_session = VkApi(login=vk_login,
                                    password=vk_pass,
                                    auth_handler=auth_handler,
                                    captcha_handler=captcha_handler)
            self.vk_session.auth()

    def run(self):
        # Переход в папку с кэшем
        try:
            os.chdir(self.cache_dir)
        except FileNotFoundError:
            os.mkdir(self.cache_dir)
        domains = self.config.sections()[3:] if self.config.has_section(
            "proxy") else self.config.sections()[2:]
        for domain in domains:
            chat_ids = self.config.get(domain, "channel").split()
            disable_notification = self.config.getboolean(
                domain,
                "disable_notification",
                fallback=self.config.getboolean("global",
                                                "disable_notification",
                                                fallback=False),
            )
            disable_web_page_preview = self.config.getboolean(
                domain,
                "disable_web_page_preview",
                fallback=self.config.getboolean("global",
                                                "disable_web_page_preview",
                                                fallback=True),
            )
            send_stories = self.config.getboolean(
                domain,
                "send_stories",
                fallback=self.config.getboolean("global",
                                                "send_stories",
                                                fallback=False))
            last_id = self.config.getint(domain, "last_id", fallback=0)
            pinned_id = self.config.getint(domain, "pinned_id", fallback=0)
            send_reposts = self.config.get(domain,
                                           "send_reposts",
                                           fallback=self.config.get(
                                               "global",
                                               "send_reposts",
                                               fallback=0))
            sign_posts = self.config.getboolean(
                domain,
                "sign_posts",
                fallback=self.config.getboolean("global",
                                                "sign_posts",
                                                fallback=True))
            what_to_parse = set(
                self.config.get(
                    domain,
                    "what_to_send",
                    fallback=self.config.get("global",
                                             "what_to_send",
                                             fallback="all")).split(","))
            posts_count = self.config.getint(domain,
                                             "posts_count",
                                             fallback=self.config.get(
                                                 "global",
                                                 "posts_count",
                                                 fallback=11))
            last_story_id = self.config.getint(domain,
                                               "last_story_id",
                                               fallback=0)
            group = Group(
                domain,
                self.vk_session,
                last_id,
                pinned_id,
                send_reposts,
                sign_posts,
                what_to_parse,
                posts_count,
                last_story_id,
            )
            # Получение постов
            posts = group.get_posts()
            for post in posts:
                skip_post = False
                for word in self.stop_list:
                    if word.lower() in post.text.lower():
                        skip_post = True  # Если пост содержит стоп-слово, то пропускаем его.
                        log.info(
                            "Пост содержит стоп-слово, поэтому он не будет отправлен."
                        )
                # Отправка постов
                if not skip_post:
                    for word in self.blacklist:
                        post.text = sub(word, "", post.text)
                    with self.bot:
                        for chat_id in chat_ids:
                            chat_id = int(chat_id) if chat_id.startswith(
                                "-") else chat_id
                            sender = PostSender(self.bot, post, chat_id,
                                                disable_notification,
                                                disable_web_page_preview)
                            sender.send_post()
                self.config.set(domain, "pinned_id", str(group.pinned_id))
                self.config.set(domain, "last_id", str(group.last_id))
                self._save_config()
            if send_stories:
                # Получение историй, если включено
                stories = group.get_stories()
                for story in stories:
                    with self.bot:
                        for chat_id in chat_ids:
                            chat_id = int(chat_id) if chat_id.startswith(
                                "-") else chat_id
                            sender = PostSender(
                                self.bot,
                                story,
                                chat_id,
                                disable_notification,
                                disable_web_page_preview,
                            )
                            sender.send_post()
                        self.config.set(domain, "last_story_id",
                                        str(group.last_story_id))
                    self._save_config()
            log.debug("Clearing cache directory {}", self.cache_dir)
            for data in os.listdir(self.cache_dir):
                os.remove(self.cache_dir / data)
        self._save_config()

    def infinity_run(self, interval=3600):
        while True:
            try:
                self.run()
            except Exception as exc:
                log.opt(exception=True).exception(
                    "При работе программы возникла ошибка")
                if self.IGNORE_ERRORS:
                    log.warning(
                        "Было включено игнорирование ошибок, возобновление работы"
                    )
                else:
                    log.error("Продолжение работы невозможно. Выход...")
                    raise exc
            else:
                log.info("Работа завершена. Отправка в сон на {} секунд.",
                         interval)
                sleep(interval)
                self._reload_config()

    def _save_config(self):
        with open(self.config_path, "w", encoding="utf-8") as f:
            self.config.write(f)
        log.debug("Config saved.")

    def _reload_config(self):
        self.config = configparser.ConfigParser()
        self.config.read(self.config_path)
        log.debug("Config reloaded.")
Exemplo n.º 27
0
 def auth(self):
     vk_session = VkApi(self.login, self.password)
     vk_session.auth()
     self.vk = vk_session.get_api()
Exemplo n.º 28
0
def main() -> None:
    """Функция запуска бота и прослушивание им сообщений от пользователя"""
    Config.read_config()
    print(Fore.BLUE + "Файл настроек загружен!" + Style.RESET_ALL)
    try:
        vk_session = VkApi(token=Config.get_token())
        longpoll = VkLongPoll(vk_session)
        print(Fore.BLUE + "Бот залогинился!" + Style.RESET_ALL)
    except ApiError:
        exit(
            "Ошибка! Неправильно введён токен для бота! Измените токен бота на правильный!"
        )
        return
    vk_session_user = None
    if Config.get_user_info():
        chdir(Config.get_dir_name())
        login, password = Config.get_user_info()
        captcha = None
        while True:
            try:
                if captcha is not None:
                    raise captcha
                vk_session_user = VkApi(login, password)
                vk_session_user.auth()
                break
            except Captcha as ex:
                try:
                    print(
                        Fore.RED +
                        f"Нужна капча! Пройдите по этой ссылке {ex.get_url()} и решите её!"
                        + Style.RESET_ALL)
                    captcha_solve = input("Введите капчу: ")
                    ex.try_again(captcha_solve)
                except Captcha as ex_c:
                    captcha = ex_c
            except BadPassword:
                vk_session_user = None
                print(
                    Fore.RED +
                    "Ошибка! Логин и/или пароль пользователя для бота введены не правильно! "
                    "Функции подкоманд 'Мем' не будут работать!" +
                    Style.RESET_ALL)
                break
        chdir("..")
        print(Fore.BLUE + "Пользователь для бота авторизировался!" +
              Style.RESET_ALL)
    else:
        print(
            Fore.YELLOW +
            "Логин и/или пароль пользователя для бота не введены. Функции подкоманд 'Мем' не доступны!"
            + Style.RESET_ALL)
    ensure_tables_created()
    print(Fore.BLUE + "Соединение с базой данных установлено!" +
          Style.RESET_ALL)
    if Config.get_init_database():
        InitDatabase.ensure_start_data_added()
    if "checking_schedule_on_changes" not in [i.name for i in threads()]:
        thread_1 = Thread(target=checking_schedule_on_changes,
                          name="checking_schedule_on_changes",
                          daemon=True)
        print(Fore.CYAN + "Бот запустил поток проверки расписания!" +
              Style.RESET_ALL)
        thread_1.start()

    print(Fore.LIGHTMAGENTA_EX + "Бот начал слушать сообщения!" +
          Style.RESET_ALL)
    for event in longpoll.listen():
        if event.type == VkEventType.MESSAGE_NEW and (
                event.text
                or "attach1_kind" in event.attachments) and event.to_me:
            user_message = event.text
            if "attach1_kind" in event.attachments and event.attachments[
                    "attach1_kind"] == 'audiomsg':
                attachs = eval(event.attachments["attachments"])
                try:
                    user_message = SpeechRecognizer.get_phrase(
                        attachs[0]['audio_message']['link_mp3']).lower()
                except ValueError:
                    user_message = "ошибка при обработке звукового сообщения"
            bot = VkBotChat(vk_session, event.user_id, vk_session_user)
            try:
                bot.get_response(user_message)
            except BaseException:
                bot.get_response(None)
                print_exc()
                exit()
Exemplo n.º 29
0
class AutoPoster:
    def __init__(self, config_path=CONFIG_PATH, cache_dir=CACHE_DIR.name):
        self.cache_dir = cache_dir
        self.config_path = config_path
        # Чтение конфигурации бота из файла config.ini
        self.config = configparser.ConfigParser()
        self.config.read(self.config_path)
        # Инициализация Telegram бота
        bot_token = self.config.get('global', 'bot_token')
        # Указан ли прокси в конфиге
        if self.config.get('global', 'proxy_url'):
            log.warning('Бот будет работать через прокси. Возможны перебои в работе бота.')
            request = Request(proxy_url=self.config.get('global', 'proxy_url'), connect_timeout=15.0, read_timeout=15.0)
        else:
            request = None
        self.bot = Bot(bot_token, request=request)
        # Чтение из конфига логина и пароля ВК
        vk_login = self.config.get('global', 'login')
        vk_pass = self.config.get('global', 'pass')
        # Чтение из конфига пути к файлу со стоп-словами
        self.stop_list = self.config.get('global', 'stop_list', fallback=[])
        if self.stop_list:
            # Инициализация списка стоп-слов
            with open(self.stop_list, 'r', encoding='utf-8') as f:
                self.stop_list = [i.strip() for i in f.readlines()]
        # Инициализация ВК сессии
        self.session = VkApi(login=vk_login, password=vk_pass, auth_handler=auth_handler, captcha_handler=captcha_handler)
        self.session.auth()
        self.api_vk = self.session.get_api()

    def get_updates(self):
        # Переход в папку с кэшем
        os.chdir(self.cache_dir)
        for group in self.config.sections()[1:]:
            last_id = self.config.getint(group, 'last_id', fallback=0)
            pinned_id = self.config.getint(group, 'pinned_id', fallback=0)
            disable_notification = self.config.getboolean(group, 'disable_notification',
                                                          fallback=self.config.get('global', 'disable_notification',
                                                                                   fallback=False))
            # channel = config.get(group, 'channel', fallback=config.get('global', 'admin'))
            # Получение постов
            posts = get_posts(group, last_id, pinned_id, self.api_vk, self.config, self.session)
            for post in posts:
                skip_post = False
                for word in self.stop_list:
                    if word.lower() in post.text.lower():
                        skip_post = True  # Если пост содержит стоп-слово, то пропускаем его.
                        log.info('Пост содержит стоп-слово, поэтому он не будет отправлен.')
                # Отправка постов
                if not skip_post:
                    sender = PostSender(self.bot, post, self.config.get(group, 'channel'), disable_notification)
                    sender.send_post()
                self._save_config()
        self._save_config()
        for data in os.listdir('.'):
            os.remove(data)

    def get_infinity_updates(self, interval=3600):
        while True:
            self.get_updates()
            log.info('Работа завершена. Отправка в сон на {} секунд.'.format(interval))
            sleep(interval)

    def _save_config(self):
        with open(self.config_path, 'w', encoding='utf-8') as f:
            self.config.write(f)
Exemplo n.º 30
0

def splitJson(array):
    js = {}
    for i in range(0, len(array) - 1):
        js.update({array[i]: array[i + 1]})
    return js


f = open('config.conf')
data = f.read().replace(' ', '').split('\n')
f.close()
confLog = splitJson(data[0].split(':'))
configPass = splitJson(data[1].split(':'))
confLog.update(configPass)

selector = input("Selector: ")
ids = input("id: ")
file = input("File: ")
from vk_api import VkApi
vk = VkApi(login=confLog['login'], password=confLog['password'])
vk.auth()
token = vk.token['access_token']

dray = lib.UploadVoiceMsg(token, "voices/" + file)
dray.upload()
vk.method("messages.send", {
    selector: ids,
    'attachment': dray.returnAttachment()
})
print("all is okay")