Ejemplo n.º 1
0
 def menu_bonus(self):
     datetime_now = localize_datetime(datetime.datetime.utcnow(), DEFAULT_TIME_ZONE)
     datetime_last = localize_datetime(remove_tz(self.gamer.roulette_points_today), DEFAULT_TIME_ZONE)
     if (datetime_now.date() - datetime_last.date()).days > 0:
         self.gamer.roulette_points += 500
         self.gamer.roulette_points_today = datetime_now
         self.gamer.save()
         return "Выдал пособие по безработице"
     else:
         raise PWarning("Ты уже получил бонус. Приходи завтра")
Ejemplo n.º 2
0
    def start(self):
        if not self.event.sender.check_role(Role.TRUSTED) and \
                len(NotifyModel.objects.filter(user=self.event.user)) >= 5:
            raise PWarning("Нельзя добавлять более 5 напоминаний")
        timezone = self.event.sender.city.timezone.name

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

        if (date - datetime_now).seconds < 60:
            raise PWarning("Нельзя добавлять напоминание на ближайшую минуту")
        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:
            raise PWarning("Нельзя указывать дату в прошлом")

        text = self.event.message.args_str_case.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.bot.commands.NotifyRepeat import NotifyRepeat
            if command in self.full_names or command in NotifyRepeat(
            ).full_names:
                text = f"/обосрать {self.event.sender.name}"
        notify_datetime = localize_datetime(remove_tz(date), timezone)

        notify = NotifyModel(
            date=date,
            text=text,
            user=self.event.user,
            chat=self.event.chat,
            text_for_filter=notify_datetime.strftime("%d.%m.%Y %H:%M") + " " +
            text)
        notify.save()
        notify.text_for_filter += f" ({notify.id})"
        notify.save()

        return f'Сохранил на дату {str(notify_datetime.strftime("%d.%m.%Y %H:%M"))}'
Ejemplo n.º 3
0
    def get_flag_by_notify(self, notify):

        if notify.user.profile.check_role(Role.BANNED):
            return False

        if notify.repeat:
            if notify.crontab:
                timezone = notify.user.profile.city.timezone.name
                localized_datetime = localize_datetime(remove_tz(self.dt_now),
                                                       timezone)

                entry = CronTab(notify.crontab)
                prev_seconds_delta = -entry.previous(localized_datetime,
                                                     default_utc=True)
                return prev_seconds_delta <= 60
            else:
                datetime1 = datetime.combine(date.min,
                                             remove_tz(notify.date).time())
                datetime2 = datetime.combine(date.min, self.dt_now.time())
                delta_time = datetime1 - datetime2 + timedelta(minutes=1)
                return delta_time.seconds <= 60
        else:
            delta_time = remove_tz(
                notify.date) - self.dt_now + timedelta(minutes=1)
            return delta_time.days == 0 and delta_time.seconds <= 60
Ejemplo n.º 4
0
def get_notifies_from_object(notifies_obj, timezone, print_username=False):
    if len(notifies_obj) == 0:
        raise PWarning("Нет напоминаний")
    result = ""

    for notify in notifies_obj:
        if notify.date:
            notify_datetime = localize_datetime(remove_tz(notify.date), timezone)
        else:
            notify_datetime = notify.crontab

        if print_username:
            result += f"{notify.user}\n"
        if notify.repeat:
            if notify.crontab:
                result += f"{notify_datetime} - Постоянное"
            else:
                result += f"{str(notify_datetime.strftime('%H:%M'))} - Постоянное"
        else:
            result += f"{str(notify_datetime.strftime('%d.%m.%Y %H:%M'))} - Постоянное"
        if notify.chat:
            result += f" (Конфа - {notify.chat.name})"
        result += f"\n{notify.text}\n\n"

    result_without_mentions = result.replace('@', '@_')
    return result_without_mentions
Ejemplo n.º 5
0
 def get_avg_price_data(data, tariff):
     tariff_map = {
         'econom': 0,
         'comfort': 1,
         'comfortplus': 2,
         'express': 3,
         'courier': 4,
     }
     tariff_val = tariff_map[tariff]
     x_data = [
         localize_datetime(remove_tz(x.created), 'Europe/Samara').replace(
             day=1, month=1, year=1900) + datetime.timedelta(hours=4)
         for x in data[list(data.keys())[0]]
     ]
     y_data = [0 for _ in range(len(x_data))]
     y_data_len = [0 for _ in range(len(x_data))]
     for key in data:
         for i, item in enumerate(data[key]):
             try:
                 y = item.data['options'][tariff_val]['price']
                 y_data[i] += y
                 y_data_len[i] += 1
             except Exception:
                 pass
     y_data = [x[0] / x[1] for x in zip(y_data, y_data_len)]
     return x_data, y_data
