I'm kindly asking to help me find right architecture, and/or advice regarding right conv_handler to handle user route from start to sending message.
I'm trying to send in my (single user) telegram bot some reminders, divided in categories.
For example, I want to enter Telegram chat, press "Home tasks" from lined buttons, then buttons should update regarding all home subcategories, eg. "Reapir", "Shopping". And after pressing "Repair" bot should ask type text. I'll type "Fix chair". And bot should send it to function sendToDB (in my case just print): "Home tasks", "Reapir", "Fix chair".
In the example case below: "Category 2", "Subcategory 2", "Test text"
I havent found similar functional example in lib docs.
And, the second (but smaller problem) - how to awoid infinum pressing /start button for each reminder? May be there's way to start new first layer buttons after complete prewious handle?
There's the code (not working), partly taken from example, partly GPTed, partly edited by myself:
"""Simple inline keyboard bot with multiple CallbackQueryHandlers.
This Bot uses the Application class to handle the bot.
First, a few callback functions are defined as callback query handler. Then, those functions are
passed to the Application and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Example of a bot that uses inline keyboard that has multiple CallbackQueryHandlers arranged in a
ConversationHandler.
Send /start to initiate the conversation.
Press Ctrl-C on the command line to stop the bot.
"""
import logging
from src import settings
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (
Application,
CallbackQueryHandler,
CommandHandler,
ContextTypes,
ConversationHandler,
MessageHandler,
filters,
)
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# set higher logging level for httpx to avoid all GET and POST requests being logged
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)
# States for the conversation handler
FIRST, SECOND, THIRD = range(3)
# Callback data for the first layer buttons
ONE, TWO, THREE, FOUR = range(4)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Send message on `/start`."""
# Get user that sent /start and log his name
user = update.message.from_user
logger.info("User %s started the conversation.", user.first_name)
# Send message with text and appended InlineKeyboard
await update.message.reply_text("Welcome! Please choose a category:", reply_markup=get_first_layer_keyboard())
# Tell ConversationHandler that we're in state `FIRST` now
return FIRST
def get_first_layer_keyboard():
"""Create and return the first layer keyboard."""
#Create custom keyboard with buttons (e.g., "Category 1", "Category 2", etc.)
buttons = [
[InlineKeyboardButton("Category 1", callback_data=str(ONE))],
[InlineKeyboardButton("Category 2", callback_data=str(TWO))]
]
return InlineKeyboardMarkup(buttons)
def get_second_layer_keyboard():
"""Create and return the first layer keyboard."""
#Create custom keyboard with buttons (e.g., "SubCategory 1", "SubCategory 2", etc.)
buttons = [
[InlineKeyboardButton("SubCategory 1", callback_data=str(ONE))],
[InlineKeyboardButton("SubCategory 2", callback_data=str(TWO))]
]
return InlineKeyboardMarkup(buttons)
async def first_layer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Handle the first layer button press."""
query = update.callback_query
query.answer()
await query.edit_message_text("You selected Category 1. Now choose a subcategory:")
return SECOND
async def second_layer(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Handle the second layer button press."""
query = update.callback_query
query.answer()
await query.edit_message_text("You selected Subcategory 1. Please enter some text:")
return THIRD
async def handle_text_input(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Handle the user's text input."""
user_text = update.message.text
# Process the user's input (e.g., call your function with category, subcategory, and user_text)
# Example:
# process_user_input(context.user_data["category"], context.user_data["subcategory"], user_text)
await update.message.reply_text(f"Received: {user_text}. Processing...")
# End the conversation
return ConversationHandler.END
async def cancel(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Cancel the conversation."""
await update.message.reply_text("Conversation canceled.")
return ConversationHandler.END
def main() -> None:
"""Run the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token(settings.API_TOKEN).build()
# Setup conversation handler with the states FIRST and SECOND
# Use the pattern parameter to pass CallbackQueries with specific
# data pattern to the corresponding handlers.
# ^ means "start of line/string"
# $ means "end of line/string"
# So ^ABC$ will only allow 'ABC'
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", start)],
states={
FIRST: [CallbackQueryHandler(first_layer, pattern="^" + str(ONE) + "$")],
SECOND: [CallbackQueryHandler(second_layer, pattern="^" + str(TWO) + "$")],
THIRD: [MessageHandler(filters.TEXT & ~filters.COMMAND, handle_text_input)],
},
fallbacks=[CommandHandler("start", start)],
)
# Add ConversationHandler to application that will be used for handling updates
application.add_handler(conv_handler)
# Run the bot until the user presses Ctrl-C
application.run_polling(allowed_updates=Update.ALL_TYPES)
if __name__ == "__main__":
main() ```