Search code examples
pythonwhile-looptelegrampython-telegram-bot

how to stop a while loop in python-telegram from client side


How can I stop a while loop inside a function which is passed as a parameter for a telegram bot CommandHandler, using a command or text from the client side?

I have this bot:

from telegram import *
from datetime import datetime
import time
from telegram.ext import *
import ast #ignore this. i'll use it later

RUN_FUNC = True
def func_starter(update: Update, context):
    update.effective_chat.send_message('Function innitiated.')
    counter = 0
    RUN_FUNC = True
    while RUN_FUNC:
        print(f'function running for {counter} seconds.')
        counter += 1
        time.sleep(1)


def func_stopper(update: Update, context):
    update.effective_chat.send_message('function stopped')
    RUN_FUNC = False


def main():
    updater = Updater('*********:***********************************', use_context=True)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("stop", func_stopper))
    dp.add_handler(CommandHandler("start", func_starter))

    updater.start_polling(0)
    updater.idle()

main()

So the bot gets the /start command from the client and it starts the func_starter function which has conditional while loop in it. But because the program never makes it past the while loop, any other command / text from the client, never gets registered by the python code therefore the loop goes on forever. I want to be able to stop the func_starter function, using a command from the client side. I even made a global variable but obviously to no avail lol. It is logical I think that the program never makes it past the while loop, so is there any way to listen for new commands while in the loop?


Solution

  • I see two options:

    1. pass run_async=True to CommandHandler("start", …), which will make func_starter run in its own thread.
    2. Instead of using a while loop inside callbacks, use JobQueue to schedule the next steps