ruz-bot/daemons/notify.py
2022-10-21 18:17:41 +03:00

67 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
import zoneinfo
from time import sleep
import croniter
import pytz
from telebot.apihelper import ApiTelegramException
from daemons.bot import bot
from helpers import now
from helpers.keyboards import main_keyboard
from helpers.models import UserSchema
from helpers.mongo import mongo
from helpers.ruz import ruz
def process():
for user in mongo.users_collection.find({"hse_id": {"$ne": None}, "next_notify_time": {"$lte": now()}}):
try:
lessons = mongo.get_today_lessons(UserSchema().load(user))
if len(lessons) == 0:
ans = "Сегодня у тебя нет пар."
else:
ans = ruz.schedule_builder(lessons)
bot.send_message(
user['chat_id'],
"Напоминаю о занятиях сегодня!\n" + ans,
reply_markup=main_keyboard()
)
except:
pass
hours, minutes = user['notify_daily'].split(':')
cron = croniter.croniter(f"{minutes} {hours} * * *", now())
next_date = cron.get_next(datetime.datetime)
next_date = next_date.replace(tzinfo=pytz.timezone('Europe/Moscow'))
mongo.users_collection.update_one({"chat_id": user['chat_id']}, {"$set": {"next_notify_time": next_date}})
for user in mongo.users_collection.find({"notify_minutes": {"$ne": None}, "hse_id": {"$ne": None}}):
for lesson in mongo.lessons_collection.find({
"hse_user_id": user["hse_id"],
"begin": {"$lte": now() + datetime.timedelta(minutes=5)},
"notified": False
}):
ans = ""
ans += f"Аудитория: {lesson['building']}, {lesson['auditorium']}\n"
ans += f"Начало: {lesson['begin'].strftime('%H:%M')}\n"
ans += f"Конец: {lesson['end'].strftime('%H:%M')}\n"
ans += f"Преподаватель: {(lesson['lecturer'] or 'Неизвестно')}\n"
try:
bot.send_message(
user["chat_id"],
"Уведомляю о занятиях!\n" + ans
)
except ApiTelegramException:
pass
mongo.lessons_collection.update_one({"_id": lesson['_id']}, {"$set": {"notified": True}})
def notify():
while True:
print("notify start")
begin = datetime.datetime.now()
process()
end = datetime.datetime.now()
print('notify finished')
print("time elapsed", (end - begin).total_seconds())
sleep(60 * 2)