How to switch to another command handler? #5147
-
|
Suppose a bot has several commands available: |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 11 replies
-
|
Concurrency in PTB might be what you're looking for Or do you mean you want to terminate command0 handling completely and never resume it? In that case no its not possible to stop update processing after it's started |
Beta Was this translation helpful? Give feedback.
-
|
The key here is to use from telegram import Update
from telegram.ext import (
Application, ConversationHandler, CommandHandler,
MessageHandler, filters, ContextTypes
)
# States
CMD0_STEP, CMD1_STEP = range(2)
async def command0_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text("Command 0 started. Send me data:")
return CMD0_STEP
async def command0_process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text(f"Command 0 processed: {update.message.text}")
return ConversationHandler.END
async def command1_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text("Command 1 started. Send me data:")
return CMD1_STEP
async def command1_process(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
await update.message.reply_text(f"Command 1 processed: {update.message.text}")
return ConversationHandler.END
conv_handler = ConversationHandler(
entry_points=[
CommandHandler("command0", command0_start),
CommandHandler("command1", command1_start),
],
states={
CMD0_STEP: [MessageHandler(filters.TEXT & ~filters.COMMAND, command0_process)],
CMD1_STEP: [MessageHandler(filters.TEXT & ~filters.COMMAND, command1_process)],
},
fallbacks=[],
allow_reentry=True, # This is the key!
)The crucial parameter is
Without This is the idiomatic PTB approach — no need to manually terminate handlers or manage concurrency. |
Beta Was this translation helpful? Give feedback.
When the two handlers are registered with separate groups, it basically allows a single update (the one with
/command0for example) to be handled multiple times; twice in this case.update with /command0->conv_hander-> no match forSTATE1-> match for fallback -> fallback is calledif there are other handlers registered with different group(s), continue, otherwise update processing ends. we continue:
update with /command0->CommandHandler-> match ->command0_handeris calledthis would just relief you from doing
await context.update_queue.put(update)i…