示例#1
0
 def test_profile_exists_expired_token(self):
     self.set_user_profile(test_personal_expired_token)
     workgroup = "-" + str(links.group_with_three_postsID)
     with self.assertRaises(KeyError):
         two_upper_posts = \
         helpers.make_request_vk('wall.get', personal=True, count=2, chat_owner=OwnerAndBotChatData.owner_id,
                                 owner_id=workgroup)['response']['items']
示例#2
0
 def test_profile_exists_valid_token(self):
     self.set_user_profile(test_personal_token)
     workgroup = "-" + str(links.group_with_three_postsID)
     two_upper_posts = \
         helpers.make_request_vk('wall.get', personal=True, count=2, chat_owner=OwnerAndBotChatData.owner_id,
                                 owner_id=workgroup)['response']['items']
     self.assertEqual(len(two_upper_posts), 2)
 def choose_post(self, post_quantity):
     max_offset = post_quantity - 1
     code_logger.info(f'In RandomPostAction.choose_post. Max offset: {max_offset}')
     random_offset = random.randint(0, max_offset)
     code_logger.info(f'In RandomPostAction.choose_post. Random offset: {random_offset}')
     one_post = helpers.make_request_vk('wall.get', personal=True, chat_owner=self.chat_owner, count=1,
                                        offset=random_offset, owner_id=self.workgroup)['response']['items'][0]
     return one_post
示例#4
0
 def test_chat_owner_doesnt_have_profile(self):
     workgroup = "-" + str(links.normal_group1ID)
     with self.assertRaises(PersonalTokenException) as context:
         two_upper_posts = \
         helpers.make_request_vk('wall.get', personal=True, count=2, chat_owner=OwnerAndBotChatData.owner_id,
                                 owner_id=workgroup)['response']['items']
     self.assertEqual(str(context.exception),
                      f"UserProfile matching query does not exist. Chat owner: {OwnerAndBotChatData.owner_id}.")
示例#5
0
def public_or_event(group_name):
    group_type = re.search(r'^(event|public)', group_name)[0]
    if group_type == "public":
        group_type = "page"
    group_id = re.search(r'\d{1,}$', group_name)[0]
    response_content = helpers.make_request_vk('groups.getById',
                                               group_id=group_id)
    code_logger.info(response_content)
    group = GroupReference(response_content)
    if group_type == group.type and group.is_closed == 0 and group.deactivated is None:
        return True, (group.screen_name, group.group_id)
    else:
        return False, group
    def get_post_quantity(self):
        """ will get Key Error when:
        - too many requests per second (more than 3);
            {'error': {'error_code': 6, 'error_msg': 'Too many requests per second',...
        - group is blocked;
            {'error': {'error_code': 15, 'error_msg': 'Access denied: group is blocked',...
        - wall is available only for community members
            {'error': {'error_code': 15, 'error_msg': 'Access denied: this wall available only for community members'...
        - user authorization failed: invalid access_token
            {'error': {'error_code': 5, 'error_msg': 'User authorization failed: invalid access_token (4).',...
        """

        try:
            post_quantity = helpers.make_request_vk('wall.get', personal=True, chat_owner=self.chat_owner, count=1,
                                                    owner_id=self.workgroup)
        except PersonalTokenException as e:
            # this shouldn't happen, random_post option should be true only after profile check
            code_logger.info("In RandomPostAction.get_post_quantity. PersonalTokenException: " + str(e))

            raise UserProfileError(self.input_message,
                                   error_description=f"An error message is sent to chat owner.",
                                   bot_response={"message": common_dict["not_login"].substitute(command=random_post),
                                                 "peer_id": self.chat_owner})

        try:
            return post_quantity['response']['count']

        except KeyError as e:
            code_logger.info(post_quantity)
            if post_quantity['error']['error_code'] == 6:
                raise LimitError(self.input_message,
                                 error_description=f"RandomPostAction. get_post_quantity. {post_quantity['error']}")

            if post_quantity['error']['error_code'] == 15:
                raise GroupValidationError(self.input_message, bot_response=common_dict["group_turned_bad"].substitute(
                    group_link=self.setting_db_object.random_post_group_link))

            if post_quantity['error']['error_code'] == 5:

                raise UserProfileError(self.input_message, error_description="An error message is sent to chat owner.",
                                       bot_response={
                                           "message": common_dict["refresh_token"].substitute(command=random_post),
                                           "peer_id": self.chat_owner})

            else:  # maybe another error exists
                raise VKBotException(self.input_message,
                                     error_description=f"RandomPostAction. get_post_quantity. unknown KeyError: {e}")
    def check_for_admin(self):
        """ For now this method is only used in user conversations anyway,
            but I added
            self.conversation_type == 'user'
            check for future possible use in chat conversations.

        """
        response_content = helpers.make_request_vk(
            'messages.getConversationsById',
            peer_ids=self.chat_db_object.chat_id)  # !!!
        response_dict = helpers.parse_vk_object(response_content)
        admin_indicator = response_dict.get('response__count', None)
        if admin_indicator and admin_indicator > 0:
            return
        else:
            code_logger.debug(
                f"Bot isn't admin in chat {self.chat_db_object.chat_id}")
            bot_response = f"Бот не является админом в чате {self.chat_db_object.chat_id} и не может выполнять команды."
            if self.conversation_type == 'user':
                raise NotAdminError(self.message, bot_response=bot_response)
