代码之家  ›  专栏  ›  技术社区  ›  sliwka

在pyTelegramBotAPI中,如果不停止整个过程,就无法停止机器人

  •  1
  • sliwka  · 技术社区  · 2 年前

    我已经为此挠头6个小时了。我试图在不停止整个过程的情况下停止我的机器人。bot轮询停止的条件应该是变量ID与get_active_session()函数返回的变量ID不同。当get_active_sesion()返回与ID相同的值时,bot应该再次开始轮询

    我试了太多的片段,都记不清了。在大多数情况下,即使ID与get_active_session()返回的ID不同,机器人也不会停止

    以下是其中一个:

    def start_polling():
        while get_active_session() != ID:
            try:
                bot.polling(none_stop=True)
            except Exception as e:
                print(f"Polling error: {e}")
                time.sleep(2)
    
    
    def stop_polling():
        bot.stop_polling()
    
    print(f"\n\n{get_active_session()}")
    
    while True:
        if get_active_session() == ID:
            stop_polling()
        else:
            start_polling()
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Tim Roberts    2 年前

    这就是我的意思。注意,我假设 bot.polling 启动后台活动,并且您不必一直在循环中调用它。如果你必须自己做主循环,那么它需要有所不同。

    polling = False
    
    def start_polling():
        global polling
        if not polling:
            bot.polling(none_stop=True)
        polling = True
    
    def stop_polling():
        global polling
        if polling:
            bot.stop_polling()
        polling = False
    
    print(f"\n\n{get_active_session()}")
    
    while True:
        if get_active_session() == ID:
            stop_polling()
        else:
            start_polling()
        time.sleep(1)
    

    或者,使用类跳过全局:

    class Poller:
        def __init__(self, bot):
            self.polling = False
            self.bot = bot
    
        def start_polling(self):
            if not self.polling:
                self.bot.polling(none_stop=True)
            self.polling = True
    
        def stop_polling(self:):
            if self.polling:
                self.bot.stop_polling()
            self.polling = False
    
        def mainloop(self):
            while True:
                if get_active_session() == ID:
                    self.stop_polling()
                else:
                    self.start_polling()
                time.sleep(1)
    
    poll = Poller(bot)
    poll.mainloop()
    
    推荐文章