Search code examples
pythontelegrampy-telegram-bot-api

How to separate a command from the rest of the message in telegram bots with pyTelegramBotAPI?


For example in the following command

/set first_name, last_name

How to separate or remove /set from the rest of the message?


Solution

  • Since commands can use only latin letters, numbers and underscores, you can separate it with the tiny regular expression, like this:

        import re
        pattern = "^\/[a-zA-Z\d_]* (.*)$"
        string = "/set first_name, last_name"
        match = re.match(command_pattern , string)
        message = match.group(1)  
        # first_name, last_name
    

    Another solution:

    string = "/set first_name, last_name"
    message = " ".join(string.split(" ")[1:])
    # first_name, last_name
    

    But the limitation of the last method is that it removes double spaces from the string if they existed.