# -*- coding: utf-8 -*-
import sys
from twisted.python import log
from twisted.words.protocols import jabber
from twisted.internet.error import ConnectionLost
from wokkel.client import XMPPClient
from wokkel.ping import PingClientProtocol
from twisted.internet.task import LoopingCall
JID = unicode('YOUR@JABBER.ID')
PASSWORD = 'PASSWORD'
INTERVAL = 3
class SpecialPingClientProtocol(PingClientProtocol):
def __init__(self, entity, interval):
self.__entity = jabber.jid.internJID(entity)
self.__interval = interval
self.__pingLoop = None
def _onError(self, failure):
log.msg('Failure %s at %s' % (failure, self.__class__.__name__))
error = failure.trap(jabber.error.StanzaError, ConnectionLost)
if error == jabber.error.StanzaError:
if failure.value.condition == 'feature-not-implemented':
return None
elif error == ConnectionLost:
# Do some beautiful things
log.msg('Connection is lost. I want to reconnect NOW')
return failure
def _sendPing(self):
defer = self.ping(self.__entity)
defer.addErrback(self._onError)
def stopPing(self):
log.msg('Ping to %s stopped at %s' % (self.__entity, self.__class__.__name__))
if self.__pingLoop is not None and self.__pingLoop.running:
self.__pingLoop.stop()
self.__pingLoop = None
def startPing(self):
log.msg('Ping to %s started at %s ' % (self.__entity, self.__class__.__name__))
self.__pingLoop = LoopingCall(self._sendPing)
self.__pingLoop.start(self.__interval, now = False)
def main():
log.startLogging(sys.stdout)
transport = XMPPClient(jabber.jid.internJID(JID), PASSWORD)
transport.logTraffic = True
pinger = SpecialPingClientProtocol(JID, INTERVAL)
pinger.setHandlerParent(transport)
transport.startService()
pinger.startPing()
reactor.run()
if __name__ == '__main__':
from twisted.internet import reactor
main()