def handle(self, *args, **kwargs):
        yt_subs = YoutubeSubscribe.objects.all()
        for yt_sub in yt_subs:
            youtube_info = YoutubeInfo(yt_sub.channel_id)
            youtube_data = youtube_info.get_youtube_channel_info()
            if youtube_data['last_video']['date'] > yt_sub.date:
                if yt_sub.chat:
                    bot = get_bot_by_platform(yt_sub.chat.get_platform_enum())
                    peer_id = yt_sub.chat.chat_id
                else:
                    bot = get_bot_by_platform(
                        yt_sub.author.get_platform_enum())
                    peer_id = yt_sub.author.user_id

                if bot.platform == Platform.TG:

                    text = f"Новое видео на канале {yt_sub.title}\n" \
                           f"{get_tg_formatted_url(youtube_data['last_video']['title'], youtube_data['last_video']['link'])}"
                else:
                    text = f"Новое видео на канале {yt_sub.title}\n" \
                           f"{youtube_data['last_video']['title']}\n" \
                           f"{youtube_data['last_video']['link']}"

                bot.parse_and_send_msgs(text, peer_id)
                yt_sub.date = youtube_data['last_video']['date']
                yt_sub.save()
            time.sleep(2)
示例#2
0
    def stop_if_need(self):
        self.get_server_info()
        # Если сервак онлайн и нет игроков
        if self.server_info['online'] and not self.server_info['players']:
            obj, created = Service.objects.get_or_create(name=f'stop_{self._get_service_name()}')

            # Создание событие. Уведомление, что мы скоро всё отрубим
            if created:
                message = f"Если никто не зайдёт на сервак по майну {self.get_version()}, то через полчаса я его остановлю"
                users_notify = Profile.objects.filter(groups__name=Role.MINECRAFT_NOTIFY.name)
                for user in users_notify:
                    bot = get_bot_by_platform(user.get_platform_enum())
                    bot.parse_and_send_msgs_thread(message, user.user_id)

            # Если событие уже было создано, значит пора отрубать
            else:
                update_datetime = obj.update_datetime
                delta_seconds = (datetime.utcnow() - remove_tz(update_datetime)).seconds
                if delta_seconds <= 1800 + 100:
                    obj.delete()
                    Service.objects.get_or_create(self._get_service_name())

                    self.stop(send_notify=False)

                    message = f"Вырубаю майн {self.get_version()}"
                    users_notify = Profile.objects.filter(groups__name=Role.MINECRAFT_NOTIFY.name)
                    for user in users_notify:
                        bot = get_bot_by_platform(user.get_platform_enum())
                        bot.parse_and_send_msgs_thread(message, user.user_id)
                else:
                    obj.delete()

        # Эта ветка нужна, чтобы вручную вырубленные серверы не провоцировали при последующем старте отключение в 0/30 минут
        else:
            Service.objects.filter(name=f'stop_{self._get_service_name()}').delete()
示例#3
0
文件: Meme.py 项目: Xoma163/petrovich
    def menu_rename(self):
        self.check_sender(Role.MODERATOR)
        self.check_args(3)
        self.int_args = [1]
        self.parse_int()
        meme = self.get_meme(_id=self.event.message.args[1])

        new_name_list = self.event.message.args[2:]
        self.check_meme_name_is_no_digits(new_name_list)
        new_name = " ".join(new_name_list)

        try:
            MemeModel.objects.get(name=new_name)
            raise PWarning("Мем с таким названием уже есть")
        except MemeModel.DoesNotExist:
            pass

        user_msg = f'Мем с названием "{meme.name}" переименован.\n' \
                   f'Новое название - "{new_name}"'

        meme.name = new_name
        meme.save()

        if meme.author != self.event.sender:
            user = meme.author.get_user_by_default_platform()
            bot = get_bot_by_platform(user.get_platform_enum())
            bot.parse_and_send_msgs(user_msg, user.user_id)
        return user_msg
示例#4
0
文件: Meme.py 项目: Xoma163/petrovich
    def menu_confirm(self):
        self.check_sender(Role.MODERATOR)

        if len(self.event.message.args) == 1:
            meme = self.get_meme(approved=False)
            meme_to_send = self.prepare_meme_to_send(meme)
            meme_to_send['text'] = f"{meme.author}\n" \
                                   f"{meme.name} ({meme.id})"
            return meme_to_send

        self.check_args(2)

        meme_filter = self.get_default_meme_filter_by_args(
            self.event.message.args[1:])
        meme = self.get_meme(**meme_filter)

        if meme.approved:
            raise PWarning("Мем уже подтверждён")

        user_msg = f'Мем с названием "{meme.name}" подтверждён.'
        user = meme.author.get_user_by_default_platform()
        bot = get_bot_by_platform(user.get_platform_enum())
        bot.parse_and_send_msgs(user_msg, user.user_id)

        msg = f'Мем "{meme.name}" ({meme.id}) подтверждён'
        meme.approved = True
        meme.save()
        return msg
