Search code examples
pythonfunctiontelegram-api

How to stop a function from another function?


TOKEN = 'token'
bot = telebot.TeleBot(TOKEN)

def main():
   for i in range(0,100):
      print(i)

@bot.message_handler(commands=['start'])
def start(message):
  main()

@bot.message_handler(commands=['stop'])
def stopfunc(message):
   #how to stop the function main() ?

while True:
   bot.polling()

Solution

  • Add stop flag :

    • Add logic to main function : when stop flag is True, the main function should return
    • In stopfunc set the stop flag is True
    stop = False
    def main():
       global stop
       for i in range(0,100):
           if stop:
              break
           print(i)
        
    @bot.message_handler(commands=['stop'])
    def stopfunc(message):
        global stop
        stop = True       
    
    ...