MessageHandler not able to catch commands

Question:

we would like to monitor users who send commands to the bot,
but when the bot is started,
the messagehandler is able to catch messages and report that a private chat is started, but it seems that it can’t catch any of the three pre-defined commands(which are working fine).

this is confusing.

below is the main function block.

thanks in advance.

def main() -> None:
    """Start the bot."""
    # Create the Application and pass it your bot's token.
    application = Application.builder().token("token").build()

    # Command handlers
    application.add_handler(CommandHandler('help', help_command))
    application.add_handler(CommandHandler('start', start))
    application.add_handler(CommandHandler('show_chats', show_chats))

    # Handle members joining/leaving chats.
    application.add_handler(ChatMemberHandler(greet_chat_members, ChatMemberHandler.CHAT_MEMBER))

    # Keep track of which chats the bot is in
    application.add_handler(ChatMemberHandler(track_chats, ChatMemberHandler.MY_CHAT_MEMBER))

    # Interpret any other command or text message as a start of a private chat.
    # This will record the user as being in a private chat with bot.
    application.add_handler(MessageHandler(filters.ALL, start_private_chat))

    # Run the bot until the user presses Ctrl-C
    # We pass 'allowed_updates' handle *all* updates including `chat_member` updates
    # To reset this, simply pass `allowed_updates=[]`
    application.run_polling(allowed_updates=Update.ALL_TYPES)

and if i put the command handlers behind the messagehandler, they simply no longer work.

Asked By: Arthur Zhang

||

Answers:

If you want to process all messages, including the three commands ‘start’, ‘help’, and ‘show_chats’, and pass them to the start_private_chat function, you can update your main function as follows:

First, remove the lines where you add the CommandHandler instances for those three commands:

# application.add_handler(CommandHandler('help', help_command))
# application.add_handler(CommandHandler('start', start))
# application.add_handler(CommandHandler('show_chats', show_chats))

Then, modify the start_private_chat function to handle those three commands, along with any other message:

def start_private_chat(update: Update, context: CallbackContext) -> None:
    message = update.message.text
    if message.startswith('/start'):
        start(update, context)
    elif message.startswith('/help'):
        help_command(update, context)
    elif message.startswith('/show_chats'):
        show_chats(update, context)
    else:
        # Process any other message here
        pass

Finally, change the MessageHandler line in your main function to handle all messages:

# Pass all messages, including texts and commands, to the start_private_chat function
application.add_handler(MessageHandler(Filters.all, start_private_chat))

it would be helpful if you provide more code

Answered By: Obaskly