Exemple #1
0
    def start(self):
        if self.vk_event.msg.lower() in ['идиот?', 'ты идиот?']:
            return "Мне потанцевать нельзя?"
        elif self.vk_event.msg.lower() in ['да?']:
            return {'attachments': 'video162408856_456239566'}

        bad_words = get_bad_words()

        if not check_user_group(self.vk_event.sender, Role.ADMIN):
            min_index_bad = len(self.vk_event.msg)
            max_index_bad = -1
            for word in bad_words:
                ind = self.vk_event.msg.lower().find(word)
                if ind != -1:
                    if ind < min_index_bad:
                        min_index_bad = ind
                    if ind > max_index_bad:
                        max_index_bad = ind

            min_index_bad = self.vk_event.msg.rfind(' ', 0, min_index_bad)
            if min_index_bad == -1:
                min_index_bad = self.vk_event.msg.rfind(',', 0, min_index_bad)
                if min_index_bad == -1:
                    min_index_bad = self.vk_event.msg.rfind(
                        '.', 0, min_index_bad)
                    if min_index_bad == -1:
                        min_index_bad = self.vk_event.msg.find('/')
            min_index_bad += 1
            if max_index_bad != -1:
                len_bad = self.vk_event.msg.find(',', max_index_bad)
                if len_bad == -1:
                    len_bad = self.vk_event.msg.find(' ', max_index_bad)
                    if len_bad == -1:
                        len_bad = self.vk_event.msg.find('?', max_index_bad)
                        if len_bad == -1:
                            len_bad = len(self.vk_event.msg)

                rand_int = get_random_int(len(BAD_ANSWERS) - 1)
                messages = [BAD_ANSWERS[rand_int]]
                name = self.vk_event.sender.name
                if self.vk_event.sender.gender == '1':
                    msg_self = "сама"
                else:
                    msg_self = "сам"
                messages.append(
                    f"{name}, может ты {msg_self} {self.vk_event.msg[min_index_bad: len_bad]}?"
                )
                return messages

        random_events = [["Да", "Ага", "Канеш", "Само собой", "Абсолютно"],
                         ["Нет", "Неа", "Ни за что", "Невозможно", "NO"],
                         [
                             "Ну тут даже я хз", "ДА НЕ ЗНАЮ Я", "Хз",
                             "Спроси у другого бота", "Да нет наверное"
                         ]]
        probability_events1 = [47, 47, 6]
        probability_events2 = [40, 15, 15, 15, 15]
        selected_event = random_event(random_events, probability_events1)
        selected_event2 = random_event(selected_event, probability_events2)
        return selected_event2
Exemple #2
0
    def start(self):

        from apps.API_VK.command.initial import HELP_TEXT, API_HELP_TEXT

        if self.vk_event.from_api:
            help_texts = API_HELP_TEXT
        else:
            help_texts = HELP_TEXT

        ordered_roles = [
            {
                "role": Role.USER,
                "text": "общие команды"
            },
            {
                "role": Role.ADMIN,
                "text": "команды для администраторов"
            },
            {
                "role": Role.MODERATOR,
                "text": "команды для модераторов"
            },
            {
                "role": Role.MINECRAFT,
                "text": "команды для игроков майнкрафта"
            },
            {
                "role": Role.TRUSTED,
                "text": "команды для доверенных пользователей"
            },
            {
                "role": Role.STUDENT,
                "text": "команды для группы 6221"
            },
            {
                "role": Role.MINECRAFT_NOTIFY,
                "text": "команды для уведомлённых майнкрафтеров"
            },
            {
                "role": Role.TERRARIA,
                "text": "команды для игроков террарии"
            },
        ]
        output = ""
        for role in ordered_roles:
            if check_user_group(
                    self.vk_event.sender,
                    role['role']) and help_texts[role['role'].name]:
                output += f"\n\n— {role['text']} —\n"
                output += help_texts[role['role'].name]
        if help_texts['games']:
            output += "\n\n— игры —\n"
            output += help_texts['games']
        output = output.rstrip()
        return output
Exemple #3
0
    def start(self):
        user = self.vk_bot.get_user_by_name(self.vk_event.args,
                                            self.vk_event.chat)

        if check_user_group(user, Role.ADMIN):
            return "Нельзя банить админа"
        group_banned = Group.objects.get(name=Role.BANNED.name)
        user.groups.add(group_banned)
        user.save()

        return "Забанен"
