chat photo improvements.

This commit is contained in:
Lia Schöneweiß
2023-05-24 15:52:33 +02:00
committed by Remy Moll
parent 0860196a53
commit 1613e05b61
3 changed files with 66 additions and 49 deletions

View File

@@ -1,22 +1,45 @@
import os
from pathlib import Path
from telegram.ext import ExtBot
import random
from telegram.error import BadRequest
import logging
from datetime import time, timedelta, timezone, datetime, date
from peewee import fn
MEDIA_DIR = Path(os.getenv("MEDIA_DIR"))
CHAT_ID = os.getenv("CHAT_ID")
async def set_random(bot: ExtBot) -> None:
"""Set a random chat photo."""
if os.getenv("DOCKERIZED", "false") == "false":
# only change image on prod
return
photos = list(MEDIA_DIR.glob("*.jpg")) + list(MEDIA_DIR.glob("*.png")) + list(MEDIA_DIR.glob("*.jpeg"))
if len(photos) == 0:
return
class SetChatPhotoJob():
def __init__(self, models, bot: ExtBot, job_queue):
self.models = models
self.bot = bot
self.logger = logging.getLogger(self.__class__.__name__)
if os.getenv("DOCKERIZED", "false") != "true":
# when running locally, annoy the programmer every 60 seconds <3
job_queue.run_repeating(self.callback_photo, interval=60)
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_monthly(self.callback_photo, when=sending_time, day=-1)
photo = random.choice(photos)
await bot.set_chat_photo(CHAT_ID, photo)
async def callback_photo(self, context):
# last_seen of memory must be older than 10 days in past or None
with self.models.db:
possible_photos = self.models.JournalEntry.select().where(
self.models.JournalEntry.media_path != None
).order_by(fn.Random())
try:
chosen_entry = possible_photos.get()
except:
self.logger.warning("No photos available.")
return
chat_id = os.getenv("CHAT_ID")
try:
await self.bot.set_chat_photo(chat_id, chosen_entry.media_path)
except BadRequest:
self.logger.error("This is a private chat!")
return