问题描述
我对编码和python比较陌生。我正在尝试使用telebot制作电报bot。 我必须顺其自然。例如:/ start之后,我应该得到一条文本。因此,我创建了一个running_work_list,其中工作流程按顺序排列,完成后,我删除索引0元素。 “开始”是数组中的第一个元素。 因此,我尝试实现类似这样的方法,以便我可以轻松地对每个步骤进行编码,而不必考虑输入和决定。
但是尽管放入了if语句,即使条件失败,“ @ bot.message_handler()”仍在运行。
if running_work_list[0]=='start':
print('inside if')
@bot.message_handler(commands=['start','new test'])
def start(message):
print('user sent start')
bot.send_message(message.chat.id,welcome_message)
running_work_list.pop(0)
print(f'work flow deciding list {running_work_list}')
@bot.message_handler(content_types=['text','photo','poll'])
def bot_intro(message):
print('here')
print(f'user sent {message.text}')
bot.send_message(message.chat.id,BOT_INTRO_MSG)
下面是我得到的输出。用户先发送了/ start信息,然后发送了其他一些随机文本。
inside if
user sent start
work flow deciding list ['test_name','test_description','test_time','test_image','test_poll']
here
user sent fdf
即使我们将它放入if语句中,它是否也会运行'@ bot.message_handler()'?
解决方法
当消息与您已作为参数传递的过滤器相匹配(@bot.message_handler
或content_types
)时,执行commands
装饰器将标记要调用的函数。 telebot
库直接调用它们,并且在注册后不执行if
语句。
执行此操作的正确方法是反转逻辑:在程序的顶层定义消息处理程序函数,并确定在函数内的if
中应该做什么。