Vasile
Vasile

Reputation: 841

Run multiple chatbots in telegram [python]

What I want to achieve: I have a table of chatbot tokens that is updated regularly. My goal is to: 1)Check if a chatbot token is already running on a thread

2)If the token is not running: start a thread

3)If one of the threads is dead for some reason- create a new one with the same token

My problem: I always get "Error while getting Updates: Conflict: terminated by other getUpdates request;"

I understand that my solution is not suited for running multiple instances of the bots, but I didn't find any other solution for this.

# my_threads = {
#     'token1': threading.Thread( name='token1'),
#     'token2': threading.Thread( name='token2')
# }
my_threads = {}

while True:
    for doc in db["admin_chats"].find():  # loop over tokens 
        if doc["token"] not in my_threads.keys():
            new_thread = threading.Thread(target=bot_runner.run, args=(doc,), name=doc["token"])
            my_threads[doc["token"]] = new_thread
            new_thread.daemon = True
            new_thread.start()

            print "created thread " + doc["token"]
    for key, thread in my_threads.iteritems():
        if not thread.is_alive():
            doc = dict()
            doc["token"] = key
            new_thread = threading.Thread(target=bot_runner.run, args=(doc,), name=doc["token"])
            new_thread.start()
            my_threads[doc["token"]] = new_thread
            print "restarted thread " + doc["token"]
            time.sleep(2)
    time.sleep(5)

Upvotes: 0

Views: 2138

Answers (1)

Ali Hashemi
Ali Hashemi

Reputation: 3368

I think the problem does NOT underlay in this piece of code, but in bot_runner.run. The error: Error while getting Updates: Conflict: terminated by other getUpdates request; happens when your session has not been terminated correctly (see this). What you have to do is to make sure you terminate the sessions before your threads drop dead! In other words: FIX THE bot_runner.run function.

Upvotes: 1

Related Questions