Exemple #4
0
    def start(self):
        action = self.vk_event.args[0].lower()
        if action in ['добавить', 'подписаться', 'подписка']:
            self.check_args(2)
            channel_id = self.vk_event.args[1]
            try:
                url = f'https://youtube.com/user/{channel_id}'
                response = requests.get(url)
                bsop = BeautifulSoup(response.content, 'html.parser')
                channel_id = bsop.find_all('link', {'rel': 'canonical'})[0].attrs['href'].split('/')[-1]
            except Exception:
                pass

            if self.vk_event.chat:
                existed_sub = YoutubeSubscribe.objects.filter(chat=self.vk_event.chat,
                                                              channel_id=channel_id)
            else:
                existed_sub = YoutubeSubscribe.objects.filter(chat__isnull=True,
                                                              channel_id=channel_id)
            if existed_sub.exists():
                return f"Ты уже и так подписан на канал {existed_sub.first().title}"

            user_subs_count = YoutubeSubscribe.objects.filter(author=self.vk_event.sender).count()

            # Ограничение 3 подписки для нетрастед
            if not check_user_group(self.vk_event.sender, Role.TRUSTED) and user_subs_count >= MAX_USER_SUBS_COUNT:
                return f"Максимальное число подписок - {MAX_USER_SUBS_COUNT}"
            youtube_info = YoutubeInfo(channel_id)
            youtube_data = youtube_info.get_youtube_channel_info()
            yt_sub = YoutubeSubscribe(
                author=self.vk_event.sender,
                chat=self.vk_event.chat,
                channel_id=channel_id,
                title=youtube_data['title'],
                date=youtube_data['last_video']['date']
            )
            yt_sub.save()
            return f'Подписал на канал {youtube_data["title"]}'
        elif action in ['удалить', 'отписаться', 'отписка']:
            self.check_args(2)
            channel_filter = self.vk_event.args[1:]
            yt_sub = self.get_sub(channel_filter, True)
            yt_sub_title = yt_sub.title
            yt_sub.delete()
            return f"Удалил подписку на канал {yt_sub_title}"
        elif action in ['подписки']:
            return self.get_subs()
        elif action in ['конфа']:
            self.check_conversation()
            return self.get_subs(conversation=True)
        else:
            return "Не понял команды (добавить/удалить/подписки)"
Exemple #5
0
    def start(self):
        if self.vk_event.sender.city is None:
            return "Не знаю ваш город. /город"
        if not check_user_group(self.vk_event.sender, Role.TRUSTED) and \
                len(NotifyModel.objects.filter(author=self.vk_event.sender)) >= 5:
            return "Нельзя добавлять более 5 напоминаний"
        user_timezone = self.vk_event.sender.city.timezone.name

        date, args_count, exact_time_flag = get_time(self.vk_event.args[0],
                                                     self.vk_event.args[1])
        if args_count == 2:
            self.check_args(3)
        if not date:
            return "Не смог распарсить дату"
        date = normalize_datetime(date, user_timezone)
        datetime_now = localize_datetime(datetime.utcnow(), "UTC")

        if (date - datetime_now).seconds < 60:
            return "Нельзя добавлять напоминание на ближайшую минуту"
        if not exact_time_flag and ((date - datetime_now).days < 0 or
                                    (datetime_now - date).seconds < 0):
            date = date + timedelta(days=1)
        if (date - datetime_now).days < 0 or (datetime_now - date).seconds < 0:
            return "Нельзя указывать дату в прошлом"

        text = self.vk_event.original_args.split(' ', args_count)[args_count]
        if text[0] == '/':
            first_space = text.find(' ')
            if first_space > 0:
                command = text[1:first_space]
            else:
                command = text[1:]
            from apps.API_VK.command.commands.NotifyRepeat import NotifyRepeat
            if command in self.names or command in NotifyRepeat().names:
                text = f"/обосрать {self.vk_event.sender.name}"
        notify_datetime = localize_datetime(remove_tz(date), user_timezone)

        notify = NotifyModel(
            date=date,
            text=text,
            author=self.vk_event.sender,
            chat=self.vk_event.chat,
            text_for_filter=notify_datetime.strftime("%d.%m.%Y %H:%M") + " " +
            text)
        if self.vk_event.attachments:
            notify.attachments = json.dumps(self.vk_event.attachments)
        notify.save()
        notify.text_for_filter += f" ({notify.id})"
        notify.save()

        return f'Сохранил на дату {str(notify_datetime.strftime("%d.%m.%Y %H:%M"))}'
