def start(self): if not self.event.sender.check_role(Role.TRUSTED) and \ len(NotifyModel.objects.filter(author=self.event.sender)) >= 5: raise PWarning("Нельзя добавлять более 5 напоминаний") timezone = self.event.sender.city.timezone.name date, args_count, exact_time_flag = get_time( self.event.args[0], self.event.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.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.bot.commands.NotifyRepeat import NotifyRepeat if command in self.names or command in NotifyRepeat().names: text = f"/обосрать {self.event.sender.name}" notify_datetime = localize_datetime(remove_tz(date), timezone) notify = NotifyModel( date=date, text=text, author=self.event.sender, chat=self.event.chat, text_for_filter=notify_datetime.strftime("%d.%m.%Y %H:%M") + " " + text) if self.event.platform == Platform.VK: if self.event.attachments: notify.attachments = self.event.attachments notify.save() notify.text_for_filter += f" ({notify.id})" notify.save() return f'Сохранил на дату {str(notify_datetime.strftime("%d.%m.%Y %H:%M"))}'
def start(self): if self.event.fwd: if self.event.args: if self.event.args[0] == '1': for fwd in self.event.fwd: lms = LaterMessageSession() lms.date = localize_datetime(datetime.utcnow(), "UTC") lms.author = self.event.sender lms.save() self._append_message_to_lms(fwd, lms) lms.save() else: raise PWarning("Не понял аргумента") else: lms = LaterMessageSession() lms.date = localize_datetime(datetime.utcnow(), "UTC") lms.author = self.event.sender lms.save() for fwd in self.event.fwd: self._append_message_to_lms(fwd, lms) lms.save() return "Сохранил" else: lms = LaterMessageSession.objects.filter( author=self.event.sender).order_by('date').first() if not lms: raise PWarning("Ничего не нашёл :(") else: author = None msgs = [] for lm in lms.later_messages.all().order_by('date'): if lm.message_author: author = lm.message_author elif lm.message_bot: author = lm.message_bot msg = f"{author} ({lm.date.strftime('%d.%m.%Y %H:%M:%S')}):\n" \ f"{lm.text}" attachments = [] if lm.attachments and lm.attachments != "null": lm_attachments = lm.attachments attachments = get_attachments_for_upload( self.bot, lm_attachments) msgs.append({'msg': msg, 'attachments': attachments}) lm.delete() lms.delete() return msgs
def get_another_position(author, where): positions = { "home": { 0: "Выхожу из дома", 1: "Я дома", "count": 0 }, "work": { 0: "Я на работе", 1: "Выхожу с работы", "count": 0 }, "university": { 0: "Я в универе", 1: "Выхожу из универа", "count": 0 }, } today = localize_datetime(datetime.datetime.utcnow(), author.city.timezone.name) today_logs = MovementLog.objects.filter(date__year=today.year, date__month=today.month, date__day=today.day, author=author) for today_log in today_logs: if today_log.event in positions: positions[today_log.event]['count'] += 1 msg = positions[where][positions[where]['count'] % 2] return msg
def start(self): if self.event.args: city = City.objects.filter( synonyms__icontains=self.event.args[0]).first() else: city = self.event.sender.city self.check_city(city) new_date = localize_datetime(datetime.datetime.utcnow(), city.timezone.name) return new_date.strftime("%d.%m.%Y\n%H:%M:%S")
def start(self): user = self.bot.get_user_by_name(self.event.args, self.event.chat) if self.event.sender.city: timezone = self.event.sender.city.timezone.name else: timezone = TIME_ZONE today = localize_datetime(datetime.datetime.utcnow(), timezone) log = MovementLog.objects.filter(success=True, date__year=today.year, date__month=today.month, date__day=today.day, author=user).first() if user is None: raise PWarning("Такого пользователя нет") if log is None: raise PWarning("Информации пока ещё нет") localized_date = localize_datetime(remove_tz(log.date), timezone).strftime("%H:%M:%S") return f"{localized_date}\n{log.msg}"
def menu_play(self): with lock: winner_today = PetrovichGames.objects.filter( chat=self.event.chat).last() if winner_today: datetime_now = localize_datetime(datetime.datetime.utcnow(), DEFAULT_TIME_ZONE) datetime_last = localize_datetime(remove_tz(winner_today.date), DEFAULT_TIME_ZONE) if (datetime_now.date() - datetime_last.date()).days <= 0: if winner_today.user.gender == '1': winner_gender = "Петровна" else: winner_gender = "Петрович" return f"{winner_gender} дня - {winner_today.user}" group_banned = Group.objects.get(name=Role.BANNED.name) winner = PetrovichUser.objects.filter( chat=self.event.chat, active=True).exclude( user__groups=group_banned).order_by("?").first() if winner: winner = winner.user else: raise PWarning( "Нет участников игры. Зарегистрируйтесь! /петрович рег") PetrovichGames.objects.filter(chat=self.event.chat).delete() PetrovichGames(user=winner, chat=self.event.chat).save() winner_petrovich = PetrovichUser.objects.filter( user=winner, chat=self.event.chat).first() winner_petrovich.wins += 1 winner_petrovich.save() if winner_petrovich.user.gender == '1': winner_gender = "Наша сегодняшняя Петровна дня" else: winner_gender = "Наш сегодняшний Петрович дня" messages = [ "Такс такс такс, кто тут у нас", f"{winner_gender} - {self.bot.get_mention(winner_petrovich.user, str(winner_petrovich.user))}" ] return messages
def get_notifies_from_object(notifies_obj, timezone, print_username=False): if len(notifies_obj) == 0: raise PWarning("Нет напоминаний") result = "" for notify in notifies_obj: notify_datetime = localize_datetime(remove_tz(notify.date), timezone) if print_username: result += f"{notify.author}\n" if notify.repeat: 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" return result
def start(self): text_filter = None page = 1 if self.event.args is not None: if len(self.event.args) >= 2: text_filter = " ".join(self.event.args[:-1]) page = self.event.args[-1] page, result = check_int_arg(page) if not result: page = 1 self.check_number_arg_range(page, 0) elif len(self.event.args) == 1: arg = self.event.args[0] try: arg = int(arg) page = arg except ValueError: text_filter = self.event.args[0] if self.event.chat: objs = QuoteBook.objects.filter(chat=self.event.chat) else: objs = QuoteBook.objects.filter(user=self.event.sender) if text_filter: objs = objs.filter(text__icontains=text_filter) objs = objs.order_by('-date') p = Paginator(objs, 5) if page <= 0: page = 1 if page > p.num_pages: page = p.num_pages objs_on_page = p.page(page) if self.event.sender.city: time_zone = self.event.sender.city.timezone else: time_zone = DEFAULT_TIME_ZONE msg = f"Страница {page}/{p.num_pages}\n\n" for i, obj_on_page in enumerate(objs_on_page): dt = localize_datetime( remove_tz(obj_on_page.date), str(time_zone)).strftime('%d.%m.%Y %H:%M:%S') if self.event.platform == Platform.API: msg += f"Цитата #{i + 1}\n" \ f"{obj_on_page.text}\n" \ f"(c) {dt}\n" else: msg += f"------------------------------{i + 1}------------------------------\n" \ f"{obj_on_page.text}\n" \ f"(c) {dt}\n" return msg
def handle(self, *args, **options): from apps.bot.classes.common.CommonMethods import remove_tz, localize_datetime from apps.bot.classes.common.CommonMethods import get_attachments_for_upload notifies = Notify.objects.all() datetime_now = datetime.utcnow() for notify in notifies: try: if notify.author.check_role(Role.BANNED): continue if notify.repeat: datetime1 = datetime.combine(date.min, remove_tz(notify.date).time()) datetime2 = datetime.combine(date.min, datetime_now.time()) delta_time = datetime1 - datetime2 + timedelta(minutes=1) flag = delta_time.seconds <= 60 else: delta_time = remove_tz( notify.date) - datetime_now + timedelta(minutes=1) flag = delta_time.days == 0 and delta_time.seconds <= 60 if flag: attachments = [] if notify.chat: platform = notify.chat.get_platform_enum() else: platform = notify.author.get_platform_enum() bot = get_bot_by_platform(platform)() event_model = get_event_by_platform(platform) if notify.attachments and notify.attachments != "null": notify_attachments = notify.attachments attachments = get_attachments_for_upload( bot, notify_attachments) notify_datetime = localize_datetime( remove_tz(notify.date), notify.author.city.timezone.name) message = f"Напоминалка на {notify_datetime.strftime('%H:%M')}\n" \ f"{bot.get_mention(notify.author)}:\n" \ f"{notify.text}" result_msg = {'msg': message, 'attachments': attachments} if notify.chat: bot.parse_and_send_msgs_thread(notify.chat.chat_id, result_msg) # Раскоментить если отправлять в лс пользователю, что это его напоминание else: # Если напоминание в ЛС и это не команда # Если надо уведомлять о том, что будет выполнена команда - убираем условие if not notify.text.startswith('/'): bot.parse_and_send_msgs_thread( notify.author.user_id, result_msg) # Если отложенная команда if notify.text.startswith('/'): msg = notify.text[1:] event = { 'message': { 'text': msg }, 'sender': notify.author, 'platform': platform } if notify.chat: event['chat'] = notify.chat event['peer_id'] = notify.chat.chat_id else: event['chat'] = None event['peer_id'] = notify.author.user_id event_object = event_model(event) bot.menu(event_object, send=True) if notify.repeat: # Для постоянных уведомлений дата должа быть на завтрашний день обязательно. # Это важно для сортировки new_datetime = datetime.combine( datetime_now.date(), notify.date.time()) + timedelta(days=1) new_datetime = localize_datetime( remove_tz(new_datetime), notify.author.city.timezone.name) notify.date = new_datetime notify.save() else: notify.delete() except Exception as e: print(str(e)) tb = traceback.format_exc() print(tb)