from datetime import datetime, timedelta from telegram import ParseMode, ReplyKeyboardRemove from flask import current_app from app import app_context from ..jobs import JobQueue # RECORD_REMINDER_INITIAL_DELAY = timedelta(hours=4) # RECORD_REMINDER_INTERVAL = timedelta(hours=2) # RESERVATION_REMINDER_TIME_DELTA = timedelta(minutes=10) def add_record_reminder(record): with app_context(): initial_delay = current_app.config.get('RECORD_REMINDER_INITIAL_DELAY', timedelta(hours=4)) interval = current_app.config.get('RECORD_REMINDER_INTERVAL', timedelta(hours=2)) JobQueue.add_job_repeating( modelname='record', id=record._id, taskname='', callback=send_record_reminder, first=(record.time_start + initial_delay - datetime.now()), interval=interval, context={ 'record_id': record._id } ) def remove_record_reminder(record): JobQueue.remove_job(modelname='record', id=record._id, taskname='') def update_record_reminder(record): remove_record_reminder(record) add_record_reminder(record) def send_record_reminder(context): job = context.job record_id = job.context['record_id'] from app.controllers import RecordController with app_context(): record = RecordController.get(record_id) chat_id = record.user.telegram_chat_id now = datetime.now() if record.time_end and now > record.time_end: # Remove reminder if the end time is passed remove_record_reminder(record) return seconds = (now - record.time_start).total_seconds() hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) if hours > 0: time_string = '{} hours and {} minutes'.format(int(hours), int(minutes)) elif minutes > 0: time_string = '{} minutes'.format(int(minutes)) else: time_string = '{} seconds'.format(int(seconds)) reminder_text = ( 'You are at the workshop for ' + time_string + '.\n\n' 'Send /leave if you are not there anymore.' ) context.bot.send_message(chat_id, text=reminder_text)