xmpp: Fix issues with reconnecting

This commit is contained in:
Alexei Sorokin 2017-06-03 22:12:30 +03:00
parent 60dfc17c67
commit b702c1af45

View File

@ -5,13 +5,13 @@ import re
import signal
import sys
import time
from threading import Thread
from irc.bot import SingleServerIRCBot
import sleekxmpp
if sys.version_info.major >= 3:
from configparser import SafeConfigParser
else:
from ConfigParser import SafeConfigParser
from threading import Thread
from irc.bot import SingleServerIRCBot
class IRCBot:
@ -122,17 +122,23 @@ class XMPPBot:
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('groupchat_message', self.on_message)
self.client.add_event_handler('muc::%s::presence' % self.muc,
self.on_presence)
def connect(self):
if not self.client.connect():
# sys.stderr.write('could not connect!\n')
sys.stderr.write('Could not connect to server, or password ' +
'mismatch!\n')
sys.exit(1)
# sys.stderr.write('connected with %s\n'%con)
def join_muc(self):
muc_plugin = self.client.plugin['xep_0045']
if self.muc in muc_plugin.getJoinedRooms():
muc_plugin.leaveMUC(self.muc, self.nick,
msg='Replaced by new connection')
muc_plugin.joinMUC(self.muc, self.nick, wait=True)
muc_plugin.joinMUC(self.muc, self.nick)
def on_session_start(self, event):
print('Connected to XMPP')
@ -140,6 +146,10 @@ class XMPPBot:
self.client.send_presence()
self.join_muc()
def on_session_end(self, event):
time.sleep(2.0)
self.connect()
def on_message(self, event):
body = event['body']
nick = event['mucnick']
@ -192,15 +202,9 @@ class XMPPBot:
def start(self):
self.client.register_plugin('xep_0045') # XMPP MUC.
self.client.register_plugin('xep_0199') # XMPP Ping.
if self.client.connect():
# sys.stderr.write('connected with %s\n'%con)
self.register_handlers()
self.client.process(block=True)
else:
# sys.stderr.write('could not connect!\n')
sys.stderr.write('Could not connect to server, or password ' +
'mismatch!\n')
sys.exit(1)
self.register_handlers()
self.connect()
self.client.process(block=True)
class Intermedia:
@ -320,8 +324,7 @@ if __name__ == '__main__':
config.read('config.ini')
if not config.sections():
sys.stderr.write('Error: Configuration file does not exist ' +
'or is empty.\n')
sys.stderr.write('Error: Configuration file does not exist or is empty.\n')
sys.exit(1)
shared_opts['prefix'] = config.get('Shared', 'prefix')