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
- identifying why the 1st code gave me a syntax error.
- How to implement this startswith(‘/test’) properly.
Thank you so much in advance.
2
Answers
Because ternary operator has a specific syntax, that has to be followed:
What you did in the first sample is:
Also you don’t have to do it like you did
.startswith()
returnsbool
on its own.It’s unclear what decorator does, but why don’t you just perform the check inside of the function?
I think you are looking for something like that:
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.