def __init__(self, root, parent): self.root = root self.parent = parent self.logger = logging.getLogger("xmppClient") self.config = self.root.getServiceNamed('config') self.config.set("enabled", False, "main", network="xmpp") service.MultiService.__init__(self) self.protocol = None try: self.myjid = self.config.get("jid", "", "main.xmppClient") password = self.config.get("password", "", "main.xmppClient") if not (self.myjid and password): self.logger.warn("please set main.xmppClient.jid "+\ "and main.xmppClient.password") return self.client = XMPPClient(jid.internJID(self.myjid + "/otfbot"), password) self.client.logTraffic = False self.protocol = Bot(root, self) self.messageProtocol = myMessageProtocol(self.protocol) self.messageProtocol.setHandlerParent(self.client) self.presenceClientProtocol = myPresenceClientProtocol( self.protocol) self.presenceClientProtocol.setHandlerParent(self.client) self.rosterClientProtocol = myRosterClientProtocol(self.protocol) self.rosterClientProtocol.setHandlerParent(self.client) self.protocol.messageProtocol = self.messageProtocol self.protocol.rosterClientProtocol = self.rosterClientProtocol self.protocol.presenceClientProtocol = self.presenceClientProtocol self.client.setServiceParent(self) except Exception as e: self.logger.error(e)
def makeService(self, options): """ Make services to handle push event notifications. """ # check confguration file is specified and exists if not options["config"]: raise ValueError( 'Configuration file not specified (try to check --help option)' ) cfgFileName = options["config"] if not os.path.isfile(cfgFileName): raise ValueError('Configuration file not found:', cfgFileName) # read configuration file cfg = ConfigParser() cfg.read(cfgFileName) # create Twisted application application = service.Application("gitlab-webhook-xmpp") serviceCollection = service.IServiceCollection(application) # create XMPP client client = XMPPClient(JID(cfg.get('xmpp', 'jid')), cfg.get('xmpp', 'password')) # client.logTraffic = True client.setServiceParent(application) # join to all MUC rooms nickname = cfg.get('xmpp', 'nickname') if cfg.has_option( 'xmpp', 'nickname') else DEFAULT_NICKNAME notifications = cfg.items('notifications') for room, repositoryMasks in notifications: mucHandler = MUCHandler(JID(room), nickname, repositoryMasks.split(',')) mucHandler.setHandlerParent(client) self.mucHandlers.append(mucHandler) templateLoader = None if cfg.has_option('message', 'template'): templateFullName = cfg.get('message', 'template') templatePath, self.templateName = os.path.split(templateFullName) templateLoader = FileSystemLoader(templatePath) else: self.templateName = DEFAULT_TEMPLATE_NAME templateLoader = PackageLoader('xmpp_webhook', 'templates') self.templateEnvironment = Environment(loader=templateLoader, extensions=['jinja2.ext.i18n']) self.templateEnvironment.install_null_translations( ) # use i18n to pluralize only # create web hook handler rootHttpResource = Resource() rootHttpResource.putChild('', WebHookHandler(self)) site = server.Site(rootHttpResource) httpPort = cfg.getint('http', 'port') if cfg.has_option( 'http', 'port') else DEFAULT_HTTP_PORT httpServer = internet.TCPServer(httpPort, site) httpServer.setServiceParent(serviceCollection) return serviceCollection
def __init__(self, jid, password, host=None, port=5222, logid=None): XMPPClient.__init__(self, jid, password, host=host, port=port) self.log = getLoggerAdapter( log) if logid is None else getLoggerAdapter(log, id=logid) self.factory.addBootstrap(xmlstream.STREAM_ERROR_EVENT, self._onStreamError) self._authFailureTime = None self._lastTimeAuth = None self._connectedTime = None
def run(self, application, jidstr, password, muc, server): self.xmppclient = XMPPClient(JID(jidstr), password) if CowrieConfig().getboolean('output_xmpp', 'debug', fallback=False): self.xmppclient.logTraffic = True (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, server, user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.anonymous = True self.xmppclient.startService()
def connect(self): application = service.Application("gbot") xmppclient = XMPPClient(jid.internJID(self.username), self.password) xmppclient.logTraffic = False self.protocol = GBotProtocol() self.protocol.bot = self self.protocol.setHandlerParent(xmppclient) xmppclient.setServiceParent(application) return application
def connect(self): application = service.Application('UniblabXMPP') xmppclient = XMPPClient(jid.internJID(self.xmpp_user), self.xmpp_pass) self.client=UniblabXMPPProtocol() self.client.transport = self self.client.setHandlerParent(xmppclient) xmppclient.setServiceParent(application) xmppclient.startService()
def run(self, application, jidstr, password, muc, server): self.xmppclient = XMPPClient(JID(jidstr), password) if CONFIG.has_option('output_xmpp', 'debug') and \ CONFIG.getboolean('output_xmpp', 'debug') is True: self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, server, user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.anonymous = True self.xmppclient.startService()
class StatusProxy(object): def __init__(self, username, password, host='talk.google.com'): self.client = XMPPClient(JID(username), password,host) self.presence = PresenceFetcher() self.presence.setHandlerParent(self.client) self.client.startService() def getStatuses(self, account): if isinstance(account, str): account = JID(account) return self.presence.doProbe(account)
def setupConnection(self): xmppclient = XMPPClient(self.jid, self.password, self.jabber_server) xmppclient.logTraffic = False xmppbot = XMPPCassBot(self, self.state['nickname']) xmppbot.conference_server = self.conference_server xmppbot.setHandlerParent(xmppclient) xmppclient.setServiceParent(self) self.xmppbot = xmppbot self.xmppclient = xmppclient
def _connected(self, xs): XMPPClient._connected(self, xs) self._connectedTime = None def logDataIn(buf): self.log.debug("RECV: %r", buf) def logDataOut(buf): self.log.debug("SEND: %r", buf) if self.logTraffic: self.xmlstream.rawDataInFn = logDataIn self.xmlstream.rawDataOutFn = logDataOut
def __init__(self, jidString, password, host=None, port=5222): XMPPClient.__init__(self, internJID(jidString), password, host=host, port=port) self.logTraffic = False self.messagebot = MessageBot() self.messagebot.setHandlerParent(self) self.rosterManager = RosterManager() self.rosterManager.setHandlerParent(self)
def makeService(self, options): """ Make services to handle push event notifications. """ # check confguration file is specified and exists if not options["config"]: raise ValueError('Configuration file not specified (try to check --help option)') cfgFileName = options["config"]; if not os.path.isfile(cfgFileName): raise ValueError('Configuration file not found:', cfgFileName) # read configuration file cfg = ConfigParser() cfg.read(cfgFileName) # create Twisted application application = service.Application("gitlab-webhook-xmpp") serviceCollection = service.IServiceCollection(application) # create XMPP client client = XMPPClient(JID(cfg.get('xmpp', 'jid')), cfg.get('xmpp', 'password')) # client.logTraffic = True client.setServiceParent(application) # join to all MUC rooms nickname = cfg.get('xmpp', 'nickname') if cfg.has_option('xmpp', 'nickname') else DEFAULT_NICKNAME notifications = cfg.items('notifications') for room, repositoryMasks in notifications: mucHandler = MUCHandler(JID(room), nickname, repositoryMasks.split(',')) mucHandler.setHandlerParent(client) self.mucHandlers.append(mucHandler) templateLoader = None if cfg.has_option('message', 'template'): templateFullName = cfg.get('message', 'template') templatePath, self.templateName = os.path.split(templateFullName) templateLoader = FileSystemLoader(templatePath) else: self.templateName = DEFAULT_TEMPLATE_NAME templateLoader = PackageLoader('xmpp_webhook', 'templates') self.templateEnvironment = Environment(loader=templateLoader, extensions=['jinja2.ext.i18n']) self.templateEnvironment.install_null_translations() # use i18n to pluralize only # create web hook handler rootHttpResource = Resource() rootHttpResource.putChild('', WebHookHandler(self)) site = server.Site(rootHttpResource) httpPort = cfg.getint('http', 'port') if cfg.has_option('http', 'port') else DEFAULT_HTTP_PORT httpServer = internet.TCPServer(httpPort, site) httpServer.setServiceParent(serviceCollection) return serviceCollection
def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(jid.JID(jidstr), password) if self.cfg.has_option('database_xmpp', 'debug') and self.cfg.get('database_xmpp', 'debug') in ('1', 'true', 'yes'): self.xmppclient.logTraffic = True # DEBUG HERE self.xmppclient.setServiceParent(application) (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, channels.keys(), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService()
def createService(): bot_jid = "{0}@{1}/{2}".format(cfg.connect.jabber.jid, cfg.connect.jabber.server, cfg.connect.jabber.resource) xmppclient = XMPPClient(jid.internJID(bot_jid), cfg.connect.jabber.password, cfg.connect.jabber.server) xmppclient.logTraffic = cfg.connect.jabber.log_traffic # Send some whitespace every once in a while to stay alive KeepAlive().setHandlerParent(xmppclient) # Hook chat instance into main app connection = JabberConnector() FritBot.bot.registerConnector(connection) connection.setHandlerParent(xmppclient) return xmppclient
def start_services(config): client = XMPPClient(jid.internJID(config.credentials['jid']), config.credentials['password']) application = service.Application('commitbot') bot = CommitBot(config) bot.setHandlerParent(client) site = server.Site(WebHook(config, bot)) tcp_server = reactor.listenTCP(8888, site) app.startApplication(application, None) client.startService() reactor.run()
def __init__(self, root, parent): self.root = root self.parent = parent self.logger = logging.getLogger("xmppClient") self.config = self.root.getServiceNamed('config') self.config.set("enabled", False, "main", network="xmpp") service.MultiService.__init__(self) self.protocol=None try: self.myjid=self.config.get("jid", "", "main.xmppClient") password=self.config.get("password", "", "main.xmppClient") if not (self.myjid and password): self.logger.warn("please set main.xmppClient.jid "+\ "and main.xmppClient.password") return self.client = XMPPClient(jid.internJID(self.myjid+"/otfbot"), password) self.client.logTraffic = False self.protocol=Bot(root, self) self.messageProtocol=myMessageProtocol(self.protocol) self.messageProtocol.setHandlerParent(self.client) self.presenceClientProtocol=myPresenceClientProtocol(self.protocol) self.presenceClientProtocol.setHandlerParent(self.client) self.rosterClientProtocol=myRosterClientProtocol(self.protocol) self.rosterClientProtocol.setHandlerParent(self.client) self.protocol.messageProtocol=self.messageProtocol self.protocol.rosterClientProtocol=self.rosterClientProtocol self.protocol.presenceClientProtocol=self.presenceClientProtocol self.client.setServiceParent(self) except Exception, e: self.logger.error(e)
def __init__(self): self.client = XMPPClient(JID(config.JABBER_CLIENT_USER), config.JABBER_CLIENT_PASS, config.JABBER_CLIENT_HOST) self.presenceFetcher = PresenceFetcher() self.presenceFetcher.setHandlerParent(self.client) self.tweeter = Tweeter() self.loopingCall = LoopingCall(self.makeRequest)
def createXMPPClients(self, jid, password): """ Create XMPP clients. @return: C{(xmppClient, pubsubClient)} """ xmppClient = XMPPClient(jid, password) xmppClient.startService() presence = PresenceClientProtocol() presence.setHandlerParent(xmppClient) presence.available(priority=127) pubsubClient = SuperfeedrClient(self) pubsubClient.setHandlerParent(xmppClient) return xmppClient, pubsubClient
def makeService(self, options): """ Construct a TCPServer from a factory defined in myproject. """ multi_service = MultiService() from wokkel.client import XMPPClient from twisted.words.protocols.jabber import jid import forwarder xmppclient = XMPPClient(jid.internJID(options["account"]), options["password"]) xmppclient.logTraffic = False bot = forwarder.ForwarderProtocol(options["uri"]) bot.setHandlerParent(xmppclient) multi_service.addService(xmppclient) return multi_service
def makeService(config): if IQ.timeout is None: IQ.timeout = 30 xmppService = XMPPClient(config['jid'], config['secret'], config.get('xmpp-host'), config.get('xmpp-port', 5222)) if config['verbose']: xmppService.logTraffic = True presenceHandler = PresenceHandler() presenceHandler.setHandlerParent(xmppService) pinger = Pinger(config['service']) pinger.setHandlerParent(xmppService) pinger.verbose = config['verbose'] return xmppService
def initIrcJabberRelay(application): manager = RelayManager() # Configure IRC ircfactory = IrcBotFactory(manager, cfg["ircchannel"], cfg["ircnick"], manager.sendJabber) # point = TCP4ClientEndpoint(reactor, 'irc.freenode.net', 6667) # d = point.connect(ircfactory) # d.addCallback(gotProtocol) connector = internet.TCPClient(cfg["ircserver"], cfg["ircport"], ircfactory) connector.setServiceParent(application) # Configure Jabber xmppclient = XMPPClient(jid.internJID(cfg["jabberjid"]), cfg["jabberpass"]) jabberbot = JabberBot(manager, cfg["jabberserver"], cfg["jabberchannel"], cfg["jabbernick"], manager.sendIRC) xmppclient.logTraffic = False jabberbot.setHandlerParent(xmppclient) xmppclient.setServiceParent(application) manager.setJabber(jabberbot)
class StatusBotService(service.Service): def __init__(self): self.client = XMPPClient(JID(config.JABBER_CLIENT_USER), config.JABBER_CLIENT_PASS, config.JABBER_CLIENT_HOST) self.presenceFetcher = PresenceFetcher() self.presenceFetcher.setHandlerParent(self.client) self.tweeter = Tweeter() self.loopingCall = LoopingCall(self.makeRequest) def startService(self): service.Service.startService(self) self.client.startService() self.loopingCall.start(config.REFRESH_INTERVAL_SECS) def stopService(self): service.Service.stopService(self) self.loopingCall.stop() self.client.stopService() def makeRequest(self): d = self.presenceFetcher.doProbe(config.JABBER_TARGET) d.addCallbacks(self._sendTweet, log.err) return d def _sendTweet(self, statuses): if not statuses: log.msg("No statuses received") return succeed(None) else: d = self.tweeter.tweet(statuses[0]) d.addCallback(self._receiveTweetResponse) return d def _receiveTweetResponse(self, result): code, body = result # 403 is probably a duplicate tweet if code == 200: decoded = json.loads(body) log.msg("Tweeted new status: " + decoded['text']) elif code == 403: log.msg("Duplicate tweet, ignoring") else: log.err("Error tweeting {}: {}".format(code, body))
def make_client(config): keepalive = KeepAlive() keepalive.interval = config.getint('hipchat', 'keepalive.interval') xmppclient = XMPPClient( jid.internJID(config.get('hipchat', 'jabber_id')), config.get('hipchat', 'password') ) xmppclient.logTraffic = config.getboolean('hipchat', 'logtraffic') mucbot = HipBot( config.get('hipchat', 'server'), config.get('hipchat', 'channel'), config.get('hipchat', 'botnick'), config.get('hipchat', 'stfu_minutes')) mucbot.setHandlerParent(xmppclient) keepalive.setHandlerParent(xmppclient) return xmppclient
def makeService(self, options): with open(options.config, "r") as config_file: config = json.load(config_file) root = resource.Resource() root.putChild('jsMath', static.File(config["global"]["jsmath"])) bot = service.MultiService() xmppclient = XMPPClient(JID(config["global"]["jid"]), config["global"]["password"]) xmppclient.logTraffic = options['verbose'] xmppclient.setServiceParent(bot) xmppclient.dbpool = DatabaseRunner(config["global"]["database"]) xmppclient.rooms = dict() xmlrpc_port = config["global"].get("xml-rpc-port", None) if xmlrpc_port is not None: xmlrpcinterface = XMLRPCInterface(xmppclient) rpc = internet.TCPServer(xmlrpc_port, server.Site(xmlrpcinterface)) rpc.setName('XML-RPC') rpc.setServiceParent(bot) for muc_config in config["mucs"]: room_jid = JID(muc_config["jid"]) mucbot = KITBot(room_jid, muc_config.get("password", None), config["global"]["logpath"]) mucbot.setHandlerParent(xmppclient) if "xml-rpc-id" in muc_config: xmppclient.rooms[muc_config["xml-rpc-id"]] = mucbot # Log resource portal = Portal( LogViewRealm(os.path.join(config["global"]['logpath'], room_jid.user + '.log')), [strcred.makeChecker(muc_config["log-auth"])] ) credential_factory = DigestCredentialFactory('md5', 'Hello Kitty!') auth_resource = HTTPAuthSessionWrapper(portal, [credential_factory]) root.putChild(room_jid.user, auth_resource) httpd_log_view = internet.TCPServer(config["global"]["http-port"], server.Site(root)) httpd_log_view.setServiceParent(bot) # REPL over SSH def makeREPLProtocol(): namespace = dict(bot=xmppclient) return insults.ServerProtocol(manhole.ColoredManhole, namespace) repl_realm = manhole_ssh.TerminalRealm() repl_realm.chainedProtocolFactory = makeREPLProtocol repl_checker = checkers.SSHPublicKeyDatabase() repl_portal = Portal(repl_realm, [repl_checker]) repl_factory = manhole_ssh.ConchFactory(repl_portal) repl = internet.TCPServer(config["global"]["ssh-port"], repl_factory) repl.setServiceParent(bot) return bot
def configure(self, *args, **kwargs): # user args self.nick = kwargs.get('nick') # TODO: remove, make this just the bot name... self.room_nick = kwargs.get('room_nick') if self.room_nick is None: self.room_nick = self.nick self.log_traffic = kwargs.get('log_traffic', False) #TODO: remove localhost default, fail. self.server = kwargs.get('server', 'localhost') self.port = kwargs.get('port', XMPP_DEFAULT_PORT) self.use_ssl = kwargs.get('use_ssl', True) self.keepalive_freq = kwargs.get('keepalive_freq') # defaults to None if type(self.keepalive_freq) not in (None, float): try: self.keepalive_freq = float(self.keepalive_freq) except Exception as e: self.log.error( 'invalid keepalive passed in, {0!r}: {1!r}'.format( self.keepalive_freq, e)) self.keepalive_freq = None #TODO: have this default to botname @ . self.jabber_id = kwargs.get('jabber_id', self.nick + '@' + self.server) #self.room_jabber_id = # do we need this for servers that act wonky? maybe. self.password = kwargs.get('password') self.rooms = kwargs.get('rooms') # allow users to define custom handlers? not now. #self.subprotocol_handlers = kwargs.get() # internal self.bot_jid = jid.internJID(self.jabber_id) # probably want to override client? self.client = XMPPClient(self.bot_jid, self.password, host=self.server) if self.log_traffic is True: self.client.logTraffic = True
def run(self, application, jidstr, password, muc, server): self.xmppclient = XMPPClient(JID(jidstr), password) if CONFIG.has_option('output_xmpp', 'debug') and \ CONFIG.getboolean('output_xmpp', 'debug') is True: self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol( muc, server, user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.anonymous = True self.xmppclient.startService()
def make_client(bot, config, password): keepalive = KeepAlive() keepalive.interval = 30 xmppclient = XMPPClient(jid.internJID(config.get("hipchat", "jid")), password) xmppclient.logTraffic = True team_members = [n.strip() for n in config.get("team", "members").decode("utf-8").strip().split(u",")] mucbot = HipchatBot( bot, config.get("hipchat", "room_server"), config.get("hipchat", "room_jid"), config.get("team", "room_name"), config.get("hipchat", "nickname"), config.get("hipchat", "stfu_minutes"), team_members, ) mucbot.setHandlerParent(xmppclient) keepalive.setHandlerParent(xmppclient) return xmppclient
def makeService(cls, config): """ Setup the necessary network services for the application server. """ if(conf.get('suppress-deprecation-warnings')): warnings.filterwarnings('ignore', r'.*', DeprecationWarning) master_service = service.MultiService() xmpp_client = XMPPClient(jid.internJID(conf.get('jid')), conf.get('secret')) xmpp_client.setName("xmpp-client") xmpp_client.setServiceParent(master_service) bot = xmpp.BotProtocol() bot.setHandlerParent(xmpp_client) for room in conf.get('join-rooms'): print 'creating room client for %s' % room muc_client = xmpp.MUCBotClient(*room) muc_client.setHandlerParent(xmpp_client) return master_service
def xmpp_service(self, cfg, env): host = None port = 5222 user = cfg.get("xmpp", "user") pwrd = cfg.get("xmpp", "pwrd") if (cfg.has_option("xmpp", "host")): host = cfg.get("xmpp", "host") if (cfg.has_option("xmpp", "port")): port = cfg.getint("xmpp", "port") service = XMPPClient(JID(user), pwrd, host, port) presence = xmpp.PresenceHandler() leelasrv = xmpp.XmppService(cfg) presence.setHandlerParent(service) leelasrv.setHandlerParent(service) return (service)
def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(jid.internJID(jidstr), password) if self.cfg.has_option('database_xmpp', 'debug') and \ self.cfg.get('database_xmpp', 'debug') in ('1', 'true', 'yes'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol( muc, channels.keys(), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService()
def __init__(self, myjid, mysecret): application = service.Application("Xmpp XiVO CTI") xmppclient = XMPPClient(jid.internJID(myjid), mysecret) xmppclient.setServiceParent(application) xmppclient.startService() xmppclient.logTraffic = DEBUG self.factory = xmppProtocol() self.factory.setHandlerParent(xmppclient) self.pubsub_factory = ctiPubSubClient(CONFIG["xmpp"]["jid"]) self.pubsub_factory.setHandlerParent(xmppclient)
def __init__(self, gatewayId, gatewayRegTopic, xmppServer, gatewayJID, gatewayPassword, mqttBroker): self.gatewayId = gatewayId self.gatewayRegTopic = gatewayRegTopic self.xmppServerJID = jid.JID(xmppServer) self.mqttFactory = MQTTListenerFactory(self) self.xmppClient = XMPPClient(jid.JID(gatewayJID), gatewayPassword) XMPPPublishSubscriber().setHandlerParent(self.xmppClient) self.xmppClient.parent = self self.xmppClient.logTraffic = True # TODO: Should connect outside of the service reactor.connectTCP(mqttBroker, 1883, self.mqttFactory) reactor.connectTCP(xmppServer, 5222, self.xmppClient.factory) log.msg('Starting gateway\nGateway ID: %s\nGateway registration topic: %s\nXMPP Server: %s\n' % (gatewayId, gatewayRegTopic, self.xmppServerJID))
def configure(self, *args, **kwargs): # user args self.nick = kwargs.get('nick') # TODO: remove, make this just the bot name... self.room_nick = kwargs.get('room_nick') if self.room_nick is None: self.room_nick = self.nick self.log_traffic = kwargs.get('log_traffic', False) #TODO: remove localhost default, fail. self.server = kwargs.get('server', 'localhost') self.port = kwargs.get('port', XMPP_DEFAULT_PORT) self.use_ssl = kwargs.get('use_ssl', True) self.keepalive_freq = kwargs.get('keepalive_freq') # defaults to None if type(self.keepalive_freq) not in (None, float): try: self.keepalive_freq = float(self.keepalive_freq) except Exception as e: self.log.error('invalid keepalive passed in, {0!r}: {1!r}'.format(self.keepalive_freq, e)) self.keepalive_freq = None #TODO: have this default to botname @ . self.jabber_id = kwargs.get('jabber_id', self.nick + '@' + self.server) #self.room_jabber_id = # do we need this for servers that act wonky? maybe. self.password = kwargs.get('password') self.rooms = kwargs.get('rooms') # allow users to define custom handlers? not now. #self.subprotocol_handlers = kwargs.get() # internal self.bot_jid = jid.internJID(self.jabber_id) # probably want to override client? self.client = XMPPClient(self.bot_jid, self.password, host=self.server) if self.log_traffic is True: self.client.logTraffic = True
class Output(cowrie.core.output.Output): def __init__(self): cowrie.core.output.Output.__init__(self) def start(self): from random import choice import string server = CONFIG.get('output_xmpp', 'server') user = CONFIG.get('output_xmpp', 'user') password = CONFIG.get('output_xmpp', 'password') muc = CONFIG.get('output_xmpp', 'muc') resource = ''.join([choice(string.ascii_letters) for i in range(8)]) jid = user + '/' + resource application = service.Application('honeypot') self.run(application, jid, password, JID(None, [muc, server, None]), server) def run(self, application, jidstr, password, muc, server): self.xmppclient = XMPPClient(JID(jidstr), password) if CONFIG.has_option('output_xmpp', 'debug') and \ CONFIG.getboolean('output_xmpp', 'debug') is True: self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol( muc, server, user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.anonymous = True self.xmppclient.startService() def write(self, logentry): for i in list(logentry.keys()): # Remove twisted 15 legacy keys if i.startswith('log_'): del logentry[i] elif i == "time": del logentry[i] msgJson = json.dumps(logentry, indent=5) self.muc.groupChat(self.muc.jrooms, msgJson) def stop(self): self.xmppclient.stopService()
class Output(cowrie.core.output.Output): """ xmpp output """ def start(self): server = CowrieConfig.get("output_xmpp", "server") user = CowrieConfig.get("output_xmpp", "user") password = CowrieConfig.get("output_xmpp", "password") muc = CowrieConfig.get("output_xmpp", "muc") resource = "".join([choice(string.ascii_letters) for i in range(8)]) jid = user + "/" + resource application = service.Application("honeypot") self.run(application, jid, password, JID(None, [muc, server, None]), server) def run(self, application, jidstr, password, muc, server): self.xmppclient = XMPPClient(JID(jidstr), password) if CowrieConfig.getboolean("output_xmpp", "debug", fallback=False): self.xmppclient.logTraffic = True (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, server, user + "-" + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.anonymous = True self.xmppclient.startService() def write(self, logentry): for i in list(logentry.keys()): # Remove twisted 15 legacy keys if i.startswith("log_"): del logentry[i] elif i == "time": del logentry[i] msgJson = json.dumps(logentry, indent=5) self.muc.groupChat(self.muc.jrooms, msgJson) def stop(self): self.xmppclient.stopService()
class DBLogger(dblog.DBLogger): def start(self, cfg): from random import choice import string server = cfg.get('database_xmpp', 'server') user = cfg.get('database_xmpp', 'user') password = cfg.get('database_xmpp', 'password') muc = cfg.get('database_xmpp', 'muc') channels = {} for i in ('createsession', 'connectionlost', 'loginfailed', 'loginsucceeded', 'command', 'clientversion'): x = cfg.get('database_xmpp', 'signal_' + i) if not x in channels: channels[x] = [] channels[x].append(i) resource = ''.join([choice(string.ascii_letters) for i in range(8)]) jid = user + '/' + resource application = service.Application('honeypot') self.run(application, jid, password, muc, channels) def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(jid.JID(jidstr), password) if self.cfg.has_option('database_xmpp', 'debug') and \ self.cfg.get('database_xmpp', 'debug') in ('1', 'true', 'yes'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, channels.keys(), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService() def broadcast(self, msgtype, msg): if msgtype in self.signals: self.report(msgtype, '%s@%s' % (self.signals[msgtype], self.muc.server), msg) def report(self, msgtype, to, xmsg): body = domish.Element((None, 'body')) body.addContent('\n') msg = domish.Element( ('http://github.com/micheloosterhof/cowrie', 'cowrie')) msg['type'] = msgtype msg.addChild(xmsg) body.addChild(msg) self.muc.groupChat(jid.JID(to), body) # We have to return an unique ID def createSession(self, peerIP, peerPort, hostIP, hostPort): session = uuid.uuid4().hex ses = domish.Element((None, 'session')) ses['session'] = session ses['remote_host'] = peerIP ses['remote_port'] = str(peerPort) if self.anonymous == True: ses['local_host'] = '127.0.0.1' else: ses['local_host'] = hostIP ses['local_port'] = str(hostPort) self.broadcast('createsession', ses) return session def handleTTYLogOpened(self, session, args): pass def handleConnectionLost(self, session, args): ses = domish.Element((None, 'session')) ses['session'] = session self.broadcast('connectionlost', ses) def handleLoginFailed(self, session, args): ses = domish.Element((None, 'credentials')) ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginfailed', ses) def handleLoginSucceeded(self, session, args): ses = domish.Element((None, 'credentials')) ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginsucceeded', ses) def handleCommand(self, session, args): ses = domish.Element((None, 'command')) ses['session'] = session ses['command'] = 'known' ses.addContent(args['input']) self.broadcast('command', ses) def handleUnknownCommand(self, session, args): ses = domish.Element((None, 'command')) ses['session'] = session ses['command'] = 'unknown' ses.addContent(args['input']) self.broadcast('command', ses) def handleInput(self, session, args): ses = domish.Element((None, 'input')) ses['session'] = session ses['realm'] = args['realm'] ses.addContent(args['input']) self.broadcast('input', ses) def handleTerminalSize(self, session, args): pass def handleClientVersion(self, session, args): ses = domish.Element((None, 'version')) ses['session'] = session ses['version'] = args['version'] self.broadcast('clientversion', ses)
def __init__(self, user, password, host=None, port=5222): jid_obj = jid.internJID(user) XMPPClient.__init__(self, jid_obj, password, host, port)
self.__send__(packet) output = (self.PACKET.get_packet(packet_id), None) # Return status. return output def abort_job(self, vm_jid, job_id): """ Terminate a job. """ self.__send__(self.abort_job_packet(vm_jid, job_id)) def terminate_vm(self, vm_jid): """ Terminate a VM. """ self.__send__(packet) # Misc. if __name__ == "__main__": FARM_JID = raw_input("Farm JID: ") MY_JID = raw_input("My JID: ") PASSWORD = raw_input("My password: "******"TestVillein") test_villein = villein(MY_JID, PASSWORD, FARM_JID) xmpp_client = XMPPClient(test_villein.JID, PASSWORD) xmpp_client.logTraffic = False test_villein.setHandlerParent(xmpp_client) xmpp_client.setServiceParent(app)
class XmppBackend(ProtocolBackend): protocol_name = 'xmpp' def configure(self, *args, **kwargs): # user args self.nick = kwargs.get('nick') # TODO: remove, make this just the bot name... self.room_nick = kwargs.get('room_nick') if self.room_nick is None: self.room_nick = self.nick self.log_traffic = kwargs.get('log_traffic', False) #TODO: remove localhost default, fail. self.server = kwargs.get('server', 'localhost') self.port = kwargs.get('port', XMPP_DEFAULT_PORT) self.use_ssl = kwargs.get('use_ssl', True) self.keepalive_freq = kwargs.get('keepalive_freq') # defaults to None if type(self.keepalive_freq) not in (None, float): try: self.keepalive_freq = float(self.keepalive_freq) except Exception as e: self.log.error( 'invalid keepalive passed in, {0!r}: {1!r}'.format( self.keepalive_freq, e)) self.keepalive_freq = None #TODO: have this default to botname @ . self.jabber_id = kwargs.get('jabber_id', self.nick + '@' + self.server) #self.room_jabber_id = # do we need this for servers that act wonky? maybe. self.password = kwargs.get('password') self.rooms = kwargs.get('rooms') # allow users to define custom handlers? not now. #self.subprotocol_handlers = kwargs.get() # internal self.bot_jid = jid.internJID(self.jabber_id) # probably want to override client? self.client = XMPPClient(self.bot_jid, self.password, host=self.server) if self.log_traffic is True: self.client.logTraffic = True # def connect_handlers(self): # for subprotocol in self.subprotocol_handlers: # instance = subprotocol() # instance.setHandlerParent(self.client) def connect(self, *args, **kwargs): #TODO: try moving this below self.client.startService() # setup handlers self.muc_handler = MucBot(self.rooms, self.room_nick, backend=self) self.muc_handler.setHandlerParent(self.client) self.presence = xmppim.PresenceClientProtocol() self.presence.setHandlerParent(self.client) self.presence.available() self.keepalive = ClientKeepalive(interval=self.keepalive_freq) self.keepalive.setHandlerParent(self.client) def handle_action(self, action): #self.log.debug(': {0!r}'.format(action)) if action.action_type == 'message': body = action.meta.get('body') if body: if action.destination_rooms: for room in action.destination_rooms: if action.scope == 'public': # TODO: replace this with an actual room lookup of known rooms room_jid = jid.internJID(room) message = muc.GroupChat(recipient=room_jid, body=body) self.client.send(message.toElement())
output = (self.PACKET.get_packet(packet_id), None) # Return status. return output def abort_job(self, vm_jid, job_id): """ Terminate a job. """ self.__send__(self.abort_job_packet(vm_jid, job_id)) def terminate_vm(self, vm_jid): """ Terminate a VM. """ self.__send__(packet) # Misc. if __name__ == "__main__": FARM_JID = raw_input("Farm JID: ") MY_JID = raw_input("My JID: ") PASSWORD = raw_input("My password: "******"TestVillein") test_villein = villein(MY_JID, PASSWORD, FARM_JID) xmpp_client = XMPPClient(test_villein.JID, PASSWORD) xmpp_client.logTraffic = False test_villein.setHandlerParent(xmpp_client) xmpp_client.setServiceParent(app)
class DBLogger(dblog.DBLogger): def start(self, cfg): from random import choice import string server = cfg.get('database_xmpp', 'server') user = cfg.get('database_xmpp', 'user') password = cfg.get('database_xmpp', 'password') muc = cfg.get('database_xmpp', 'muc') channels = {} for i in ('createsession', 'connectionlost', 'loginfailed', 'loginsucceeded', 'command', 'clientversion'): x = cfg.get('database_xmpp', 'signal_' + i) if not x in channels: channels[x] = [] channels[x].append(i) resource = ''.join([choice(string.ascii_letters) for i in range(8)]) jid = user + '/' + resource application = service.Application('honeypot') self.run(application, jid, password, JID(None,[muc,server,None]), channels) def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(JID(jidstr), password) if self.cfg.has_option('database_xmpp', 'debug') and \ self.cfg.get('database_xmpp', 'debug') in ('1', 'true', 'yes'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol( muc, channels.keys(), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService() def broadcast(self, msgtype, msg): if msgtype in self.signals: self.report(msgtype, '%s@%s' % (self.signals[msgtype], self.muc.server) , msg) def report(self, msgtype, to, xmsg): msg = {} msg['type'] = msgtype msg['message'] = xmsg msgJson = json.dumps(msg,indent=5) self.muc.groupChat(self.muc.jrooms, msgJson) # We have to return an unique ID def createSession(self, peerIP, peerPort, hostIP, hostPort): session = uuid.uuid4().hex ses = {} ses['session'] = session ses['remote_host'] = peerIP ses['remote_port'] = str(peerPort) if self.anonymous == True: ses['local_host'] = '127.0.0.1' else: ses['local_host'] = hostIP ses['local_port'] = str(hostPort) self.broadcast('createsession', ses) return session def handleTTYLogOpened(self, session, args): pass def handleConnectionLost(self, session, args): ses = {} ses['session'] = session self.broadcast('connectionlost', ses) def handleLoginFailed(self, session, args): ses = {} ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginfailed', ses) def handleLoginSucceeded(self, session, args): ses = {} ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginsucceeded', ses) def handleCommand(self, session, args): ses = {} ses['session'] = session ses['command'] = 'known' ses['input'] = args['input'] self.broadcast('command', ses) def handleUnknownCommand(self, session, args): ses = {} ses['session'] = session ses['command'] = 'unknown' ses['input'] = args['input'] self.broadcast('command', ses) def handleInput(self, session, args): ses = {} ses['session'] = session ses['realm'] = args['realm'] ses['input'] = args['input'] self.broadcast('input', ses) def handleTerminalSize(self, session, args): pass def handleClientVersion(self, session, args): ses = {} ses['session'] = session ses['version'] = args['version'] self.broadcast('clientversion', ses)
import sys from twisted.python import log from twisted.internet import reactor from twisted.words.protocols.jabber.jid import JID from wokkel.client import XMPPClient from wokkel.xmppim import RosterClientProtocol class RosterHandler(RosterClientProtocol): def gotRoster(self, roster): print 'Got roster:' for entity, item in roster.iteritems(): print ' %r (%r)' % (entity, item.name or '') def connectionInitialized(self): RosterClientProtocol.connectionInitialized(self) d = self.getRoster() d.addCallback(self.gotRoster) d.addErrback(log.err) USER_JID, PASSWORD = sys.argv[1:3] client = XMPPClient(JID(USER_JID), PASSWORD) roster = RosterHandler() roster.setHandlerParent(client) client.startService() reactor.run()
def makeService(self, options): # create Twisted application application = service.Application(TAP_NAME) serviceCollection = service.IServiceCollection(application) # check confguration file is specified and exists if not options["config"]: raise ValueError('Configuration file not specified (try to check --help option)') cfgFileName = options["config"]; if not os.path.isfile(cfgFileName): raise ConfigurationError('Configuration file not found:', cfgFileName) # read configuration file cfg = ConfigParser() with codecs.open(cfgFileName, 'r', encoding='utf-8') as f: cfg.readfp(f) # get Google login and password from configuration if not cfg.has_option('account', 'login') or not cfg.has_option('account', 'password'): raise ConfigurationError('Google account login and password must be specified ' 'in configuration file [account] section') self.googleLogin = cfg.get('account', 'login') self.googlePassword = cfg.get('account', 'password') self.googleDeveloperId = cfg.get('account', 'developer_id') \ if cfg.has_option('account', 'developer_id') else None # get ANDROID_ID from configuration if not cfg.has_option('account', 'android_id'): raise ConfigurationError('ANDROID_ID must be specified in configuration file [account] section') self.androidId = cfg.get('account', 'android_id') # get apps to monitor reviews apps = cfg.items('apps') if not apps: raise ConfigurationError('No apps to monitor reviews defined ' 'in configuration file [apps] section') for appId, appName in apps: self.apps.append(Application(appId, appName)) # open database dbFilename = cfg.get('db', 'filename') if cfg.has_option('db', 'filename') else DEFAULT_DB_FILENAME self.dbpool = adbapi.ConnectionPool("sqlite3", dbFilename, check_same_thread=False) # create XMPP client client = XMPPClient(JID(cfg.get('xmpp', 'jid')), cfg.get('xmpp', 'password')) # client.logTraffic = True client.setServiceParent(application) # join to all MUC rooms nickname = cfg.get('xmpp', 'nickname') if cfg.has_option('xmpp', 'nickname') else DEFAULT_NICKNAME notifications = cfg.items('chats') for chat, appIdPatterns in notifications: mucNotifier = MUCNotifier(JID(chat), nickname, appIdPatterns.split(',')) mucNotifier.setHandlerParent(client) self.mucNotifiers.append(mucNotifier) self.pollPeriod = humanfriendly.parse_timespan(cfg.get('poll', 'period')) \ if cfg.has_option('poll', 'period') else DEFAULT_POLL_PERIOD self.pollDelay = humanfriendly.parse_timespan(cfg.get('poll', 'delay')) \ if cfg.has_option('poll', 'delay') else DEFAULT_POLL_DELAY self.langs = [lang.strip() for lang in cfg.get('poll', 'lang').split(',')] \ if cfg.has_option('poll', 'lang') else [ DEFAULT_LANG ] templateLoader = None if cfg.has_option('notification', 'template'): templateFullName = cfg.get('notification', 'template') templatePath, self.templateName = os.path.split(templateFullName) templateLoader = FileSystemLoader(templatePath) else: self.templateName = DEFAULT_TEMPLATE_NAME templateLoader = PackageLoader('reviewnotify', 'templates') self.templateEnvironment = Environment(loader=templateLoader, extensions=['jinja2.ext.i18n']) localeDir = pkg_resources.resource_filename('reviewnotify', 'locales') locale = None if cfg.has_option('i18n', 'locale'): locale = cfg.get('i18n', 'locale') translations = babel.support.Translations.load(dirname=localeDir, locales=locale) self.templateEnvironment.install_gettext_translations(translations) self.templateEnvironment.filters['datetime'] = format_datetime self.templateEnvironment.filters['review_url'] = review_url reactor.callLater(3.0, self.run) # TODO make initial delay configurable return serviceCollection
def __init__(self, username, password, host='talk.google.com'): self.client = XMPPClient(JID(username), password,host) self.presence = PresenceFetcher() self.presence.setHandlerParent(self.client) self.client.startService()
class DBLogger(dblog.DBLogger): def start(self): from random import choice import string server = CONFIG.get('database_xmpp', 'server') user = CONFIG.get('database_xmpp', 'user') password = CONFIG.get('database_xmpp', 'password') muc = CONFIG.get('database_xmpp', 'muc') channels = {} for i in ('createsession', 'connectionlost', 'loginfailed', 'loginsucceeded', 'command', 'clientversion'): x = CONFIG.get('database_xmpp', 'signal_' + i) if x not in channels: channels[x] = [] channels[x].append(i) resource = ''.join([choice(string.ascii_letters) for i in range(8)]) jid = user + '/' + resource application = service.Application('honeypot') self.run(application, jid, password, JID(None, [muc, server, None]), channels) def run(self, application, jidstr, password, muc, channels, anon=True): self.xmppclient = XMPPClient(JID(jidstr), password) if CONFIG.has_option('database_xmpp', 'debug') and CONFIG.getboolean( 'database_xmpp', 'debug'): self.xmppclient.logTraffic = True # DEBUG HERE (user, host, resource) = jid.parse(jidstr) self.muc = XMPPLoggerProtocol(muc, list(channels.keys()), user + '-' + resource) self.muc.setHandlerParent(self.xmppclient) self.xmppclient.setServiceParent(application) self.signals = {} for channel in channels: for signal in channels[channel]: self.signals[signal] = channel self.anonymous = True self.xmppclient.startService() def broadcast(self, msgtype, msg): if msgtype in self.signals: self.report(msgtype, '{}@{}'.format(self.signals[msgtype], self.muc.server), msg) def report(self, msgtype, to, xmsg): msg = {} msg['type'] = msgtype msg['message'] = xmsg msgJson = json.dumps(msg, indent=5) self.muc.groupChat(self.muc.jrooms, msgJson) # We have to return an unique ID def createSession(self, peerIP, peerPort, hostIP, hostPort): session = uuid.uuid4().hex ses = {} ses['session'] = session ses['remote_host'] = peerIP ses['remote_port'] = str(peerPort) if self.anonymous: ses['local_host'] = '127.0.0.1' else: ses['local_host'] = hostIP ses['local_port'] = str(hostPort) self.broadcast('createsession', ses) return session def handleTTYLogOpened(self, session, args): pass def handleConnectionLost(self, session, args): ses = {} ses['session'] = session self.broadcast('connectionlost', ses) def handleLoginFailed(self, session, args): ses = {} ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginfailed', ses) def handleLoginSucceeded(self, session, args): ses = {} ses['session'] = session ses['username'] = args['username'] ses['password'] = args['password'] self.broadcast('loginsucceeded', ses) def handleCommand(self, session, args): ses = {} ses['session'] = session ses['command'] = 'known' ses['input'] = args['input'] self.broadcast('command', ses) def handleUnknownCommand(self, session, args): ses = {} ses['session'] = session ses['command'] = 'unknown' ses['input'] = args['input'] self.broadcast('command', ses) def handleInput(self, session, args): ses = {} ses['session'] = session ses['realm'] = args['realm'] ses['input'] = args['input'] self.broadcast('input', ses) def handleTerminalSize(self, session, args): pass def handleClientVersion(self, session, args): ses = {} ses['session'] = session ses['version'] = args['version'] self.broadcast('clientversion', ses)
for message in reversed(notification_set.get_messages()): body = message self.groupChat(self.room_jid, body) return notification_set def _log_success(self, notification_set): log.msg("Task finished successfully.") return True def _log_exceptions(self, failure): log.msg("Exception:{}".format(failure.getErrorMessage())) log.msg("Traceback:{}".format(failure.getTraceback())) body = "Is it just me, or is the internet on fire?" self.groupChat(self.room_jid, body) if __name__ == "__main__": # set up logging. FORMAT = '%(asctime)s :: %(message)s' logging.basicConfig(filename='sovbot.log', format=FORMAT, level=logging.INFO) observer = log.PythonLoggingObserver(loggerName='sovbot') observer.start() # set up client. client = XMPPClient(THIS_JID, PASSWORD) client.logTraffic = LOG_TRAFFIC mucHandler = SovBot(ROOM_JID, NICKNAME) mucHandler.setHandlerParent(client) client.startService() reactor.run()
def _authd(self, xs): currTime = Timer().utcnow() self._authFailureTime = None self._lastTimeAuth = self._connectedTime = currTime XMPPClient._authd(self, xs)
from twisted.internet import reactor from twisted.words.protocols.jabber.jid import JID from wokkel.client import XMPPClient from echo import Echo from roster import Roster with open('account', 'r') as f: account = f.readlines() jid = JID(account[0].rstrip('\n')) password = account[1].rstrip('\n') client = XMPPClient(jid, password) echo = Echo() roster = Roster() roster.setHandlerParent(client) echo.setHandlerParent(client) client.startService() reactor.run()
# Configuration parameters config = ConfigParser.RawConfigParser() config.read('bot.conf') myJID = JID(config.get('Connection', 'my_jid')) roomJID = JID(config.get('Connection', 'room_jid')) roomPassword = config.get('Connection', 'room_password') my_nick = config.get('Connection', 'my_nick') my_secret = config.get('Connection', 'my_secret') rt_url = config.get('RT', 'url') rt_display_url = config.get('RT','display_url') rt_user = config.get('RT', 'user') rt_pwd = config.get('RT', 'pwd') rt_default_queue = config.get('RT','default_queue') LOG_TRAFFIC = False #LOG_TRAFFIC = True # Set up the Twisted application application = service.Application("MUC Client") client = XMPPClient(myJID, my_secret) client.logTraffic = LOG_TRAFFIC client.setServiceParent(application) mucHandler = RTBot(roomJID, my_nick, rt_url, rt_user, rt_pwd, roomPassword, rt_display_url, output_format) mucHandler.setHandlerParent(client)
class XmppBackend(ProtocolBackend): protocol_name = 'xmpp' def configure(self, *args, **kwargs): # user args self.nick = kwargs.get('nick') # TODO: remove, make this just the bot name... self.room_nick = kwargs.get('room_nick') if self.room_nick is None: self.room_nick = self.nick self.log_traffic = kwargs.get('log_traffic', False) #TODO: remove localhost default, fail. self.server = kwargs.get('server', 'localhost') self.port = kwargs.get('port', XMPP_DEFAULT_PORT) self.use_ssl = kwargs.get('use_ssl', True) self.keepalive_freq = kwargs.get('keepalive_freq') # defaults to None if type(self.keepalive_freq) not in (None, float): try: self.keepalive_freq = float(self.keepalive_freq) except Exception as e: self.log.error('invalid keepalive passed in, {0!r}: {1!r}'.format(self.keepalive_freq, e)) self.keepalive_freq = None #TODO: have this default to botname @ . self.jabber_id = kwargs.get('jabber_id', self.nick + '@' + self.server) #self.room_jabber_id = # do we need this for servers that act wonky? maybe. self.password = kwargs.get('password') self.rooms = kwargs.get('rooms') # allow users to define custom handlers? not now. #self.subprotocol_handlers = kwargs.get() # internal self.bot_jid = jid.internJID(self.jabber_id) # probably want to override client? self.client = XMPPClient(self.bot_jid, self.password, host=self.server) if self.log_traffic is True: self.client.logTraffic = True # def connect_handlers(self): # for subprotocol in self.subprotocol_handlers: # instance = subprotocol() # instance.setHandlerParent(self.client) def connect(self, *args, **kwargs): #TODO: try moving this below self.client.startService() # setup handlers self.muc_handler = MucBot(self.rooms, self.room_nick, backend=self) self.muc_handler.setHandlerParent(self.client) self.privatechat_handler = PrivateChatBot(backend=self) self.privatechat_handler.setHandlerParent(self.client) self.presence = xmppim.PresenceClientProtocol() self.presence.setHandlerParent(self.client) self.presence.available() self.keepalive = ClientKeepalive(interval=self.keepalive_freq) self.keepalive.setHandlerParent(self.client) def handle_action(self, action): self.log.debug('XMPP ACTION : {0!r}'.format(action)) if action.action_type != 'message': return body = str(action.meta.get('body')) if not body: return if not action.destination_rooms: return for room in action.destination_rooms: if action.scope == 'public': room_jid = jid.internJID(room) message = muc.GroupChat(recipient=room_jid, body=body) self.client.send(message.toElement()) if action.scope == 'private': if room is not None: msg = xmppim.Message(recipient=jid.internJID(room), sender=self.bot_jid, body=body) self.client.send(msg.toElement())