Ejemplo n.º 6
0
    def menu_play(self):
        with lock:
            datetime_now = localize_datetime(datetime.datetime.utcnow(),
                                             DEFAULT_TIME_ZONE)
            winner_today = PetrovichGames.objects.filter(
                chat=self.event.chat).first()
            if winner_today:
                datetime_last = localize_datetime(remove_tz(winner_today.date),
                                                  DEFAULT_TIME_ZONE)
                if (datetime_now.date() - datetime_last.date()).days <= 0:
                    if winner_today.profile.gender and winner_today.profile.gender == '1':
                        winner_gender = "Петровна"
                    else:
                        winner_gender = "Петрович"
                    return f"{winner_gender} дня - {winner_today.profile}"

            group_banned = Group.objects.get(name=Role.BANNED.name)
            winner = PetrovichUser.objects.filter(
                chat=self.event.chat, active=True).exclude(
                    profile__groups=group_banned).order_by("?").first()
            if winner:
                winner = winner.profile
            else:
                raise PWarning(
                    "Нет участников игры. Зарегистрируйтесь! /петрович рег")

            winner_petrovich = PetrovichGames(profile=winner,
                                              chat=self.event.chat)
            winner_petrovich.save()
            if winner.gender and winner.gender == '1':
                winner_gender = "Наша сегодняшняя Петровна дня"
            else:
                winner_gender = "Наш сегодняшний Петрович дня"

            first_message = random_event([
                "Такс такс такс, кто тут у нас", "*барабанная дробь*",
                "Вы готовы узнать победителя голодных игр?", "Ну шо, погнали",
                "Вы не поверите...",
                "Опять вы в игрульки свои играете да? Ну ладно"
            ])

            return [
                first_message,
                f"{winner_gender} - {self.bot.get_mention(winner, str(winner))}"
            ]
Ejemplo n.º 7
0
 def extend_repeat_notify(self, notify):
     if notify.date:
         # Для постоянных уведомлений дата должа быть на завтрашний день обязательно.
         # Это важно для сортировки
         new_datetime = datetime.combine(
             self.dt_now.date(), notify.date.time()) + timedelta(days=1)
         new_datetime = localize_datetime(
             remove_tz(new_datetime),
             notify.user.profile.city.timezone.name)
         notify.date = new_datetime
         notify.save()
Ejemplo n.º 8
0
    def start(self):
        city = None
        if self.event.message.args:
            city = City.objects.filter(
                synonyms__icontains=self.event.message.args[0]).first()
        if not city:
            city = self.event.sender.city
        self.check_city(city)

        new_date = localize_datetime(datetime.datetime.utcnow(),
                                     city.timezone.name)
        dt_str = new_date.strftime("%d.%m.%Y\n%H:%M:%S")
        return f"Время в городе {city}\n\n{dt_str}"
Ejemplo n.º 9
0
    def send_notify_message(bot, notify):
        if notify.date:
            notify_datetime = localize_datetime(
                remove_tz(notify.date), notify.user.profile.city.timezone.name)
            user_str = f"{bot.get_mention(notify.user.profile)}:" if notify.mention_sender else f"{notify.user.profile}:"
            message = f"Напоминалка на {notify_datetime.strftime('%H:%M')}\n" \
                      f"{user_str}\n" \
                      f"{notify.text}"
        else:
            if notify.user.get_platform_enum() == Platform.TG:
                message = f"Напоминалка по {get_tg_formatted_text_line(notify.crontab)}\n"
            else:
                message = f"Напоминалка по {notify.crontab}\n"
            user_str = f"{bot.get_mention(notify.user.profile)}" if notify.mention_sender else f"{notify.user.profile}"
            message += f"{user_str}\n" \
                       f"{notify.text}"

        result_msg = {'text': message}

        if notify.chat:
            bot.parse_and_send_msgs(result_msg, notify.chat.chat_id)
        else:
            if not notify.text.startswith('/'):
                bot.parse_and_send_msgs(result_msg, notify.user.user_id)
Ejemplo n.º 10
0
    def start(self):
        if not self.event.sender.check_role(Role.TRUSTED) and \
                len(NotifyModel.objects.filter(user=self.event.sender)) >= 5:
            raise PWarning("Нельзя добавлять более 5 напоминаний")
        timezone = self.event.sender.city.timezone.name

        crontab = None
        date = None
        try:
            crontab = get_crontab(self.event.message.args)
            args_split = self.event.message.args_str_case.split(' ', 5)
            if len(args_split) > 5:
                text = args_split[-1]
            else:
                text = ""
        except Exception:
            date = get_time(self.event.message.args[0])
            if not date:
                raise PWarning("Не смог распарсить дату")
            date = normalize_datetime(date, timezone)
            datetime_now = localize_datetime(datetime.utcnow(), "UTC")

            if (date - datetime_now).seconds < 60:
                raise PWarning(
                    "Нельзя добавлять напоминание на ближайшую минуту")

            if (date - datetime_now).days < 0 or (datetime_now -
                                                  date).seconds < 0:
                date = date + timedelta(days=1)

            text = self.event.message.args_str_case.split(' ', 1)[1]
        if text[0] == '/':
            first_space = text.find(' ')
            if first_space > 0:
                command = text[1:first_space]
            else:
                command = text[1:]
            from apps.bot.commands.Notify import Notify
            if command in self.full_names or command in Notify().full_names:
                text = f"/обосрать {self.event.sender.name}"
        if date:
            notify_datetime = localize_datetime(remove_tz(date), timezone)

        if crontab:
            notify = NotifyModel(crontab=crontab,
                                 text=text,
                                 user=self.event.user,
                                 chat=self.event.chat,
                                 repeat=True,
                                 text_for_filter=f'{crontab} {text}')
        else:
            notify = NotifyModel(
                date=date,
                text=text,
                user=self.event.user,
                chat=self.event.chat,
                repeat=True,
                text_for_filter=f'{notify_datetime.strftime("%H:%M")} {text}')
        notify.save()
        notify.text_for_filter += f" ({notify.id})"
        notify.save()
        if date:
            return f'Следующее выполнение - {str(notify_datetime.strftime("%d.%m.%Y %H:%M"))}'
        else:
            return 'Добавил напоминание'