ruz-bot/daemons/notify.py
emmatveev 18aabe497b
All checks were successful
Deploy Dev / Build (pull_request) Successful in 4s
Deploy Dev / Push (pull_request) Successful in 7s
Deploy Dev / Deploy dev (pull_request) Successful in 14s
Deploy Prod / Build (pull_request) Successful in 4s
Deploy Prod / Push (pull_request) Successful in 8s
Deploy Prod / Deploy prod (pull_request) Successful in 20s
fix
2024-11-27 16:37:59 +03:00

91 lines
4.8 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 helpers import now
from helpers.mongo import mongo
from helpers.ruz import ruz
from daemons import base
from utils import queues
def process():
for user in mongo.users_collection.find({"notify_minutes": {"$ne": None}, "email": {"$ne": None}}):
time_now = now(user)
for lesson in mongo.lessons_collection.find({
"user_email": user["email"],
"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']}"
queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': f"Через {user['notify_minutes']} минут у тебя занятие!\n" + ans, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
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}}):
deny_weekday = 6 if user.get('daily_notify_today', True) else 5
if time_now.weekday() != deny_weekday:
if user.get('daily_notify_today', True):
lessons = mongo.get_today_lessons(user)
else:
lessons = mongo.get_tomorrow_lessons(user)
if len(lessons) == 0:
text = f"{'Сегодня' if user.get('daily_notify_today', True) else 'Завтра'} у тебя нет пар, отдыхай."
else:
text = ruz.schedule_builder(lessons)
try:
queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': f"Уведомляю о занятиях! Твое расписание на {'сегодня' if user.get('daily_notify_today', True) else 'завтра'}:\n" + text, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
except:
pass
mongo.users_collection.update_one(
{"chat_id": user["chat_id"]},
{"$set": {"next_daily_notify_time": user['next_daily_notify_time'] + datetime.timedelta(days=1)}}
)
for user in mongo.users_collection.find({"first_lesson_notify": {"$exists": True, "$ne": None}, "email": {"$ne": None}}):
time_now = now(user)
for lesson in mongo.lessons_collection.find({
"user_email": user["email"],
"begin": {"$lte": time_now + datetime.timedelta(minutes=user["first_lesson_notify"])},
"notified_today": {"$ne": True}
}).sort("begin"):
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']}"
mess = "Пары начутся через "
if user['first_lesson_notify'] == 30:
mess += "30 минут"
elif user['first_lesson_notify'] == 60:
mess += "1 час"
elif user['first_lesson_notify'] == 4 * 60:
mess += "4 часа"
else:
mess += "12 часов"
mess += "!\n\nТвоя первая пара:\n\n" + ans
queues.set_task('botalka_mailbox', {'project': 'ruz-bot', 'name': 'telegram-bot', 'body': {'text': mess, 'chat_id': user["chat_id"], 'parse_mode': 'Markdown'}}, 1)
start_of_day = datetime.datetime(year=time_now.year, month=time_now.month, day=time_now.day)
mongo.lessons_collection.update_many({"begin": {"$gte": start_of_day, "$lt": (start_of_day + datetime.timedelta(days=1))}, "user_email": user["email"]}, {"$set": {"notified_today": True}})
break
class Daemon(base.Daemon):
def execute(self):
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)