Files
journal-bot/bot/cronjob/random_memory.py
Remy Moll f7478fb1e3
All checks were successful
Build container / Build (pull_request) Successful in 1m10s
more refinements for the deployment
2025-07-29 15:58:34 +02:00

67 lines
2.4 KiB
Python

from datetime import time, timedelta, timezone, datetime, date
from telegram.constants import ParseMode
import os
from peewee import fn
import logging
import models
from telegram.ext import ExtBot
class RandomMemoryJob():
def __init__(self, bot: ExtBot, job_queue):
self.bot = bot
self.logger = logging.getLogger(self.__class__.__name__)
if not models.IS_PRODUCTION:
# when running locally, annoy the programmer every 60 seconds <3
job_queue.run_repeating(self.callback_memory, interval=3600)
self.min_age = 0 # do not filter messages: show them all
else:
# set the message sending time; include UTC shift +2
sending_time = time(hour=12, minute=0, second=0, tzinfo=timezone(timedelta(hours=2)))
job_queue.run_daily(self.callback_memory, sending_time)
self.min_age = 30 # days
async def callback_memory(self, context):
# last_seen of memory must be older than 10 days in past or None
with models.db:
possible_entries = models.JournalEntry.select().where(
(models.JournalEntry.last_shown <= datetime.today().date() - timedelta(days=self.min_age)) | \
(models.JournalEntry.last_shown == None)
).order_by(fn.Random())
try:
chosen_entry = possible_entries.get()
except:
self.logger.warning("Come back later for another memory.")
return
# update the last_shown of the chosen entry
chosen_entry.last_shown = datetime.today().date()
chosen_entry.save()
chat_id = os.getenv("CHAT_ID")
rating_string = f" ({models.RATING_MAPPING[chosen_entry.rating]})" if chosen_entry.rating else ""
message_text = f"On {chosen_entry.date_pretty}{rating_string}, " \
f"{chosen_entry.author} wrote: \n" \
f"{chosen_entry.spoiler_text}"
if chosen_entry.media_path:
await self.bot.send_photo(
chat_id = chat_id,
photo = chosen_entry.media_path,
caption = message_text,
parse_mode=ParseMode.HTML
)
else:
await self.bot.send_message(
chat_id = chat_id,
text = message_text,
parse_mode=ParseMode.HTML
)