示例#8
0
def group_validator(value):
    """
    Works both for forms and code.
    If value in form is empty, it doesn't end up in validator.

    App and desktop link example:  https://vk.com/rgubru
    Mobile version link example:  https://m.vk.com/study_english_every_day?from=groups
    Valid are all kinds of working links, group screen name and group id.

    NB: vk group screen names like "public12345" or "event6789" are not actual vk screen names,
    so links like https://vk.com/public200069033 need some additional work (done below).
    Actual vk screen names are club12345 (with type = page) and club6789 (with type = event) respectively.

    NB: when using group token (not personal token), groups.getById request doesn't return an error
    in case of non-existent group name etc. Instead, when something goes wrong,
    it returns information of a group which token is used (so in this case - this bot's info).
    """

    code_logger.debug(f'In  validate_group: {value}')
    error_text = 'Группа %(value)s не может быть зарегистрирована для случайных постов.' \
                 ' Убедитесь, что ссылка правильная, и группа не является закрытой'
    if len(value.split()) > 1:
        code_logger.debug(
            "In  validate_group. Supposed group link has spaces.")

        raise ValidationError(
            _(error_text),
            params={'value': value},
        )
    group_name = value.split('vk.com/')[-1]
    group_name = group_name.split('?')[
        0]  # in case of link from mobile version

    pattern = r'^(event|public)\d{1,}$'  # in case of links like https://vk.com/public200069033 or https://vk.com/event200069033
    if re.fullmatch(pattern, group_name):
        proceed, info = public_or_event(group_name)
        if proceed:
            screen_name, group_id = info[0], info[1]
            return screen_name, group_id
        else:
            group = info
    else:
        response_content = helpers.make_request_vk('groups.getById',
                                                   group_id=group_name)
        code_logger.info(response_content)
        group = GroupReference(response_content)
        if group.is_closed == 0 and group.deactivated is None:
            if group.group_id != bot_groupid:  # normal case
                return group.screen_name, group.group_id
            else:
                if group.screen_name == group_name or str(
                        group.group_id
                ) == group_name:  # if user really wanted bot group, else - an error has occured
                    return group.screen_name, group.group_id

    code_logger.debug(
        f'In group_validator. group.screen_name: {group.screen_name},  group_name (from user): {group_name}, '
        f' group.is_closed: {group.is_closed},  group.deactivated: {group.deactivated}'
    )
    raise ValidationError(
        _(error_text),
        params={'value': value},
    )
 def get_name(self):
     first_name = helpers.make_request_vk('users.get', user_ids=self.from_id)['response'][0]['first_name']
     return first_name
示例#10
0
 def test_chat_owner_not_provided(self):
     workgroup = "-" + str(links.normal_group1ID)
     with self.assertRaises(PersonalTokenException) as context:
         two_upper_posts = helpers.make_request_vk('wall.get', personal=True, count=2,
                                                   owner_id=workgroup)['response']['items']
     self.assertEqual(str(context.exception), "Chat owner was not provided when 'personal' argument was True.")