【问题标题】:lamda funtion in @bot.message_handler() not working properly in telebot python@bot.message_handler() 中的 lambda 函数在 Telebot python 中无法正常工作
【发布时间】:2020-09-18 07:59:04
【问题描述】:

我尝试在 python 脚本中实现以下代码行,以便使用 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')

上面的代码给了我一个语法错误。

@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')

这段代码解决了语法错误,但它仍然没有达到我想要的效果。当用户发送“/test some text”时,我想识别它并在此之后执行一些操作。

我对 python 比较陌生,这是我第一次使用 Telebot 和 lambda 函数。所以请帮助我

  1. 找出为什么第一个代码给了我一个语法错误。
  2. 如何正确地实现这个startswith('/test')。 非常感谢您。

【问题讨论】:

    标签: python if-statement lambda telegram telegram-bot


    【解决方案1】:

    因为三元运算符有特定的语法,所以必须遵守:

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

    您在第一个示例中所做的是:

    <value if True> if <condition>
    

    你也不必像以前那样做

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

    .startswith() 会自行返回 bool

    尚不清楚装饰器的作用,但为什么不直接在函数内部执行检查呢?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 2012-02-04
      • 2013-10-09
      • 1970-01-01
      • 2012-03-31
      相关资源
      最近更新 更多