首页 > 解决方案 > 在电报中运行多个聊天机器人 [python]

问题描述

我想要实现的目标:我有一张定期更新的聊天机器人令牌表。我的目标是:1)检查聊天机器人令牌是否已经在线程上运行

2)如果令牌没有运行:启动一个线程

3)如果其中一个线程由于某种原因死了 - 创建一个具有相同标记的新线程

我的问题:我总是收到“获取更新时出错:冲突:被其他 getUpdates 请求终止;”

我知道我的解决方案不适合运行机器人的多个实例,但我没有找到任何其他解决方案。

# 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)

标签: pythonmultithreadingresttelegrampython-telegram-bot

解决方案


我认为问题不在这段代码中,而是在bot_runner.run. 错误:Error while getting Updates: Conflict: terminated by other getUpdates request;当您的会话未正确终止时发生(请参阅this)。你要做的是确保在你的线程死掉之前终止会话!换句话说:修复bot_runner.run功能。


推荐阅读