Немного отдохнув пришёл к такому решению:
def morning_routine():
"""
Delete old message IDs from the DB. Telegram's policy doesn't allow bots
to delete messages that are older than 48 hours. Wake's up a little bit
slow, to give the database time to fully load.
:return: Nothing
"""
sleep(5)
session = Session(engine)
threshold = datetime.now() - timedelta(hours=48)
stmt = delete(Message).where(
Message.date_added < threshold.strftime('%Y-%m-%d %H:%M:%S')
)
try:
session.execute(stmt)
session.commit()
except ProgrammingError:
subprocess.run(
'alembic revision --autogenerate -m "Initial migration"',
shell=True
)
subprocess.run('alembic upgrade head', shell=True)
finally:
session.close()
Буду рад конструктивной критике!