From ee5fa7e9e22c21c47b21719b3878bc21d23ae36c Mon Sep 17 00:00:00 2001 From: Alexei Sorokin Date: Sun, 28 May 2017 22:30:49 +0300 Subject: [PATCH] Fix issues with reconnecting --- hptoad.py | 52 ++++++++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 24 deletions(-) diff --git a/hptoad.py b/hptoad.py index 704cd60..530333f 100755 --- a/hptoad.py +++ b/hptoad.py @@ -37,23 +37,39 @@ class Hptoad: self.logger.setLevel(logging.DEBUG) self.jid = opts["jid"] - self.connect = opts["connect"] + self.connect_host = opts["connect"] self.muc = opts["muc"] self.pure_bot_nick = opts["nick"] self.bot_nick = self.pure_bot_nick def register_handlers(self): self.client.add_event_handler("session_start", self.on_session_start) + self.client.add_event_handler("session_end", self.on_session_end) self.client.add_event_handler("message", self.on_message, threaded=True) self.client.add_event_handler("muc::%s::presence" % self.muc, self.on_muc_presence) + def connect(self): + # Reset the nick. + self.bot_nick = self.pure_bot_nick + + if self.connect_host: + connect = self.connect_host.split(":", 1) + if len(connect) != 2 or not connect[1].isdigit(): + self.logger.critical("Conn: Connection server format is " + + "invalid, should be example.org:5222") + sys.exit(1) + else: + connect = () + + if not self.client.connect(connect): + self.logger.critical("Auth: Could not connect to server, or " + + "password mismatch!") + sys.exit(1) + def join_muc(self): - if self.muc in self.muc_obj.getJoinedRooms(): - self.muc_obj.leaveMUC(self.muc, self.bot_nick, - msg="Replaced by new connection") - self.muc_obj.joinMUC(self.muc, self.bot_nick, wait=True) + self.muc_obj.joinMUC(self.muc, self.bot_nick) def log_exception(self, ex): self.logger.error("%s: %s" % (type(ex).__name__, str(ex))) @@ -205,6 +221,10 @@ class Hptoad: ppriority=12) self.join_muc() + def on_session_end(self, event): + time.sleep(2.0) + self.connect() + def on_message(self, event): try: if not event["type"] in ("chat", "normal", "groupchat"): @@ -252,25 +272,9 @@ class Hptoad: self.log_exception(e) def run(self): - # Reset the nick. - self.bot_nick = self.pure_bot_nick - - if self.connect: - connect = self.connect.split(":", 1) - if len(connect) != 2 or not connect[1].isdigit(): - self.logger.critical("Conn: Connection server format is " + - "invalid, should be example.org:5222") - sys.exit(1) - else: - connect = () - - if self.client.connect(connect): - self.register_handlers() - self.client.process(block=True) - else: - self.logger.critical("Auth: Could not connect to server, or " + - "password mismatch!") - sys.exit(1) + self.register_handlers() + self.connect() + self.client.process(block=True) if __name__ == "__main__":