如何在Python Telegram程序中实现Inline Keyboard导航及交互逻辑?
Got it, let's walk through building this inline keyboard flow step by step. I'll use the python-telegram-bot library (version 13.x or later—callback handlers work smoothly here) to make this work as you described.
First, Setup the Basic Bot Structure
First, install the library if you haven't already:
pip install python-telegram-bot==13.7
Then, start with the core bot setup, including your main menu (I'll include a quick example of the custom keyboard you mentioned):
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters, CallbackContext # Your main menu custom keyboard def get_main_menu(): keyboard = [['Feedback']] return ReplyKeyboardMarkup(keyboard, resize_keyboard=True) # Start command to load the main menu def start(update: Update, context: CallbackContext): update.message.reply_text("Welcome to the main menu!", reply_markup=get_main_menu())
Handle the Feedback Button Click
Next, we need a handler that triggers when the user taps the "Feedback" button in the main menu. This will send the first inline keyboard with your question:
def handle_feedback_trigger(update: Update, context: CallbackContext): # Build the first inline keyboard inline_keyboard = [ [InlineKeyboardButton("No", callback_data='feedback_no')], [InlineKeyboardButton("Yes", callback_data='feedback_yes')], [InlineKeyboardButton("Leave Comments", callback_data='feedback_comments')] ] reply_markup = InlineKeyboardMarkup(inline_keyboard) # Send the question with the inline keyboard attached update.message.reply_text("Message: Do you find this app useful?", reply_markup=reply_markup)
Handle Inline Button Callback Queries
Now, we need to catch the user's selections from the inline keyboard. We'll use a CallbackQueryHandler to process each button press:
def handle_feedback_actions(update: Update, context: CallbackContext): query = update.callback_query query.answer() # Always acknowledge the callback to avoid loading spinners for the user if query.data == 'feedback_no': # Send the thank-you message and return to main menu query.edit_message_text("Thank you and we hope you can leave some comments how to improve the app") query.message.reply_text("Back to main menu:", reply_markup=get_main_menu()) elif query.data == 'feedback_yes': # Show the second inline keyboard (I filled in your partial prompt) vote_keyboard = [ [InlineKeyboardButton("⭐ 1 Star", callback_data='vote_1')], [InlineKeyboardButton("⭐⭐ 2 Stars", callback_data='vote_2')], [InlineKeyboardButton("⭐⭐⭐ 3 Stars", callback_data='vote_3')], [InlineKeyboardButton("⭐⭐⭐⭐ 4 Stars", callback_data='vote_4')], [InlineKeyboardButton("⭐⭐⭐⭐⭐ 5 Stars", callback_data='vote_5')] ] reply_markup = InlineKeyboardMarkup(vote_keyboard) query.edit_message_text("Please vote for our app:", reply_markup=reply_markup) elif query.data == 'feedback_comments': # Prompt user to enter their comments query.edit_message_text("Please type your comments below:") # Track that we're waiting for a comment using user data context.user_data['awaiting_comment'] = True # Optional: Capture and handle the user's comment def handle_comment_input(update: Update, context: CallbackContext): if context.user_data.get('awaiting_comment'): comment = update.message.text # Here you can save the comment to a database, log it, etc. update.message.reply_text("Thank you for your valuable feedback!", reply_markup=get_main_menu()) context.user_data['awaiting_comment'] = False
Wire Up All Handlers and Launch the Bot
Finally, register all handlers and start the bot:
def main(): # Replace with your bot token from @BotFather updater = Updater("YOUR_BOT_TOKEN_HERE") dp = updater.dispatcher # Register all handlers dp.add_handler(CommandHandler("start", start)) dp.add_handler(MessageHandler(Filters.regex('^Feedback$'), handle_feedback_trigger)) dp.add_handler(CallbackQueryHandler(handle_feedback_actions)) dp.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_comment_input)) # Start the bot updater.start_polling() updater.idle() if __name__ == '__main__': main()
Quick Tips
- Always call
query.answer()when handling callbacks—it’s required to let Telegram know the button press was processed. - Using
edit_message_textreplaces the existing message instead of sending a new one, keeping the chat thread clean. - The
context.user_datadict is a simple way to track conversation state (like waiting for a comment) between interactions.
You can extend the vote handling by adding more callback cases for the star buttons, following the same pattern as the initial feedback options.
内容的提问来源于stack exchange,提问作者David Tang




