def createNewConnection(self): # should make debug level settable in configuration con = jabber.Client(host=self.server, debug=DEBUG_LEVEL, log=sys.stderr) self.con = con con.setMessageHandler(self.messageCB) con.setPresenceHandler(self.presenceCB) con.setIqHandler(self.iqCB) con.setDisconnectHandler(self.disconnectedCB) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e ##sys.exit(0) return
def jabbermain(self): lock(self.mutex) try: self.jabber = jabber.Client(self.conf['server'], int(self.conf['port']) ) self.jabber.connect() except socket.error, e: lock(komsendq_m) komsendq.put(kommessage(self.me, l1_e( u"Anslutningen till Jabberservern misslyckades, gissningsvis pga nätverksfel. " u"Felet var '%s' vid anslutning till %s:%s. " u"Det är rekommenderat att du ger kommandot 'disconnect' för att " u"hamna i ett känt tillstånd." % (e.args[1], str(self.conf['server']), str(self.conf['port']) ) ))) unlock(komsendq_m) return
def connect(): global con debug = conf.general.debug print ">>> Connecting" general = conf.general if debug: print '>>> debug is [%d]' % general['debug'] print '>>> host is [%s]' % general['server'] print '>>> account is [%s]' % general['account'] print '>>> resource is [%s]' % general['resource'] con = jabber.Client(host=general['server'], debug=False, log=xmllogf, port=5223, connection=xmlstream.TCP_SSL) print ">>> Logging in" con.connect() con.setMessageHandler(messageCB) con.setPresenceHandler(presenceCB) con.setIqHandler(iqCB) con.setDisconnectHandler(disconnectedCB) con.auth(general['account'], general['password'], general['resource']) con.requestRoster() con.sendInitPresence() r = con.getRoster() # for i in userinfo.keys()[:]: # if not i in r.getJIDs() and not issuper(i): # del userinfo[i] for i in r.getJIDs(): if not userinfo.has_key(i): adduser(getdisplayname(i)) saveconfig() sendpresence(conf.general['status']) # systoall(_('Channel is started.')) print ">>> Online!" print >> logf, 'The bot is started!', time.strftime('%Y-%m-%d %H:%M:%S')
argv.remove('-d') else: log_to_stdout = False if argv[1].find('@') != -1: arg_tmp = sys.argv[1].split('@') arg_tmp.reverse() argv[1:2] = arg_tmp del arg_tmp Server = argv[1] Username = '' Password = '' Resource = 'default' con = jabber.Client(host=Server, debug=False, log=None) # Experimental SSL support # # con = jabber.Client(host=Server,debug=True ,log=sys.stderr, # port=5223, connection=xmlstream.TCP_SSL) try: con.connect() except IOError, e: pg_log("Couldn't connect: %s" % e) sys.exit(0) else: pg_log(colorize("Connected", 'red')) con.setMessageHandler(messageCB)
xmlrpc_node = iq.getQueryPayload() ## Let xmlrpclib parse the method call. The node becomes a string ## automatically when called in a str context. result,func = xmlrpclib.loads("<?xml version='1.0'?>%s" % xmlrpc_node) ## Print the function name and params xmllibrpc returns print "Recieved -> ",result ## Exit sys.exit() ## Get a jabber connection object, with logging to stderr con = jabber.Client(host=Server,log=sys.stderr) ## Try and connect try: con.connect() except: print "Couldn't connect: %s" % e sys.exit(0) else: print "Connected" ## Attatch the above iq callback con.registerHandler('iq',iq_CB) con.registerHandler('iq',iq_error_CB, type='error') con.registerHandler('iq',iq_xmlrpc_response_CB, type='get', ns='jabber:iq:rpc')
class WatcherProc(object): jc = jabber.Client(host=Config.BOT_SRVR) stream = Stream() def connect(self): r = True try: self.jc.connect() except IOError: r = False if r: self.jc.registerHandler('message', self.jcbMessage) self.jc.registerHandler('presence', self.jbcPresence) self.jc.registerHandler('iq', self.jbcIq) if self.jc.auth(Config.BOT_USER, Config.BOT_PASS, Config.BOT_LOCT): self.jc.requestRoster() else: r = False return r def disconnect(self): self.jc.disconnect() self.stream.close() def check(self): self.jc.process() self.setJabberState("Working!") strs = self.stream.getWorkingStreams() for s in strs: if s[Stream.TYPE] == 1: self.parseRSS(s) elif s[Stream.TYPE] == 2: self.parsePage(s) self.setJabberState("Waiting") for i in range(1, 300): self.jc.process() time.sleep(1) def parseRSS(self, s): if s[Stream.STATE]: state = json.loads(s[Stream.STATE]) else: state = [] #filters = json.loads(s[Stream.FILTERS]) d = feedparser.parse(s[Stream.URL]) if d: newState = [] for e in d.entries: if e and hasattr(e, 'id'): if (not e.id in state) and len(state) > 0: link = re.sub(' ', '', e.link) self.sendJabberMessage(u"%s\n%s" % (e.title, link)) newState.append(e.id) self.stream.saveState(s[Stream.ID], json.dumps(newState)) else: self.sendJabberMessage("Error loading RSS stream - " + s[Stream.URL]) def parsePage(self, s): if s[Stream.STATE]: state = s[Stream.STATE] else: state = "" p = urllib.urlopen(s[Stream.URL]) if p and p.getcode() == 200: pi = p.read() pt = re.search("<title>([^<]*)</title>", pi) if pt: newState = unicode(pt.group(1).decode("cp1251").strip()) needSave = True if state: if state <> newState and len(newState) > 16: self.sendJabberMessage(u"%s\n%s" % (newState, s[Stream.URL])) else: needSave = False if needSave: self.stream.saveState(s[Stream.ID], newState) else: self.sendJabberMessage("Error parsing page stream - " + s[Stream.URL]) else: self.sendJabberMessage("Error loading page stream - " + s[Stream.URL]) def jcbMessage(self, c, msg): if msg.getBody() and msg.getFrom().getStripped() in Config.NOTIFY: self.parseJabberMessage(msg.getBody(), msg.getFrom()) def jbcPresence(self, c, prs): who = str(prs.getFrom()) type = prs.getType() if type == 'subscribe': c.send(jabber.Presence(to=who, type='subscribed')) c.send(jabber.Presence(to=who, type='subscribe')) elif type == 'unsubscribe': c.send(jabber.Presence(to=who, type='unsubscribed')) c.send(jabber.Presence(to=who, type='unsubscribe')) def jbcIq(self, con, iq): pass def setJabberState(self, state): p = jabber.Presence() p.setStatus(state) self.jc.send(p) def sendJabberMessage(self, text): for r in Config.NOTIFY: t = self.stripXML(text.strip()) msg = jabber.Message(r, t) msg.setType('chat') self.jc.send(msg) def sendJabberMessageTo(self, to, text): t = self.stripXML(text.strip().encode("utf-8")) msg = jabber.Message(to, t) msg.setType('chat') self.jc.send(msg) self.jc.process() def parseJabberMessage(self, str, fr): cmd = str.split() if cmd[0] == 'ADD': self.sendJabberMessageTo(fr, self.stream.addStream(cmd[1].strip())) elif cmd[0] == 'DEL': self.sendJabberMessageTo(fr, self.stream.delStream(cmd[1].strip())) elif cmd[0] == 'LIST': self.sendJabberMessageTo(fr, self.stream.listStreams()) elif cmd[0] == 'PAUSE': self.sendJabberMessageTo(fr, self.stream.pauseStream(cmd[1].strip())) elif cmd[0] == 'START': self.sendJabberMessageTo(fr, self.stream.startStream(cmd[1].strip())) else: self.sendJabberMessageTo( fr, "commands are\nADD [stream URL] - add stream to list\nLIST - show streams with ID\nDEL [id] - delete stream with id\nPAUSE [id] - stop watching stream with id\nSTART [id] - start wathching stream with id" ) def stripXML(self, s): def fixup(m): text = m.group(0) if text[:1] == "<": if text[1:3] == 'br': return '\n' else: return "" # ignore tags if text[:2] == "&#": try: if text[:3] == "&#x": return chr(int(text[3:-1], 16)) else: return chr(int(text[2:-1])) except ValueError: pass elif text[:1] == "&": import htmlentitydefs if text[1:-1] == "mdash": entity = " - " elif text[1:-1] == "ndash": entity = "-" elif text[1:-1] == "hellip": entity = "-" else: entity = htmlentitydefs.entitydefs.get(text[1:-1]) if entity: if entity[:2] == "&#": try: return chr(int(entity[2:-1])) except ValueError: pass else: return entity return text # leave as is ret = re.sub("(?s)<[^>]*>|&#?\w+;", fixup, s) return re.sub("\n+", '\n', ret)
endcode = '\033[0m' if type(col) == type(1): return initcode + str(col) + 'm' + txt + endcode try: return initcode + str(cols[col]) + 'm' + txt + endcode except: return txt if len(sys.argv) == 1: usage() Server = sys.argv[1] Username = '' Password = '' Resource = 'default' con = jabber.Client(host=Server, debug=jabber.DBG_ALWAYS, log=sys.stderr) # Experimental SSL support # # con = jabber.Client(host=Server,debug=True ,log=sys.stderr, # port=5223, connection=xmlstream.TCP_SSL) try: con.connect() except IOError, e: print "Couldn't connect: %s" % e sys.exit(0) else: print colorize("Connected", 'red') con.registerHandler('message', messageCB)