def send_announcements(self, context): anns = announcements.get_announcements() if not anns: return settingsrepo = UserSettingsRepo() chats = settingsrepo.get_all() logging.info('Sending announcements to %d chats', len(chats)) for ann in anns: for chat in chats: try: context.bot.send_message(chat_id=chat.chat_id, parse_mode=ParseMode.HTML, text=ann['msg']) os_time.sleep(0.1) except telegram.error.Unauthorized as e: logging.warning(e) settingsrepo.delete(chat) except telegram.error.ChatMigrated as e: old = chat.chat_id chat.chat_id = e.new_chat_id settingsrepo.update(chat) logging.info("Updated chat_id %d to %d", old, chat.chat_id) except Exception as e: logging.exception(e) announcements.set_sent(ann) announcements.save_sent() settingsrepo.close() logging.info('Done sending announcements')
def daily_schedule_tomorrow(self, context): now = datetime.now() if now.weekday() == 5: # don't send reminders on the weekend self.daily_schedule_tomorrow_last_run = now return settingsrepo = UserSettingsRepo() users = settingsrepo.get_to_remind_tomorrow() users = [u for u in users if isinstance(u.remind_time_tomorrow, time)] users = [ u for u in users if self.daily_schedule_tomorrow_last_run < u.next_remind_time_tomorrow() <= now ] if not users: settingsrepo.close() return logging.info('Sending tomorrows schedule to %d users', len(users)) for user in users: try: schedule = get_schedule(user.course_id, user.year, user.curricula) if now.weekday() == 6 and not schedule.next_week_has_lessons(): msg = "{}\n\n{}".format(messages.NO_LESSONS_WEEK, messages.NO_REMIND_THIS_WEEK) context.bot.send_message(chat_id=user.chat_id, parse_mode=ParseMode.HTML, text=msg) continue if now.weekday() != 6 and not schedule.week_has_lessons(): continue schedule = schedule.tomorrow() msg = "<b>{}</b>\n\n{{}}".format( messages.YOUR_LESSONS_TOMORROW) if not schedule.has_events(): msg = msg.format(messages.NO_LESSONS) context.bot.send_message(chat_id=user.chat_id, parse_mode=ParseMode.HTML, text=msg) continue msg = msg.format(schedule.tostring(with_date=True)) context.bot.send_message(chat_id=user.chat_id, parse_mode=ParseMode.HTML, text=msg) os_time.sleep(0.1) except NotSupportedError as ex: context.bot.send_message( chat_id=user.chat_id, parse_mode=ParseMode.HTML, text=messages.COURSE_NOT_SUPPORTED.format(ex.reason)) except telegram.error.Unauthorized as e: logging.warning(e) settingsrepo.delete(user) except telegram.error.ChatMigrated as e: old = user.chat_id user.chat_id = e.new_chat_id settingsrepo.update(user) logging.info("Updated chat_id %d to %d", old, user.chat_id) except Exception as e: logging.exception(e) self.daily_schedule_tomorrow_last_run = now settingsrepo.close() logging.info("Done sending tomorrow's schedule")