skip to Main Content

I tried to implement the following line of code in python script for a telegram bot building using telebot.

@bot.message_handler(func=lambda msg:True if msg.text.startswith('/test'))
def test_start(message):
    msg=bot.send_message(message.chat.id,'This feature is under developement')

Above code gives me a syntax error.

@bot.message_handler(func=lambda msg:True if msg.text.startswith('/test') else False)
def test_start(message):
    msg=bot.send_message(message.chat.id,'This feature is under developement')

This code solves the syntax error, but still, it doesn’t do what I want it to do. When a user sends ‘/test some text’ I want to identify this and do some actions after that.

I am relatively new to python and this is my first time using telebot and lambda functions. So please help me in

  1. identifying why the 1st code gave me a syntax error.
  2. How to implement this startswith(‘/test’) properly.
    Thank you so much in advance.

2

Answers


  1. Because ternary operator has a specific syntax, that has to be followed:

    <value if True> if <condition> else <value if False>
    

    What you did in the first sample is:

    <value if True> if <condition>
    

    Also you don’t have to do it like you did

    True if msg.text.startswith('/test') else False
    

    .startswith() returns bool on its own.

    It’s unclear what decorator does, but why don’t you just perform the check inside of the function?

    @bot.message_handler
    def test_start(message):
        if msg.startswith('/test'):
            msg=bot.send_message(message.chat.id,'This is feature is under developement')
    
    Login or Signup to reply.
  2. I think you are looking for something like that:

    @bot.message_handler(func=lambda msg: True == msg.text.startswith("/test"))
    def starts_with_test(message):
        args = message.text.split(' ');
        for arg in args:
            bot.send_message(message.chat.id, "arg = " + arg)
    

    It will handle only commands that started with "/test". Then you can use split(‘ ‘) to parce arguments. For some types of fields there can be limitaions. For example for "InlineKeyboardButton"->"callback_data" field. It can be <= 64 bytes. Another handlers will work as intended.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search