0

I want to run two threads in python using their own commands from a Telegram bot. How do I do that exactly?

I am using telegram.ext module

1 Answer 1

1

Here is a working example which is self explanatory. I wrote two command functions. each function has a thread function defined inside it. Then I created a thread object with arguments passed. finally started the threads.

import time
from telegram.ext import *
import threading

BOT_TOKEN = '***INSERT YOUR BOT ID HERE***.'


def start(update: Updater, context: CallbackContext):
    update.message.reply_text('Start command going to start the thread 1 now')

    def thread1(update: Updater, context: CallbackContext):
        while True:
            update.message.reply_text('I am from thread 1. going to sleep now.')
            time.sleep(2)

    t1 = threading.Thread(target=thread1,args=(update,context))
    t1.start()


def run(update: Updater, context: CallbackContext):
    update.message.reply_text('run command is going to start the thread 2 now')

    def thread2(update: Updater, context: CallbackContext):
        while True:
            update.message.reply_text('I am from thread 2. going to sleep now')
            time.sleep(5)

    t2 = threading.Thread(target=thread2,args=(update,context))
    t2.start()


def main() -> None:
    print('bot started..')
    updater = Updater(BOT_TOKEN)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler('start', start))
    dispatcher.add_handler(CommandHandler('run', run))
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.