def connect( self): if not self.conn: if self.__debug: conn = xmpp.Client(self.jid.getDomain()) else: conn = xmpp.Client(self.jid.getDomain(), debug = []) conres = conn.connect() if not conres: self.log.error('unable to connect to server %s.' % self.jid.getDomain()) return None if conres<>'tls': self.log.warning('unable to establish secure connection - TLS failed!') authres = conn.auth(self.jid.getNode(), self.__password, self.res) if not authres: self.log.error('unable to authorize with server.') return None if authres<>'sasl': self.log.warning("unable to perform SASL auth os %s. Old authentication method used!" % self.jid.getDomain()) conn.sendInitPresence() self.conn = conn self.roster = self.conn.Roster.getRoster() self.log.info('*** roster ***') for contact in self.roster.getItems(): self.log.info(' %s' % contact) self.log.info('*** roster ***') self.conn.RegisterHandler('message', self.callback_message) self.conn.RegisterHandler('presence', self.callback_presence) return self.conn
def __connect(self): self._jid = xmpp.JID(self._settings.jid) if not self._conn: if not self._options.debug: conn = xmpp.Client(self._jid.getDomain()) else: conn = xmpp.Client(self._jid.getDomain(), debug=[]) res = conn.connect() if not res: logging.error("Unable to connect to server %s." % self._jid.getDomain()) exit() if res <> 'tls': logging.warning("Unable to establish TLS connection.") res = conn.auth(self._jid.getNode(), self._settings.password, self._settings.chat_name) if not res: logging.error("Unable to authenticate this connection.") exit() if res <> 'sasl': logging.warning("Unable to get SASL creditential for: %s." % self.jid.getDomain()) conn.RegisterHandler('message', self.message_handler) conn.RegisterHandler('presence', self.presence_handler) conn.sendInitPresence() self.roster = conn.Roster.getRoster() self._conn = conn if hasattr(self._settings, 'default_status'): self._conn.send( xmpp.Presence(status=self._settings.default_status)) if hasattr(self._settings, 'groupchat'): self.__join_muc()
def connect(self): """Connects the bot to server or returns current connection, send inital presence stanza and registers handlers """ if not self.conn: # TODO improve debug if self.__debug: conn = xmpp.Client(self.jid.getDomain()) else: conn = xmpp.Client(self.jid.getDomain(), debug=[]) #connection attempt if self.__hostname: conres = conn.connect((self.__hostname, self.__port)) else: conres = conn.connect() if not conres: self.log.error('unable to connect to server %s.' % self.jid.getDomain()) return None if conres != 'tls': self.log.warning('unable to establish secure connection '\ '- TLS failed!') username = self.jid.getNode() authres = conn.auth(username, self.__password, self.res) if not authres: self.log.error('unable to authorize with server.') return None if authres != 'sasl': self.log.warning("unable to perform SASL auth on %s. "\ "Old authentication method used!" % self.jid.getDomain()) # Connection established - save connection self.conn = conn # Send initial presence stanza (say hello to everyone) self.conn.sendInitPresence() # Save roster and log Items self.roster = self.conn.Roster.getRoster() self.log.info('*** roster ***') for contact in self.roster.getItems(): self.log.info(' %s' % contact) self.log.info('*** roster ***') # Register given handlers (TODO move to own function) for (handler, callback) in self.handlers: self.conn.RegisterHandler(handler, callback) self.log.debug('Registered handler: %s' % handler) return self.conn
def connect(self): if not self.conn: if self.__debug: conn = xmpp.Client(self.jid.getDomain()) else: conn = xmpp.Client(self.jid.getDomain(), debug=[]) conres = conn.connect() if not conres: self.log.error('unable to connect to server %s.' % self.jid.getDomain()) return None if conres <> 'tls': self.log.warning( 'unable to establish secure connection - TLS failed!') authres = conn.auth(self.jid.getNode(), self.__password, self.res) if not authres: self.log.error('unable to authorize with server.') return None if authres <> 'sasl': self.log.warning( "unable to perform SASL auth os %s. Old authentication method used!" % self.jid.getDomain()) conn.sendInitPresence() self.conn = conn self.roster = self.conn.Roster.getRoster() self.log.info('*** roster ***') for contact in self.roster.getItems(): self.log.info(' %s' % contact) self.log.info('*** roster ***') self.conn.RegisterHandler('message', self.callback_message) self.conn.RegisterHandler('presence', self.callback_presence) # keep bot alive even during long periods of inactivity if self.__keepalive: def _keepalive_f(): while True: time.sleep(self.__keepalive_time) self.callback_keepalive() keepalive_th = threading.Thread(target=_keepalive_f) keepalive_th.setDaemon(True) keepalive_th.start() # prevents from running the daemon more than once self.__keepalive = False return self.conn
def _connect(self): """ This method is called when the bot is ready to connect a xmpp server (called by "connecting" state). This part manage SASL, TLS and such things. """ if not self.conn: if len(self._username.split('@')) > 1: nod = self._username.split('@')[0] dom = self._username.split('@')[1] else: nod = None dom = None if self._debug: conn = xmpp.Client(dom) else: conn = xmpp.Client(dom, debug=[]) conres = conn.connect() if not conres: self.log.error('unable to connect to server %s.' % self.jid.getDomain()) return None if conres != 'tls': self.log.warning('unable to establish secure connection - TLS failed!') authres = conn.auth(nod, self._password, self._res) if not authres: self.log.error('unable to authorize with server.') return None if authres != 'sasl': self.log.warning("unable to perform SASL auth os %s. Old authentication method used!" % self.jid.getDomain()) conn.sendInitPresence() self.conn = conn self.updateRosters() self.conn.RegisterHandler('message', self._callback_message) self.conn.RegisterHandler('presence', self._callback_presence) self.conn.RegisterHandler('iq', self._callback_iq) # Set current JID self.jid = xmpp.JID(node=conn.User, domain=conn.Server, resource=conn.Resource) self.log.info('self.jid.getNode() = ' + self.jid.getNode()) self.log.info('self.jid.getDomain() = ' + self.jid.getDomain()) self.log.info('self.jid.getResource() = ' + self.jid.getResource()) # Set File Transfer Handler #self.ibb = xmpp.filetransfer.IBB() #self.ibb.PlugIn(self.conn) return self.conn
def _Dynamic_SendChannelMessage(self, request, response): """Implementation of channel.send_message. Queues a message to be retrieved by the client when it polls. Args: request: A SendMessageRequest. response: A VoidProto. """ application_key = urllib.quote(request.application_key()) if not request.message(): raise apiproxy_errors.ApplicationError( channel_service_pb.ChannelServiceError.BAD_MESSAGE) appname = os.environ['APPNAME'] unique_app_id = hashlib.sha1(appname + application_key).hexdigest() jid = 'channel~%s~%s@%s' % (unique_app_id, application_key, self.xmpp_domain) xmpp_username = appname + "@" + self.xmpp_domain my_jid = xmpppy.protocol.JID(xmpp_username) client = xmpppy.Client(my_jid.getDomain(), debug=[]) client.connect((self._xmpp_location, self.PORT), secure=False) client.auth(my_jid.getNode(), self.uasecret, resource=my_jid.getResource()) message = xmpppy.protocol.Message(frm=xmpp_username, to=jid, body=request.message(), typ="chat") client.send(message)
def open(self): """ Open a connection to the server. """ print "Authenticating password for '%s'..." % self.name try: self.client.auth(self.name.lower(), self.password) except IOError: self.client = xmpp.Client(self.server, debug=self.debug) self.client.connect() self.client.auth(self.name.lower(), self.password) print "Registering message handler..." self.client.RegisterHandler('message', self.messageCB) self.client.sendInitPresence() self.send("", "2") # make this the only place I'm logged in messages = self.receive() count = 0 while len(messages) == 0 and count < 5: print " waiting for response..." time.sleep(1) messages = self.receive() count += 1 if count >= 5: print "Giving up! Are you sure you have the right password?" self.ok = 0 else: print "Done!" self.ok = 1
def start_bot(): if len(sys.argv) < 3: print "Usage: start_bot.py [email protected] password" else: jid = xmpp.JID(sys.argv[1]) user, server, password = jid.getNode(), jid.getDomain(), sys.argv[2] conn = xmpp.Client(server) #,debug=[]) conres = conn.connect() if not conres: print "Unable to connect to server %s!" % server sys.exit(1) if conres <> 'tls': print "Warning: unable to estabilish secure connection - TLS failed!" authres = conn.auth(user, password) if not authres: print "Unable to authorize on %s - check login/password." % server sys.exit(1) if authres <> 'sasl': print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server conn.RegisterHandler('message', messageCB) conn.RegisterHandler('presence', presenceCB) conn.sendInitPresence() ##conn.send(xmpp.protocol.Message('*****@*****.**','This is a automatic message')) print "Bot started." GoOn(conn)
def connect_jabber(): client = xmpp.Client(JABBER_SERVER) client.connect(server=(JABBER_SERVER, JABBER_PORT)) client.auth(JABBER_USER, JABBER_PASS, JABBER_NAME) client.sendInitPresence() client.send(xmpp.Presence(to="%s/%s" % (JABBER_ROOM, JABBER_NAME))) return client
def goto34_auth(type, source, conf): if not goto: return try: bxc = random.choice(nemss) pa4ssw = random.choice(pas) gserv = random.choice(serv) mainRes = 'sdos' + str(random.randrange(00, 30)) name, domain, password, newBotJid = bxc, gserv, pa4ssw, 0 node = unicode(name) lastnick = name jid = xmpp.protocol.JID(node=node, domain=domain, resource=mainRes) psw = u'' cl = xmpp.Client(jid.getDomain(), debug=[]) con = cl.connect() au = cl.auth(jid.getNode(), password, jid.getResource()) cl.sendInitPresence() if cl.isConnected(): threading.Thread(None, j_slaefr_lev, 'j_slaefr_lev' + str(random.randrange(0, 999)), (cl, conf)).start() threading.Thread( None, change_Slaefr_nicks, 'change_Slaefr_nicks' + str(random.randrange(0, 999)), (cl, conf)).start() threading.Thread( None, change_Slaefr_prs, 'change_Slaefr_prs' + str(random.randrange(0, 999)), (cl, conf)).start() else: threading.Thread(None, goto34_auth, 'goto34_auth', (type, source, conf)).start() return except: pass
def signIn(self): #sets jabber ID self.jid = xmpp.protocol.JID(self.jid) #Creates a client self.client = xmpp.Client(self.jid.getDomain(), debug=[]) if self.client.connect() == "": #print "not connected" return False if self.client.auth(self.jid.getNode(), self.pwd) == None: #print "authentication failed" #print self.pwd #print self.jid return False #Shows server client is online self.client.sendInitPresence() self.roster = Roster.Roster(self.client) self.roster.start() self.roster.getContactList() #must do this QtCore.QObject.connect(self.roster, QtCore.SIGNAL("buddyRequest"), self.buddyRequest) self.receiveThread = ReceiveMessage.ReceiveMessage( self.client, self.contactList()) self.receiveThread.start() self.presence = xmpp.protocol.Presence() QtCore.QObject.connect(self.receiveThread, QtCore.SIGNAL("message"), self.receiveMessage) self.statusCheck = JabberContacts.JabberContacts(self.client) self.statusCheck.start() QtCore.QObject.connect(self.statusCheck, QtCore.SIGNAL("updateBuddyStatus"), self.updateBuddies) return True
def connect(self, username, password): # Create the connection jid = xmpp.protocol.JID(username) user = jid.getNode() server = jid.getDomain() self.conn = xmpp.Client(server, debug=[]) conres = self.conn.connect(("talk.google.com", 5222)) if not conres: self.logger.error("Unable to connect to server %s!" % server) sys.exit(1) if conres <> 'tls': self.logger.warn( "Unable to estabilish secure connection - TLS failed!") authres = self.conn.auth(user, password) if not authres: self.logger.error( "Unable to authorize on %s - check login/password." % server) sys.exit(1) if authres <> 'sasl': self.logger.warn( "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server) self.logger.info("Connection established.")
def updateGtalkStatus(self): #connect jid=xmpp.protocol.JID(self.username) cl=xmpp.Client(jid.getDomain(),debug=[]) if not cl.connect(('talk.google.com',5222)): print 'Can not connect to server.' return render_to_response('gtalk/gtalk.html', { 'error': 'could not connect to server', }) if not cl.auth(jid.getNode(),self.password): print 'Can not auth with server' return render_to_response('gtalk/gtalk.html', { 'error': 'coult not auth with server', }) #build query to get current status iq = xmpp.Iq() iq.setType('get') iq.setTo(self.username) node = xmpp.Node() node.setName('query') node.setAttr('xmlns', 'google:shared-status') iq.addChild(node=node) print iq #register with server and send subscribe to status updates cl.RegisterHandler('iq',self.iqHandler) cl.send(iq) self.GoOn(cl) cl.disconnect()
def plugin(srv, item): """Send a message to XMPP recipient(s).""" srv.logging.debug("*** MODULE=%s: service=%s, target=%s", __file__, item.service, item.target) xmpp_addresses = item.addrs sender = item.config['sender'] password = item.config['password'] text = item.message if not xmpp_addresses: srv.logging.warn("Skipped sending XMPP notification to %s, " "no addresses configured" % (item.target)) return False try: srv.logging.debug("Sending XMPP notification to %s, addresses: %s" % (item.target, xmpp_addresses)) for target in xmpp_addresses: jid = xmpp.protocol.JID(sender) connection = xmpp.Client(jid.getDomain(), debug=[]) connection.connect() connection.auth(jid.getNode(), password, resource=jid.getResource()) connection.send(xmpp.protocol.Message(target, text)) srv.logging.debug("Successfully sent message") except Exception as e: srv.logging.error("Error sending message to %s: %s" % (item.target, e)) return False return True
def __init__(self, JID, Password): """ Create a new bot. Connect to the server and log in. """ # connect... jid = xmpp.JID(JID) self.connection = xmpp.Client(jid.getDomain(), debug=[]) self.en_ml_db = None result = self.connection.connect() if result is None: raise ConnectionError # authorize result = self.connection.auth(jid.getNode(), Password) if result is None: raise AuthorizationError self.connection.RegisterHandler('presence', self.presenceHandler) self.connection.RegisterHandler('message', self.messageHandler) # ...become available self.connection.sendInitPresence() # presence #self.connection.sendInitPresence(requestRoster=0) try: #search the dictionary in same directory of program self.en_ml_db = DictDB("freedict-eng-mal") except: #retry in standard directory of dictd self.en_ml_db = DictDB("/usr/share/dictd/freedict-eng-mal")
def connect(self): self.disconnected = False jid = xmpp.JID(self.login) user, server, password = jid.getNode(), jid.getDomain(), self.password self.conn = xmpp.Client(server, debug=[]) conres = self.conn.connect(server=(self.server_host, self.server_port)) if not conres: print "Unable to connect to server %s!" % server sys.exit(1) if conres <> 'tls': print "Warning: unable to estabilish secure connection - TLS failed!" authres = self.conn.auth(user, password, "laptop") if not authres: print "Unable to authorize on %s - Plsese check your name/password." % server sys.exit(1) if authres <> "sasl": print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server self.conn.RegisterHandler("message", self.controller) self.conn.RegisterHandler('presence', self.presenceHandler) self.conn.RegisterDisconnectHandler(self.on_disconnect) self.conn.sendInitPresence() self.setState(self.show, self.status) if self.timer: try: self.timer.cancel() except: pass self.timer = threading.Timer(600, self.ping) self.timer.start()
def connect(self): logging.basicConfig(filename=self.__log_file, level=logging.DEBUG) if not self.conn: conn = xmpp.Client(self.jid.getDomain(), debug=[]) if self.__connect_server: try: conn_server, conn_port = self.__connect_server.split( ":", 1) except ValueError: conn_server = self.__connect_server conn_port = 5222 conres = conn.connect((conn_server, int(conn_port))) else: conres = conn.connect() if not conres: return None authres = conn.auth(self.jid.getNode(), self.__password, self.res) if not authres: return None self.conn = conn self.conn.sendInitPresence() self.roster = self.conn.Roster.getRoster() for (handler, callback) in self.handlers: self.conn.RegisterHandler(handler, callback) return self.conn
def xmppListen(gtalkServerAddr, user, passwd): cnx = xmpp.Client('gmail.com', debug=[]) cnx.connect() cnx.auth(user, passwd) cnx.sendInitPresence() cnx.RegisterHandler('message', xmppMessageCB) return cnx
def Connect(): globals()['jClient'] = globals()['JCON'] = xmpp.Client(HOST, PORT, None) Print('\n\nConnecting...', color4) if SECURE: CONNECT = jClient.connect((SERVER, PORT), None, None, False) else: CONNECT = jClient.connect((SERVER, PORT), None, False, True) if CONNECT: if SECURE and CONNECT != 'tls': Print( '\nWarning: unable to estabilish secure connection - TLS failed!', color2) else: Print('\nConnection is OK', color3) Print('Using: %s' % str(jClient.isConnected()), color4) else: Exit("\nCan't Connect.\nSleep for 30 seconds", 0, 30) Print('\nAuthentication plese wait...', color4) AUTHENT = jClient.auth(USERNAME, PASSWORD, RESOURCE) if AUTHENT: if AUTHENT != 'sasl': Print( '\nWarning: unable to perform SASL auth. Old authentication method used!', color2) else: Print('Auth is OK', color3) else: Exit( '\nAuth Error: %s %s\nMaybe, incorrect jid or password?' % ( ` jClient.lastErr `, ` jClient.lastErrCode `), 0, 12) jClient.sendInitPresence() jClient.RegisterHandler(xmpp.NS_MESSAGE, MESSAGE_PROCESSING) jClient.RegisterHandler(xmpp.NS_PRESENCE, PRESENCE_PROCESSING) jClient.RegisterHandler(xmpp.NS_IQ, IQ_PROCESSING) Print('\n\nYahoo! I am online!', color3)
def doInit(self, mode): self._jid = xmpp.protocol.JID(self.jid) self._client = xmpp.Client(self._jid.getDomain(), debug=[]) self._client.connect() self._client.auth(self._jid.getNode(), self.password, resource=session.instrument.instrument)
def im(self, iMessage): jid = xmpp.protocol.JID(self.imParams.jid) # cl = xmpp.Client( jid.getDomain(), debug=['always'] ) cl = xmpp.Client(jid.getDomain(), debug=[]) con = cl.connect((self.imParams.server, self.imParams.port)) if not con: print 'xmpp could not connect!' return False print 'xmpp connected with', con auth = cl.auth(jid.getNode(), self.imParams.password, resource=jid.getResource()) if not auth: print 'xmpp could not authenticate!' return False print 'xmpp authenticated using', auth # cl.Process( 1 ) cl.sendInitPresence( requestRoster=0) #if this line is ommited no messages are received # cl.Process( 1 ) for r in iMessage.recipients: id = cl.send(xmpp.protocol.Message(r, iMessage.message, typ='chat')) cl.Process(1) print('xmpp sent message [{}] with id {}'.format( iMessage.message.encode('utf-8'), id)) time.sleep( 2 ) # some older servers will not send the message if you disconnect immediately after sending cl.disconnect() return True
def updateGtalkStatus(self, google_username, google_pass): if '@' not in google_username: google_username = '******' % google_username print google_username #connect jid = xmpp.protocol.JID(google_username) cl = xmpp.Client(jid.getDomain(), debug=[]) if not cl.connect(('talk.google.com', 5222)): print 'Can not connect to server.' #sys.exit(1) self.updated = True return if not cl.auth(jid.getNode(), google_pass): print 'Can not auth with server %s ' % google_username self.updated = True return #build query to get current status iq = xmpp.Iq() iq.setType('get') iq.setTo(google_username) node = xmpp.Node() node.setName('query') node.setAttr('xmlns', 'google:shared-status') iq.addChild(node=node) print iq #register with server and send subscribe to status updates cl.RegisterHandler('iq', self.iqHandler) cl.send(iq) self.GoOn(cl) cl.disconnect()
def main(): #obtaining login credentials of the gmail account uname = raw_input() pwd = raw_input() jid = uname + '@gmail.com' jid = xmpp.protocol.JID(jid) cl = xmpp.Client(jid.getDomain()) if cl.connect() == "": print "Not connected!" sys.exit(0) if cl.auth(uname, pwd, 'bot') == None: print "Authentication failed" sys.exit(0) #message call back handler cl.RegisterHandler('message', messageCB) #presence notification call back handler cl.RegisterHandler('presence', presenceCB) #notifying your subscribers about your presence cl.sendInitPresence() #keep running GoOn(cl) return
def xmpp_notify(event_type, description, content=None): """XMPP Notification""" #Ignore Statistics if (event_type == 'Stats'): return jid = xmpp.protocol.JID(config.get('dbAlerter', 'xmpp_from')) cl = xmpp.Client(jid.getDomain(), debug=[]) conn = cl.connect() if not conn: log_notify('Error', 'XMPP Failed to connect.') sys.exit(1) auth = cl.auth(jid.getNode(), config.get('dbAlerter', 'xmpp_password'), resource=jid.getResource()) if not auth: log_notify('Error', 'XMPP Failed to authenticate.') sys.exit(1) id = cl.send( xmpp.protocol.Message( config.get('dbAlerter', 'xmpp_to'), event_type + ' from dbAlerter on (' + socket.gethostname() + ') - ' + description)) cl.disconnect() log_notify(event_type, description, 'XMPP')
def __init__(self, name, password, debug=[]): """ Constructs a connection for communicating to an IM server. name: can be "laura" to login into the default IM server, or can be "*****@*****.**" to connect to the server running at "yourserver.edu". password: any password of your choosing. First time use will require the password to match the username on subsequent use. debug: can be [] for no debugging information, or can be ['always'] to get see all of the debugging information. """ self.lock = threading.Lock() self.messages = [] # Start a thread up in here self.password = password if "@" not in name: self.name, self.server = name, "myro.roboteducation.org" else: self.name, self.server = name.split("@") self.debug = debug self.client = xmpp.Client(self.server, debug=self.debug) print "Making connection to server..." self.client.connect() print "Registering '%s'..." % self.name self.register(self.name.lower(), self.password) try: self.open() except AttributeError: print "Help! It appears that the Myro Chat Server is down."
def im(self, iMessage): jid = xmpp.protocol.JID(self.imParams.jid) cl = xmpp.Client(jid.getDomain(), debug=[]) con = cl.connect() if not con: print 'could not connect!' return False print 'connected with', con auth = cl.auth(jid.getNode(), self.imParams.password, resource=jid.getResource()) if not auth: print 'could not authenticate!' return False print 'authenticated using', auth #cl.SendInitPresence(requestRoster=0) # you may need to uncomment this for old server for r in iMessage.recipients: id = cl.send(xmpp.protocol.Message(r, iMessage.message)) print 'sent message with id', id time.sleep( 1 ) # some older servers will not send the message if you disconnect immediately after sending cl.disconnect() return True
def _Dynamic_SendMessage(self, request, response): """Implementation of XmppService::SendMessage. Args: request: An XmppMessageRequest. response: An XmppMessageResponse . """ appname = os.environ['APPNAME'] xmpp_username = appname + "@" + self.xmpp_domain my_jid = xmpppy.protocol.JID(xmpp_username) client = xmpppy.Client(my_jid.getDomain(), debug=[]) client.connect((self._xmpp_location, self.PORT), secure=False) client.auth(my_jid.getNode(), self.uasecret, resource=my_jid.getResource()) for jid in request.jid_list(): stripped_to = jid.strip() message = xmpppy.protocol.Message(frm=xmpp_username, to=stripped_to, body=request.body(), typ=request.type()) client.send(message) response.add_status(xmpp_service_pb.XmppMessageResponse.NO_ERROR)
def startXMPP(self): m = mind.getMind() xmpp_info = m.getXMPPLoginInfo() jid=xmpp.protocol.JID(xmpp_info['username'] + '/pyTivo') cl=xmpp.Client( server=xmpp_info['server'], port=xmpp_info['port'], debug=[], ) self.__logger.debug('Connecting to %s:%s' % (xmpp_info['server'], xmpp_info['port'])) cl.connect() cl.RegisterHandler('message', self.processMessage) self.__logger.debug('Loging in as %s/pyTivo' % xmpp_info['username']) cl.auth(user=jid.getNode(), password=config.get_server('tivo_password'), resource='pyTivo') cl.sendInitPresence(requestRoster=0) for user_name in xmpp_info['presence_list']: self.__logger.debug('Sending presence to %s' % user_name) jid = xmpp.protocol.JID(user_name) cl.sendPresence(jid) t = threading.Thread(target=self.processXMPP, args=(cl,)) t.setDaemon(True) t.start()
def __init__(self): try: with open(secrets_filename, "r") as f: data = f.read() except: err = "Error processing {} - make sure to fill in {} and reading the " + \ "instructions in discover_gchat_id.py".format(secrets_filename, secrets_filename) with open(secrets_filename, "w") as f: f.write(document) raise Exception(err) try: conf = yaml.load(data) self.automation_user = conf["automation_user"] self.automation_password = conf["automation_password"] self.automation_server = conf["automation_server"] self.automation_port = conf["automation_port"] self.destination_user = conf["destination_user"] except: raise Exception("Error parsing {}!".format(secrets_filename)) if self.automation_user is None or self.automation_password is None or self.automation_server is None or \ self.automation_port is None or self.destination_user is None: raise Exception( "Error parsing {} - not all fields have been filled in!". format(secrets_filename)) server = (self.automation_server, self.automation_port) jid = xmpp.JID(self.automation_user) self.connection = xmpp.Client(jid.getDomain(), debug=[]) self.connection.connect(server) result = self.connection.auth(jid.getNode(), self.automation_password) self.connection.sendInitPresence()
def start(self, gmail_account, password): jid = xmpp.JID(gmail_account) user, server, password = jid.getNode(), jid.getDomain(), password self.conn = xmpp.Client(server, debug=self.debug) #talk.google.com conres = self.conn.connect(server=(self.server_host, self.server_port)) if not conres: print "Unable to connect to server %s!" % server sys.exit(1) if conres <> 'tls': print "Warning: unable to estabilish secure connection - TLS failed!" authres = self.conn.auth(user, password) if not authres: print "Unable to authorize on %s - Please check your name/password." % server sys.exit(1) if authres <> "sasl": print "Warning: unable to perform SASL auth os %s. Old authentication method used!" % server self.conn.RegisterHandler("message", self.controller) self.conn.RegisterHandler('presence', self.presenceHandler) self.conn.sendInitPresence() self.setState(self.show, self.status) print "Bot started." self.GoOn()