cleanup the model layout
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Remy Moll 2023-11-17 22:53:06 +01:00
parent 9eb7f5bb77
commit 49df5a4495
7 changed files with 37 additions and 42 deletions

View File

@ -3,7 +3,7 @@ import os
from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters, CallbackQueryHandler from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ParseMode from telegram.constants import ParseMode
import models
ENTRY_OPTIONS, CONTENT_ENTRY = range(2) ENTRY_OPTIONS, CONTENT_ENTRY = range(2)
BUTTON_COUNT = 5 BUTTON_COUNT = 5
@ -12,8 +12,7 @@ BUTTON_COUNT = 5
from .basehandler import BaseHandler from .basehandler import BaseHandler
class JournalHandler(BaseHandler): class JournalHandler(BaseHandler):
def __init__(self, entry_string, models): def __init__(self, entry_string):
self.models = models
self.entry_string = entry_string self.entry_string = entry_string
self.handler = ConversationHandler( self.handler = ConversationHandler(
entry_points=[CommandHandler(entry_string, self.entry_point)], entry_points=[CommandHandler(entry_string, self.entry_point)],
@ -74,12 +73,12 @@ class JournalHandler(BaseHandler):
await query.answer() await query.answer()
date = datetime.datetime.strptime(query.data, "%d%m%Y").date() date = datetime.datetime.strptime(query.data, "%d%m%Y").date()
with self.models.db: with models.db:
self.current_model, new = self.models.JournalEntry.get_or_create( self.current_model, new = models.JournalEntry.get_or_create(
date = date date = date
) )
if new: if new:
count = self.models.JournalEntry.select().count() count = models.JournalEntry.select().count()
await query.edit_message_text( await query.edit_message_text(
text=f"Journal entry no. {count}. What happened on {self.current_model.date_pretty}?" text=f"Journal entry no. {count}. What happened on {self.current_model.date_pretty}?"
) )
@ -128,8 +127,8 @@ class JournalHandler(BaseHandler):
return ENTRY_OPTIONS return ENTRY_OPTIONS
if context.chat_data.get("delete", False): # if not set, delete was not chosen if context.chat_data.get("delete", False): # if not set, delete was not chosen
with self.models.db: with models.db:
self.current_model = self.models.JournalEntry.get_or_none( self.current_model = models.JournalEntry.get_or_none(
date = date date = date
) )
if self.current_model: if self.current_model:
@ -139,15 +138,15 @@ class JournalHandler(BaseHandler):
context.chat_data["delete"] = False context.chat_data["delete"] = False
return ConversationHandler.END return ConversationHandler.END
else: else:
with self.models.db: with models.db:
self.current_model, new = self.models.JournalEntry.get_or_create( self.current_model, new = models.JournalEntry.get_or_create(
date = date date = date
) )
if not new: if not new:
await update.message.reply_text("An entry already exists for this date") await update.message.reply_text("An entry already exists for this date")
return ConversationHandler.END return ConversationHandler.END
else: else:
count = self.models.JournalEntry.select().count() count = models.JournalEntry.select().count()
await update.message.reply_text( await update.message.reply_text(
text=f"Journal entry no. {count}. What happened on {self.current_model.date_pretty}?" text=f"Journal entry no. {count}. What happened on {self.current_model.date_pretty}?"
) )
@ -155,7 +154,7 @@ class JournalHandler(BaseHandler):
async def content_save(self, update, context): async def content_save(self, update, context):
with self.models.db: with models.db:
self.current_model.author_id = update.message.from_user.id self.current_model.author_id = update.message.from_user.id
if update.message.text: if update.message.text:
@ -187,7 +186,7 @@ class JournalHandler(BaseHandler):
async def delete_entry(self, update, context): async def delete_entry(self, update, context):
with self.models.db: with models.db:
self.current_model.delete_instance() self.current_model.delete_instance()
context.chat_data["delete"] = False context.chat_data["delete"] = False
await update.message.reply_text(text="Entry deleted ✅") await update.message.reply_text(text="Entry deleted ✅")

View File

@ -15,8 +15,7 @@ from ..basehandler import BaseHandler
class ListHandler(BaseHandler): class ListHandler(BaseHandler):
"""Create and edit lists""" """Create and edit lists"""
def __init__(self, entry_string, models): def __init__(self, entry_string):
del models # not needed here, but part of the template
self.entry_string = entry_string self.entry_string = entry_string
set_db(PERSISTENCE_DIR / "lists.sqlite") set_db(PERSISTENCE_DIR / "lists.sqlite")

View File

@ -1,15 +1,14 @@
import os import os
from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters, CallbackQueryHandler, CallbackContext from telegram.ext import ConversationHandler, CommandHandler, MessageHandler, filters, CallbackQueryHandler, CallbackContext
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, InputMediaPhoto from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, InputMediaPhoto
# ACTION_CHOICE, DATE_ENTRY, ADD_CONTENT = range(3) import models
MEMORY_CHOICE = range(1) MEMORY_CHOICE = range(1)
from .basehandler import BaseHandler from .basehandler import BaseHandler
class MemoryHandler(BaseHandler): class MemoryHandler(BaseHandler):
def __init__(self, entry_string, models): def __init__(self, entry_string):
self.models = models
self.entry_string = entry_string self.entry_string = entry_string
self.handler = ConversationHandler( self.handler = ConversationHandler(
entry_points=[CommandHandler(entry_string, self.entry_point, )], entry_points=[CommandHandler(entry_string, self.entry_point, )],
@ -34,13 +33,13 @@ class MemoryHandler(BaseHandler):
search_string = " ".join(context.args) search_string = " ".join(context.args)
if search_string == '~photo': if search_string == '~photo':
matching_models = self.models.JournalEntry.select().where(self.models.JournalEntry.media_path != "").order_by(self.models.JournalEntry.date) matching_models = models.JournalEntry.select().where(models.JournalEntry.media_path != "").order_by(models.JournalEntry.date)
else: # searching for text else: # searching for text
matching_models = self.models.JournalEntry.select().where( matching_models = models.JournalEntry.select().where(
self.models.JournalEntry.text.contains( models.JournalEntry.text.contains(
search_string search_string
) )
).order_by(self.models.JournalEntry.date) ).order_by(models.JournalEntry.date)
# exit if no memory matches the string # exit if no memory matches the string

View File

@ -6,16 +6,14 @@ from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.constants import ParseMode from telegram.constants import ParseMode
import os import os
FIRST = 1 FIRST = 1
from .basehandler import BaseHandler from .basehandler import BaseHandler
class StatusHandler(BaseHandler): class StatusHandler(BaseHandler):
"""Shows a short status of the program.""" """Shows a short status of the program."""
def __init__(self, entry_string, models): def __init__(self, entry_string):
self.start_time = datetime.datetime.now() self.start_time = datetime.datetime.now()
self.entry_string = entry_string self.entry_string = entry_string
self.models = models
self.handler = ConversationHandler( self.handler = ConversationHandler(
entry_points=[CommandHandler(self.entry_string, self.entry_point)], entry_points=[CommandHandler(self.entry_string, self.entry_point)],
states={ states={

View File

@ -4,13 +4,13 @@ from telegram.error import BadRequest
import logging import logging
from datetime import time, timedelta, timezone, datetime, date from datetime import time, timedelta, timezone, datetime, date
from peewee import fn from peewee import fn
import models
CHAT_ID = os.getenv("CHAT_ID") CHAT_ID = os.getenv("CHAT_ID")
class SetChatPhotoJob(): class SetChatPhotoJob():
def __init__(self, models, bot: ExtBot, job_queue): def __init__(self, bot: ExtBot, job_queue):
self.models = models
self.bot = bot self.bot = bot
self.logger = logging.getLogger(self.__class__.__name__) self.logger = logging.getLogger(self.__class__.__name__)
@ -26,9 +26,9 @@ class SetChatPhotoJob():
async def callback_photo(self, context): async def callback_photo(self, context):
# last_seen of memory must be older than 10 days in past or None # last_seen of memory must be older than 10 days in past or None
with self.models.db: with models.db:
possible_photos = self.models.JournalEntry.select().where( possible_photos = models.JournalEntry.select().where(
self.models.JournalEntry.media_path != None models.JournalEntry.media_path != None
).order_by(fn.Random()) ).order_by(fn.Random())
try: try:

View File

@ -2,10 +2,10 @@ from datetime import time, timedelta, timezone, datetime, date
import os import os
from peewee import fn from peewee import fn
import logging import logging
import models
class RandomMemoryJob(): class RandomMemoryJob():
def __init__(self, models, bot, job_queue): def __init__(self, bot, job_queue):
self.models = models
self.bot = bot self.bot = bot
self.logger = logging.getLogger(self.__class__.__name__) self.logger = logging.getLogger(self.__class__.__name__)
@ -23,10 +23,10 @@ class RandomMemoryJob():
async def callback_memory(self, context): async def callback_memory(self, context):
# last_seen of memory must be older than 10 days in past or None # last_seen of memory must be older than 10 days in past or None
with self.models.db: with models.db:
possible_entries = self.models.JournalEntry.select().where( possible_entries = models.JournalEntry.select().where(
(self.models.JournalEntry.last_shown <= datetime.today().date() - timedelta(days=self.min_age)) | \ (models.JournalEntry.last_shown <= datetime.today().date() - timedelta(days=self.min_age)) | \
(self.models.JournalEntry.last_shown == None) (models.JournalEntry.last_shown == None)
).order_by(fn.Random()) ).order_by(fn.Random())
try: try:

View File

@ -23,14 +23,14 @@ def main() -> None:
models.set_db(db_path) models.set_db(db_path)
application = Application.builder().token(token).build() application = Application.builder().token(token).build()
application.add_handler(journal.JournalHandler("journal", models).handler) application.add_handler(journal.JournalHandler("journal").handler)
application.add_handler(list.ListHandler("list", models).handler) application.add_handler(list.ListHandler("list").handler)
application.add_handler(status.StatusHandler("status", models).handler) application.add_handler(status.StatusHandler("status").handler)
application.add_handler(turtle.TurtleHandler().handler) application.add_handler(turtle.TurtleHandler().handler)
application.add_handler(memory.MemoryHandler("memory", models).handler) application.add_handler(memory.MemoryHandler("memory").handler)
random_memory.RandomMemoryJob(models, application.bot, application.job_queue) random_memory.RandomMemoryJob(application.bot, application.job_queue)
chat_photo.SetChatPhotoJob(models, application.bot, application.job_queue) chat_photo.SetChatPhotoJob(application.bot, application.job_queue)
# Run the bot until the user presses Ctrl-C # Run the bot until the user presses Ctrl-C
application.run_polling() application.run_polling()