improved journal date selection

This commit is contained in:
Remy Moll 2023-10-12 23:03:18 +02:00
parent c58e256194
commit df55dbf6c7

View File

@ -2,7 +2,12 @@ import datetime
import os 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
ACTION_CHOICE, DATE_ENTRY, ADD_CONTENT = range(3) from telegram.constants import ParseMode
ENTRY_OPTIONS, CONTENT_ENTRY = range(2)
BUTTON_COUNT = 5
from .basehandler import BaseHandler from .basehandler import BaseHandler
@ -13,17 +18,15 @@ class JournalHandler(BaseHandler):
self.handler = ConversationHandler( self.handler = ConversationHandler(
entry_points=[CommandHandler(entry_string, self.entry_point)], entry_points=[CommandHandler(entry_string, self.entry_point)],
states={ states={
ACTION_CHOICE: [ ENTRY_OPTIONS: [
CallbackQueryHandler(self.date_choice, pattern="today|yesterday"), CallbackQueryHandler(self.date_button, pattern=r"^\d{8}$"), # a serialized date
CallbackQueryHandler(self.date_custom, pattern="custom"), CallbackQueryHandler(self.date_custom, pattern=r"^\d{1,3}$"), # a ~ small delta
CallbackQueryHandler(self.option_delete, pattern="delete") CallbackQueryHandler(self.option_delete, pattern="delete"),
],
DATE_ENTRY: [
MessageHandler(filters.ALL, self.date_entry), MessageHandler(filters.ALL, self.date_entry),
], ],
ADD_CONTENT: [ CONTENT_ENTRY: [
MessageHandler(filters.ALL, self.content_save), MessageHandler(filters.ALL, self.content_save),
] ],
}, },
fallbacks=[], fallbacks=[],
) )
@ -37,30 +40,31 @@ class JournalHandler(BaseHandler):
await update.message.reply_text("You are not authorized to use this bot") await update.message.reply_text("You are not authorized to use this bot")
return ConversationHandler.END return ConversationHandler.END
dates = [(datetime.datetime.now() - datetime.timedelta(days = i)).date() for i in range(BUTTON_COUNT)][::-1]
names = [d.strftime("%d.%m.") for d in dates]
callbacks = [d.strftime("%d%m%Y") for d in dates]
names[-1] = "Today"
names[-2] = "Yesterday"
options = [[ options = [
InlineKeyboardButton("Today", callback_data="today"), [
InlineKeyboardButton("Yesterday", callback_data="yesterday"), InlineKeyboardButton("<<", callback_data=BUTTON_COUNT)
InlineKeyboardButton("Custom date", callback_data="custom"), ] + [
InlineKeyboardButton(n, callback_data=c) for n,c in zip(names, callbacks)
], ],
[ [
InlineKeyboardButton("Delete", callback_data="delete") InlineKeyboardButton("Delete", callback_data="delete")
] ]
] ]
keyboard = InlineKeyboardMarkup(options) keyboard = InlineKeyboardMarkup(options)
await update.message.reply_text("Please choose an option for the entry:", reply_markup=keyboard) await update.message.reply_text("Please choose a date \(or type it in the format _DDMMYYYY_\)", reply_markup=keyboard, parse_mode=ParseMode.MARKDOWN_V2)
return ACTION_CHOICE return ENTRY_OPTIONS
async def date_choice(self, update, context): async def date_button(self, update, context):
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
if query.data == "today": date = datetime.datetime.strptime(query.data, "%d%m%Y").date()
date = datetime.datetime.now().date()
elif query.data == "yesterday":
date = datetime.datetime.now().date() - datetime.timedelta(days=1)
else:
raise ValueError("Invalid date choice")
with self.models.db: with self.models.db:
self.current_model, new = self.models.JournalEntry.get_or_create( self.current_model, new = self.models.JournalEntry.get_or_create(
@ -75,15 +79,34 @@ class JournalHandler(BaseHandler):
await query.edit_message_text(text="An entry already exists for this date") await query.edit_message_text(text="An entry already exists for this date")
return ConversationHandler.END return ConversationHandler.END
return ADD_CONTENT return CONTENT_ENTRY
async def date_custom(self, update, context): async def date_custom(self, update, context):
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
await query.edit_message_text(text="Please enter the date in the format DDMMYYYY") delta = int(query.data)
return DATE_ENTRY
dates = [(datetime.datetime.now() - datetime.timedelta(days = i + delta)).date() for i in range(BUTTON_COUNT - 1)][::-1]
names = [d.strftime("%d.%m.") for d in dates]
callbacks = [d.strftime("%d%m%Y") for d in dates]
options = [
[
InlineKeyboardButton("<<", callback_data=delta + (BUTTON_COUNT - 1))
] + [
InlineKeyboardButton(n, callback_data=c) for n,c in zip(names, callbacks)
] + [
InlineKeyboardButton(">>", callback_data=delta - (BUTTON_COUNT - 1))
],
[
InlineKeyboardButton("Delete", callback_data="delete")
]
]
keyboard = InlineKeyboardMarkup(options)
await query.edit_message_text("Please choose a date \(or type it in the format _DDMMYYYY_\)", parse_mode=ParseMode.MARKDOWN_V2)
return ENTRY_OPTIONS
async def date_entry(self, update, context): async def date_entry(self, update, context):
date = update.message.text date = update.message.text
@ -91,8 +114,8 @@ class JournalHandler(BaseHandler):
try: try:
date = datetime.datetime.strptime(date, "%d%m%Y").date() date = datetime.datetime.strptime(date, "%d%m%Y").date()
except ValueError: except ValueError:
await update.message.reply_text("Please enter the date in the format DDMMYYYY") await update.message.reply_text("Please enter the date in the format _DDMMYYYY_", parse_mode=ParseMode.MARKDOWN_V2)
return DATE_ENTRY 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 self.models.db:
@ -118,7 +141,7 @@ class JournalHandler(BaseHandler):
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}?"
) )
return ADD_CONTENT return CONTENT_ENTRY
async def content_save(self, update, context): async def content_save(self, update, context):
@ -148,9 +171,9 @@ class JournalHandler(BaseHandler):
async def option_delete(self, update, context): async def option_delete(self, update, context):
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
await query.edit_message_text(text="Please enter the date in the format DDMMYYYY") await query.edit_message_text(text="Please enter the date in the format _DDMMYYYY_", parse_mode=ParseMode.MARKDOWN_V2)
context.chat_data["delete"] = True context.chat_data["delete"] = True
return DATE_ENTRY return ENTRY_OPTIONS
async def delete_entry(self, update, context): async def delete_entry(self, update, context):