ruz-bot/daemons/notify.py
Administrator 8852e91aa4 minutes
2022-10-31 12:52:27 +03:00

72 lines
3.0 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 logging
from time import sleep
from telebot.apihelper import ApiTelegramException
from daemons.bot import bot
from helpers import now
from helpers.models import UserSchema
from helpers.mongo import mongo
from helpers.ruz import ruz
def process():
for user in mongo.users_collection.find({"notify_minutes": {"$ne": None}, "hse_id": {"$ne": None}}):
time_now = now(UserSchema().load(user))
for lesson in mongo.lessons_collection.find({
"hse_user_id": user["hse_id"],
"begin": {"$lte": time_now + datetime.timedelta(minutes=user["notify_minutes"])},
"notified": False
}):
ans = f"📅 {lesson['begin'].strftime('%d.%m')}\n"
ans += f"📚 {lesson['discipline']}\n"
ans += f"🏢 {lesson['building']}, {lesson['auditorium']}\n"
ans += f"🕑 {lesson['begin'].strftime('%H:%M')} - {lesson['end'].strftime('%H:%M')}\n"
ans += f"🧑‍🏫 {(lesson['lecturer'] or 'Неизвестно')}\n"
if lesson.get('link', None):
ans += f"🔗 {lesson['link']}"
try:
bot.send_message(
user["chat_id"],
f"Через {user['notify_minutes']} минут у тебя занятие!\n" + ans
)
except ApiTelegramException:
pass
mongo.lessons_collection.update_one({"_id": lesson['_id']}, {"$set": {"notified": True}})
time_now = datetime.datetime.now()
for user in mongo.users_collection.find({"next_daily_notify_time": {"$lte": time_now}}):
user_model = UserSchema().load(user)
deny_weekday = 6 if user_model.daily_notify_today else 5
if time_now.weekday() != deny_weekday:
if user_model.daily_notify_today:
lessons = mongo.get_today_lessons(user_model)
else:
lessons = mongo.get_tomorrow_lessons(user_model)
if len(lessons) == 0:
text = f"{'Сегодня' if user_model.daily_notify_today else 'Завтра'} у тебя нет пар, отдыхай."
else:
text = ruz.schedule_builder(lessons)
try:
bot.send_message(
user["chat_id"],
f"Уведомляю о занятиях! Твое расписание на {'сегодня' if user_model.daily_notify_today else 'завтра'}:\n" + text
)
except:
pass
mongo.users_collection.update_one(
{"chat_id": user["chat_id"]},
{"$set": {"next_daily_notify_time": user_model.next_daily_notify_time + datetime.timedelta(days=1)}}
)
def notify():
while True:
logging.info("notify start")
begin = datetime.datetime.now()
process()
end = datetime.datetime.now()
logging.info('notify finished')
logging.info("time elapsed %s", (end - begin).total_seconds())
sleep(63 - end.second)