如何使用 python-telegram-bot 制作嵌套菜单

问题描述 投票:0回答:0

我需要为电报机器人编写一个嵌套菜单。我正在使用 python-telegram-bot,目前有以下代码。在命令 /caregories 上,bot 使用方法 caregory_service.get_parent_categories() 从数据库接收父类别列表,并将它们显示为菜单按钮。我想向机器人添加以下功能:当您单击每个类别按钮时,将打开一个子菜单,其中包含子类别列表和返回按钮以返回父类别列表。您可以使用方法 caregory_service.get_subcategories() 获取子类别列表。当您单击任何子类别时,它会被添加到所选子类别的列表中,并在按主菜单中的“确定”按钮后返回此列表。我怎样才能用 python-telegram-bot 实现这个?

from telegram.ext import AIORateLimiter, Application, CommandHandler, ContextTypes
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from services import CategoryService

TOKEN = 'TOKEN'

async def categories_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = []
    category_service = CategoryService()
    categories = await category_service.get_parent_categories() # get all parent categories from database

    categories_buttons = [[InlineKeyboardButton(category.name, callback_data=str(category.id))] for category in categories]
    keyboard.extend(categories_buttons)

    keyboard.extend([
        [InlineKeyboardButton(
            "Cancel",
            callback_data="cancel"
        )],
        [InlineKeyboardButton(
            "Ok",
            callback_data="confirm"
        )]])

    reply_markup = InlineKeyboardMarkup(keyboard)

    await update.message.reply_text(
        "Some text",
        reply_markup=reply_markup
    )


def create_bot() -> Application:
    bot = Application.builder().token(TOKEN).rate_limiter(AIORateLimiter()).build()
    bot.add_handler(CommandHandler("categories", categories_callback))
    return bot


async def start_bot() -> Application:
    bot = create_bot()
    await bot.initialize()
    await bot.updater.start_polling()
    await bot.start()
    return bot

bot = start_bot()
python bots telegram-bot python-telegram-bot
© www.soinside.com 2019 - 2024. All rights reserved.