Exemple #6
0
    def menu(self, vk_event, send=True):
        from apps.API_VK.command.initial import get_commands

        # Проверяем не остановлен ли бот, если так, то проверяем вводимая команда = старт?
        if not self.check_bot_working():
            if not check_user_group(vk_event.sender, Role.ADMIN):
                return

            if vk_event.command in ['старт']:
                self.BOT_CAN_WORK = True
                # cameraHandler.resume()
                msg = "Стартуем!"
                self.send_message(vk_event.peer_id, msg)
                log_result = {'result': msg}
                logger.debug(log_result)
                return msg
            return

        group = vk_event.sender.groups.filter(name=Role.BANNED.name)
        if len(group) > 0:
            return

        if self.DEBUG and send:
            if hasattr(vk_event, 'payload') and vk_event.payload:
                debug_message = \
                    f"msg = {vk_event.msg}\n" \
                    f"command = {vk_event.command}\n" \
                    f"args = {vk_event.args}\n" \
                    f"payload = {vk_event.payload}\n"
            else:
                debug_message = \
                    f"msg = {vk_event.msg}\n" \
                    f"command = {vk_event.command}\n" \
                    f"args = {vk_event.args}\n" \
                    f"original_args = {vk_event.original_args}\n"
            self.send_message(vk_event.peer_id, debug_message)

        log_vk_event = {'vk_event': vk_event}
        logger.debug(log_vk_event)

        commands = get_commands()
        for command in commands:
            try:
                if command.accept(vk_event):
                    result = command.__class__().check_and_start(
                        self, vk_event)
                    if send:
                        self.parse_and_send_msgs(vk_event.peer_id, result)
                    append_command_to_statistics(vk_event.command)
                    log_result = {'result': result}
                    logger.debug(log_result)
                    return result
            except RuntimeWarning as e:
                msg = str(e)
                log_runtime_warning = {'result': msg}
                logger.warning(log_runtime_warning)

                if send:
                    self.parse_and_send_msgs(vk_event.peer_id, msg)
                return msg
            except RuntimeError as e:
                exception = str(e)
                log_runtime_error = {
                    'exception': exception,
                    'result': exception
                }
                logger.error(log_runtime_error)
                if send:
                    self.parse_and_send_msgs(vk_event.peer_id, exception)
                return exception
            except Exception as e:
                msg = "Непредвиденная ошибка. Сообщите разработчику в группе или команда /баг"
                tb = traceback.format_exc()
                log_exception = {'exception': str(e), 'result': msg}
                logger.error(log_exception, exc_info=tb)
                if send:
                    self.parse_and_send_msgs(vk_event.peer_id, msg)
                return msg

        if vk_event.chat and not vk_event.chat.need_reaction:
            return None
        similar_command = commands[0].names[0]
        tanimoto_max = 0
        user_groups = get_user_groups(vk_event.sender)
        for command in commands:
            # Выдача пользователю только тех команд, которые ему доступны
            command_access = command.access
            if isinstance(command_access, str):
                command_access = [command_access]
            if command_access.name not in user_groups:
                continue

            for name in command.names:
                if name:
                    tanimoto_current = tanimoto(vk_event.command, name)
                    if tanimoto_current > tanimoto_max:
                        tanimoto_max = tanimoto_current
                        similar_command = name

        msg = f"Я не понял команды \"{vk_event.command}\"\n"
        if tanimoto_max != 0:
            msg += f"Возможно вы имели в виду команду \"{similar_command}\""
        logger_result = {'result': msg}
        logger.debug(logger_result)
        if send:
            self.send_message(vk_event.peer_id, msg)
        return msg
Exemple #7
0
def get_memes_names(memes, sender):
    if check_user_group(sender, Role.MODERATOR):
        meme_names = [f"{meme.name} (id - {meme.id})" for meme in memes]
    else:
        meme_names = [meme.name for meme in memes]
    return meme_names