示例#5
0
    def handle(self, *args, **options):
        chat_id = options['chat_id'][0]
        pasha = User.objects.get(user_id=chat_id)
        bot = get_bot_by_platform(pasha.get_platform_enum())

        pasha_news_last_id_entity, created = Service.objects.get_or_create(
            name='pasha_news_last_id',
            defaults={'value': 0}
        )
        pasha_news_last_id = int(pasha_news_last_id_entity.value)
        content = requests.get(f"{self.URL}/news").content
        bs4 = BeautifulSoup(content, "html.parser")
        news = list(bs4.select(".news-list > .row > a"))
        if created:
            last_news_id = self.get_news_id(news[0])
            pasha_news_last_id_entity.value = last_news_id
            pasha_news_last_id_entity.save()
            return

        news_to_send = list(filter(lambda x: self.get_news_id(x) > pasha_news_last_id, news))
        msgs = []
        for news in news_to_send:
            news_content, news_url = self.parse_news(f"{self.URL}{news.attrs['href']}")
            if pasha.get_platform_enum() == Platform.TG:
                text = f'{news_content}\n\n{get_tg_formatted_url("Полная статья", news_url)}'
            else:
                text = f"{news_content}\n\n{news_url}"
            msgs.append(text)

        last_news_id = self.get_news_id(news_to_send[0])
        pasha_news_last_id_entity.value = last_news_id
        pasha_news_last_id_entity.save()

        for msg in msgs:
            bot.parse_and_send_msgs(msg, pasha.user_id)
示例#6
0
        def send_notify():

            users_notify = Profile.objects.filter(groups__name=Role.MINECRAFT_NOTIFY.name)
            if self.event:
                users_notify = users_notify.exclude(id=self.event.sender.id)
                if self.event.chat:
                    users_in_chat = self.event.chat.users.all()
                    users_notify = users_notify.exclude(pk__in=users_in_chat)
            for user in users_notify:
                bot = get_bot_by_platform(user.get_platform_enum())
                bot.parse_and_send_msgs_thread(message, user.user_id)
示例#7
0
文件: Meme.py 项目: Xoma163/petrovich
    def menu_reject(self):
        self.check_sender(Role.MODERATOR)
        self.check_args(2)

        meme_filter = self.get_default_meme_filter_by_args(
            self.event.message.args[1:])
        meme = self.get_meme(**meme_filter)
        if meme.approved:
            raise RuntimeWarning("Нельзя отклонить уже подтверждённый мем")

        msg = f'Мем "{meme.name}" ({meme.id}) отклонён'
        user = meme.author.get_user_by_default_platform()
        bot = get_bot_by_platform(user.get_platform_enum())
        bot.parse_and_send_msgs(msg, user.user_id)

        meme.delete()
        return msg
示例#8
0
文件: Meme.py 项目: Xoma163/petrovich
    def menu_delete(self):
        self.check_args(2)
        meme_filter = self.get_default_meme_filter_by_args(
            self.event.message.args[1:])
        if not self.event.sender.check_role(Role.MODERATOR):
            meme_filter['filter_user'] = self.event.sender
        meme = self.get_meme(**meme_filter)

        # Если удаляем мем другого человека, шлём ему сообщением
        if self.event.sender.check_role(
                Role.MODERATOR) and meme.author != self.event.sender:
            user_msg = f'Мем с названием "{meme.name}" удалён поскольку он не ' \
                       f'соответствует правилам или был удалён автором.'
            user = meme.author.get_user_by_default_platform()
            bot = get_bot_by_platform(user.get_platform_enum())
            bot.parse_and_send_msgs(user_msg, user.user_id)

        meme_name = meme.name
        meme.delete()
        return f'Удалил мем "{meme_name}"'
示例#9
0
    def handle(self, *args, **options):
        chat_pks = options['chat_id'][0].split(',')

        ylc_api = YoutubeLiveCheckerAPI()
        livestream_info = ylc_api.get_stream_info_if_online()
        if not livestream_info:
            return

        stream, _ = Service.objects.get_or_create(name="stream")
        if stream.value == livestream_info['video_url']:
            return

        stream.value = livestream_info['video_url']
        stream.save()

        for chat_pk in chat_pks:
            chat = Chat.objects.get(pk=chat_pk)
            bot = get_bot_by_platform(chat.get_platform_enum())
            url = stream.value
            if bot.platform == Platform.TG:
                text = get_tg_formatted_url("стрим", url)
            else:
                text = f"Ктап подрубил стрим\n{url}"
            bot.parse_and_send_msgs(text, chat.chat_id)
示例#10
0
    def handle(self, *args, **options):

        notifies = Notify.objects.all()

        for notify in notifies:
            try:
                flag = self.get_flag_by_notify(notify)
                if not flag:
                    continue

                platform = notify.chat.get_platform_enum(
                ) if notify.chat else notify.user.get_platform_enum()
                bot = get_bot_by_platform(platform)

                self.send_notify_message(bot, notify)
                self.send_command_notify_message(bot, notify)
                if notify.repeat:
                    self.extend_repeat_notify(notify)
                else:
                    notify.delete()
            except Exception as e:
                print(str(e))
                tb = traceback.format_exc()
                print(tb)