我正在构建一个应该处理按钮和消息的机器人,这是一个有效的示例:
INTRO, GUEST_OR_USER, USERNAME, GUEST = range(4)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
keyboard = [
[InlineKeyboardButton("YES SIR!", callback_data='user')],
[InlineKeyboardButton("no", callback_data='guest')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("Are you a Stack Overflow user?", reply_markup=reply_markup)
return GUEST_OR_USER
async def guest_or_user_choice(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
query = update.callback_query
await query.answer()
if query.data == 'user':
await context.bot.send_message(chat_id=update.effective_chat.id,
text="Cool! What's your username?")
return USERNAME
await context.bot.send_message(chat_id=update.effective_chat.id,
text="Oh! Why not?")
return GUEST
async def username_entered(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("👍")
return
async def guest_conv(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("That's a shame!")
return
if __name__ == '__main__':
application = ApplicationBuilder().token(TOKEN).build()
start_handler = CommandHandler('start', start)
application.add_handler(start_handler)
conv_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(guest_or_user_choice)],
states={
USERNAME: [MessageHandler(filters.TEXT & ~filters.COMMAND, username_entered)],
GUEST: [MessageHandler(filters.TEXT & ~filters.COMMAND, guest_conv)]
},
fallbacks=[],
allow_reentry=True
)
application.add_handler(conv_handler)
application.run_polling()
但即使是这样一个简单的流程也会显示像
这样的警告PTBUserWarning:如果“per_message=False”,“CallbackQueryHandler”将 不跟踪每条消息
根据那些,ConversationHandler 应该是这样的:
conv_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(guest_or_user_choice)],
states={
USERNAME: [CallbackQueryHandler(username_entered)],
GUEST: [CallbackQueryHandler(guest_conv)]
},
fallbacks=[],
allow_reentry=True,
per_message=True
)
但这行不通,username_entered | guest_conv 从未启动。有没有办法让它在没有警告的情况下工作?如何使用 CallbackQueryHandler 处理用户文本输入?非常感谢!