La funzione lamda in @ bot.message_handler () non funziona correttamente in telebot python
Ho provato a implementare la seguente riga di codice in script python per un bot di Telegram che costruisce usando 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 is feature is under developement')
Il codice sopra mi dà un errore di sintassi.
@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 is feature is under developement')
Questo codice risolve l'errore di sintassi, ma comunque non fa quello che voglio che faccia. Quando un utente invia "/ prova del testo", voglio identificarlo e fare alcune azioni dopo.
Sono relativamente nuovo in Python e questa è la prima volta che utilizzo le funzioni telebot e lambda. Quindi per favore aiutami ad entrare
- identificare il motivo per cui il primo codice mi ha dato un errore di sintassi.
- Come implementarlo correttamente inizia con ('/ test'). Grazie mille in anticipo.
Risposte
Poiché l'operatore ternario ha una sintassi specifica, è necessario seguirla:
<value if True> if <condition> else <value if False>
Quello che hai fatto nel primo campione è:
<value if True> if <condition>
Inoltre non devi farlo come hai fatto
True if msg.text.startswith('/test') else False
.startswith()ritorna boolda solo.
Non è chiaro cosa faccia il decoratore, ma perché non esegui semplicemente il controllo all'interno della funzione?
@bot.message_handler
def test_start(message):
if msg.startswith('/test'):
msg=bot.send_message(message.chat.id,'This is feature is under developement')