Commits

Alfonso de la Guarda Reyes committed 650b7cc Merge

Comments (0)

Files changed (4)

chatbot_gtalk_setup.py

         try:
             if presence.getFrom().getStripped() != chatbotini.LOGINGTALK:
                 print "-" * 100
-                print presence.getFrom().getStripped(
-                ), ",", presence.getFrom(
-                ).getResource(
-                ), ",", presence.getType(
-                ), ",", presence.getStatus(
-                ), ",", presence.getShow()
+                print "%s,%s,%s,%s,%s" % (
+                    presence.getFrom().getStripped(),
+                    presence.getFrom().getResource(),
+                    presence.getType(),
+                    presence.getStatus(),
+                    presence.getShow())
                 print "~" * 100
 
         except UnicodeEncodeError:
             print "-" * 100
-            print presence.getFrom().getStripped(
-            ), ",", presence.getFrom().getResource(
-            ), ",", presence.getType(
-            ), ",", "No se puede mostrar nick", ",", presence.getShow()
+            print "%s,%s,%s,No se puede mostrar nick,%s" % (
+                presence.getFrom().getStripped(),
+                presence.getFrom().getResource(),
+                presence.getType(),
+                presence.getShow())
             print "~" * 100
+
         if presence.getType() == "subscribe":
             jid = presence.getFrom().getStripped()
             chatbotini.MY_LIST.Authorize(jid)
     try:
         conn.Process(1)
     except KeyboardInterrupt:
-        chatbotini.connection_log("Interrupcion de teclado (Ctrl+C)\n",
-                     "gtalk")
+        chatbotini.connection_log(
+            "Interrupcion de teclado (Ctrl+C)\n", "gtalk")
         disconnect_bot()
     return 1
 
     """
     rpta = 0
     try:
-        cache = open(chatbotini.CACHEDIR + str(
-        email) + "_1.txt", "r")
+        cache = open(
+            "%s%s_1.txt" % (chatbotini.CACHEDIR, str(email)) , "r")
         frace = cache.read()
-        cache.close()
-        if frace.count("cuantos años tienes")>0 or frace.count(
-            "y cual es tu edad"):
-            rpta = 1
+
     except IOError:
         pass
+
+    else:
+        if frace.count("cuantos años tienes") > 0 or \
+                frace.count("y cual es tu edad"):
+            rpta = 1
+
+    finally:
+        cache.close()
+
     return rpta
 
 
     Writes to the cache
     """
     try:
-        cache = open(chatbotini.CACHEDIR + str(
-        email) + "_1.txt", "w")
+        cache = open(
+            chatbotini.CACHEDIR + str(email) + "_1.txt", "w")
         cache.write(message)
-        cache.close()
+
     except IOError:
         pass
 
+    finally:
+        cache.close()
+
 
 def rpta_gtalk(conn, mess):
     """
     logtime = chatbotini.now()
     text = mess.getBody()
     #so you can convert to lower case
-    text = text.replace(
-                    u"\xe1", u"a").replace(
-                    u"\xe9", u"e").replace(
-                    u"\xed", u"i").replace(
-                    u"\xf3", u"o").replace(
-                    u"\xfa", u"u").replace(
-                    "+", " mas ")
+
+    substitutions = [
+        (u"\xe1", u"a"),
+        (u"\xe9", u"e"),
+        (u"\xed", u"i"),
+        (u"\xf3", u"o"),
+        (u"\xfa", u"u"),
+        ("+", " mas ")]
+    for search, replacement in substitutions:
+        text = text.replace(search, replacement)
+
     #text = text.replace(u"\xbf",u"") ##u"\xbf" = ¿
     user = mess.getFrom()
     user.lang = "en"   # dup
     senderemail = user.getStripped()
+
     try:
         message = text.lower().replace("\n", " ").encode("utf-8")
     except AttributeError:
         message = ""
+
     # Log query message
     registrochat(("%s <<< %s\n" % (logtime, message)), senderemail)
-    remsg = chatbotini.action_process(message, senderemail,
-        conn=CONN, mess=mess)
+
+    remsg = chatbotini.action_process(
+        message, senderemail, conn=CONN, mess=mess)
+
     #stores the questions that have no answers
-    record_questions_unanswered(message, remsg, senderemail,
-                     logtime[1:11], logtime[12:20])
+    record_questions_unanswered(
+        message, remsg, senderemail, logtime[1:11], logtime[12:20])
+
     if remsg:
         extramsg = u""
+
         if cache_read_rpta(senderemail) == 1:
+            # try except really needed?
             try:
                 anios = int(text)
-                if anios < 5:
-                    extramsg = u"""Tan joven y ya sabes escribir?"""
-                if anios > 95:
-                    extramsg = u"""Vaya eres la persona más longeva que
-                        estoy conociendo!"""
+
+            # TODO: find exception type
             except:
                 pass
-        message = xmpp.Message(to=mess.getFrom(),
-                 body=extramsg.encode("utf-8") + remsg, typ="chat")
+
+            else:
+                if anios < 5:
+                    extramsg = u"Tan joven y ya sabes escribir?"
+                if anios > 95:
+                    extramsg = (u"Vaya eres la persona más longeva que" +
+                                u"estoy conociendo!")
+
+        message = xmpp.Message(
+            to=mess.getFrom(), body=extramsg.encode("utf-8") + remsg,
+            typ="chat")
         CONN.send(unicode(message).encode("utf-8").replace(r"\n", "\n"))
+
     # Log response message
+    # TODO: move unneded code out of the try block
     try:
         message = message.getBody()
-        registrochat(("%s >>> %s\n" % (logtime, message.encode(
-        "utf-8"))), senderemail)
+        registrochat(
+            ("%s >>> %s\n" % (logtime, message.encode("utf-8"))), senderemail)
+
     except AttributeError:
         pass
 
             conn = sqlite3.connect("show_unanswered.bd")
             conn_cursor = conn.cursor()
             conn_cursor.execute(
-            """insert into preguntas values(?,?,?,?,?)""", data)
+                """insert into preguntas values(?,?,?,?,?)""", data)
             conn.commit()
             conn_cursor.close()
             conn.close()
 
-print "\n\n* ChatBot Gtalk Client *\n"
-CONN = xmpp.Client(chatbotini.SERVER, debug=[])
-SHOW = xmpp.Presence()
-# Show: dnd, away, ax
-SHOW.setShow("ax")
-CONRES = CONN.connect(server=("talk.google.com", 5223))
-chatbotini.connection_log("Iniciando sesion\n", "gtalk")
-chatbotini.connection_log("Conectando al servidor (talk.google.com)\n",
-    "gtalk")
-
-if not CONRES:
-    print "No se puede conectar al servidor %s!" % chatbotini.SERVER
+if __name__ == "__main__":
+    print "\n\n* ChatBot Gtalk Client *\n"
+    CONN = xmpp.Client(chatbotini.SERVER, debug=[])
+    SHOW = xmpp.Presence()
+
+    # Show: dnd, away, ax
+    SHOW.setShow("ax")
+    CONRES = CONN.connect(server=("talk.google.com", 5223))
+
+    chatbotini.connection_log("Iniciando sesion\n", "gtalk")
     chatbotini.connection_log(
-    "No ha sido posible conectar al servidor jabber (%s)\n" % (
-                                            chatbotini.SERVER), "gtalk")
-    chatbotini.connection_log("Terminando\n\n\n", "gtalk")
-    sys.exit(1)
-
-if CONRES != "tls":
-    print """Advertencia: no se puede estabilizar conexion segura -
-        TLS fallo"""
-AUTHRES = CONN.auth(chatbotini.LOGINGTALK.split("@")[0],
-                    chatbotini.LOGINPASSWORD,
-                    chatbotini.BOTNAME)
-chatbotini.connection_log("Autenticando\n", "gtalk")
-
-if not AUTHRES:
-    print "No se puede autorizar en %s - comprobar " % chatbotini.SERVER + \
-    "nombre de usuario / contrasenia."
-    chatbotini.connection_log("Login/Password incorrectos\n", "gtalk")
-    chatbotini.connection_log("Terminando\n\n\n", "gtalk")
-    sys.exit(1)
-
-if AUTHRES != "sasl":
-    print """Warning: SASL authentication can not you% s.
-    Old method of authentication used!""" % chatbotini.SERVER
-CONN.RegisterHandler("message", rpta_gtalk)
-CONN.RegisterHandler("presence", present_controller)
-CONN.sendInitPresence()
-CONN.send(SHOW)
-
-chatbotini.MY_LIST = CONN.getRoster()
-
-print "Gtalk Login OK"
-chatbotini.connection_log("Sesion iniciada\n", "gtalk")
-
-# Starts Application
-loop_start(CONN)
+        "Conectando al servidor (talk.google.com)\n", "gtalk")
+
+    if not CONRES:
+        print "No se puede conectar al servidor %s!" % chatbotini.SERVER
+
+        chatbotini.connection_log(
+            "No ha sido posible conectar al servidor jabber (%s)\n" % (
+                chatbotini.SERVER), "gtalk")
+        chatbotini.connection_log("Terminando\n\n\n", "gtalk")
+
+        sys.exit(1)
+
+    if CONRES != "tls":
+        print (
+            "Advertencia: no se puede estabilizar conexion segura - TLS fallo")
+
+    AUTHRES = CONN.auth(chatbotini.LOGINGTALK.split("@")[0],
+                        chatbotini.LOGINPASSWORD,
+                        chatbotini.BOTNAME)
+
+    chatbotini.connection_log("Autenticando\n", "gtalk")
+
+    if not AUTHRES:
+        print ("No se puede autorizar en %s - comprobar " +
+               "nombre de usuario / contrasenia.") % chatbotini.SERVER
+
+        chatbotini.connection_log("Login/Password incorrectos\n", "gtalk")
+        chatbotini.connection_log("Terminando\n\n\n", "gtalk")
+
+        sys.exit(1)
+
+    if AUTHRES != "sasl":
+        print """Warning: SASL authentication can not you% s.
+        Old method of authentication used!""" % chatbotini.SERVER
+
+    CONN.RegisterHandler("message", rpta_gtalk)
+    CONN.RegisterHandler("presence", present_controller)
+    CONN.sendInitPresence()
+    CONN.send(SHOW)
+
+    chatbotini.MY_LIST = CONN.getRoster()
+
+    print "Gtalk Login OK"
+    chatbotini.connection_log("Sesion iniciada\n", "gtalk")
+
+    # Starts Application
+    loop_start(CONN)

chatbot_msn_setup.py

 import select
 import urllib
 import time
-from primary import chatbotini
+
 from msn_lib import msnlib
 from msn_lib import msncb
 
+from primary import chatbotini
+
 # Basic classes
 MSN = msnlib.msnd()
 MSN.cb = msncb.cb()
         Performs the chat log.
         """
         if CONFIG["log history"]:
-            logfile = CONFIG["history directory"] + "/" + email
+            logfile = "%s/%s" % (CONFIG["history directory"], email)
             if logtype == "in":
-                lines = chatbotini.now() + " <<< " + str(msg) + "\n"
+                lines = "%s <<< %s\n" % (chatbotini.now(), str(msg))
             elif logtype == "out":
                 lines = chatbotini.now() + " >>> " + str(msg) + "\n"
+                lines = "%s >>> %s\n" % (chatbotini.now(), str(msg))
 
             file_dict = open(logfile, "a")
             file_dict.write(lines)
         """
         print "Closing"
         chatbotini.connection_log("Sesion terminada\n\n\n", "msn")
+
         try:
-            try:
-                MSN.disconnect()
-            except:
-                pass
+            MSN.disconnect()
+
+        # TODO: Add exception type
         except:
             pass
+
         sys.exit(code)
 
 
             desc = "Unknown"
         else:
             desc = msncb.error_table[errno]
+
         desc = "\rServer sent error %d: %s\n" % (errno, desc)
         print desc
+
         msncb.cb_err(md1, errno, params)
 
     def cb_adding(self, md1, typedat, tid, params):
         """
         plist = params.split(" ")
         typedat = plist[0]
+
         if typedat == "RL" or typedat == "FL":
             email = plist[2]
             nick = urllib.unquote(plist[3])
+
         if typedat == "RL":
-            out = "\r" + ("%s (%s) " % (email, nick)
-            ) + "has added you to his contact list"
+            out = "\r%s (%s) has added you to his contact list" % (email, nick)
             print out
+
             email = params.split(" ")[2]
             MSN.useradd(email)  # Automatically adds the user
+
             try:
                 MSN.userunblock(email.strip())
+
             except KeyError:
                 pass
+
         elif typedat == "FL":
-            out = "\r" + ("%s (%s) " % (email, nick)) + """has
-            been added to your contact list"""
+            out = "\r%s (%s) has been added to your contact list" % (
+                email, nick)
             print out
+
         msncb.cb_add(md1, typedat, tid, params)
 
     def cb_messages(self, md1, typedat, tid, params, sbd):
         lines = params.split("\n")
         headers = {}
         eoh = 0
+
         for line in lines:
             # End of headers
             if line == "\r":
                 break
+
             tvv = line.split(":", 1)
             typedat = tvv[0]
             value = tvv[1].strip()
             headers[typedat] = value
             eoh += 1
+
         eoh += 1
 
         # Handle special hotmail messages
         if email == "Hotmail":
             if not "Content-Type" in headers:
                 return
+
             hotmail_info = {}
+
             # Parse the body
             for line in lines:
                 line = line.strip()
+
                 if not line:
                     continue
+
                 tvv = line.split(":", 1)
                 typedat = tvv[0]
                 value = tvv[1].strip()
                 hotmail_info[typedat] = value
+
             msnlib.debug(params)
-            if headers["Content-Type"
-            ] == "text/x-msmsgsinitialemailnotification; charset=UTF-8":
+
+            if headers["Content-Type"] == ("text/x-msmsgsinitialemail" +
+                                           "notification; charset=UTF-8"):
                 newmsgs = int(hotmail_info["Inbox-Unread"])
+
                 if not newmsgs:
                     return
-                print "\rYou have %s unread email(s)" % str(newmsgs) \
-                    + " in your Hotmail account"
-            elif headers["Content-Type"
-            ] == "text/x-msmsgsemailnotification; charset=UTF-8":
+
+                print ("\rYou have %s unread email(s)" +
+                       " in your Hotmail account") % str(newmsgs)
+
+            elif headers["Content-Type"] == ("text/" +
+                                             "x-msmsgsemailnotification;" +
+                                             " charset=UTF-8"):
                 from_name = hotmail_info["From"]
                 from_addr = hotmail_info["From-Addr"]
                 subject = hotmail_info["Subject"]
-                print "\rYou have just received an email in your" + \
-                    " Hotmail account:"
+
+                print ("\rYou have just received an email in your" +
+                       " Hotmail account:")
                 print "\r\tFrom: %s (%s)" % (from_name, from_addr)
                 print "\r\tSubject: %s" % subject
             return
 
-        if "Content-Type" in headers and headers[
-            "Content-Type"] == "text/x-msmsgscontrol":
+        if "Content-Type" in headers and \
+                headers["Content-Type"] == "text/x-msmsgscontrol":
             nick = USEF_FUNCT.emailtonick(email)
             if not nick:
                 nick = email
+
             if not "typing" in MSN.users[email].priv:
                 MSN.users[email].priv["typing"] = 0
+
             if not MSN.users[email].priv["typing"] and email not in IGNORED:
                 # When typing
                 pass
+
             MSN.users[email].priv["typing"] = time.time()
-        elif "Content-Type" in headers and headers[
-            "Content-Type"] == "text/x-clientcaps":
+
+        elif "Content-Type" in headers and \
+                headers["Content-Type"] == "text/x-clientcaps":
             pass
-        elif "Content-Type" in headers and headers[
-            "Content-Type"] == "text/x-keepalive":
+
+        elif "Content-Type" in headers and \
+                headers["Content-Type"] == "text/x-keepalive":
             pass
+
         else:
             # Messages
             MSN.users[email].priv["typing"] = 0
             disp_message(email, lines, eoh)
+
             if len(HISTORY_BUFFER) > CONFIG["history size"]:
                 del(HISTORY_BUFFER[0])
+
             HISTORY_BUFFER.append((time.time(), email, lines[eoh:]))
+
         LAST_RECEIVED = email
         msncb.cb_msg(md1, type, tid, params, sbd)
 
         """
         When the server disconnect us from MSN.
         """
-        print "\rServer sent disconnect (probably you logged in somewhere else)"
+        print ("\rServer sent disconnect" +
+               " (probably you logged in somewhere else)")
+
         USEF_FUNCT.quit()
         msncb.cb_out(md1, type, tid, params)
 
         """
         email = tid
         nick = USEF_FUNCT.emailtonick(email)
+
         if not nick:
             nick = email
+
         if sbd.emails and email != sbd.emails[0]:
             first_nick = USEF_FUNCT.emailtonick(sbd.emails[0])
+
             if not first_nick:
                 first_nick = sbd.emails[0]
+
             print "\rUser %s has joined the chat with %s" % (nick, first_nick)
+
         elif len(sbd.msgqueue) > 0:
             print "\rFlushing messages for %s:" % nick
+
             for msg in sbd.msgqueue:
                 print nick, msg
+
         msncb.cb_joi(md1, type, tid, params, sbd)
 
 
     end of your header.
     """
     message = ""
+
+    substitutions = [
+        ("\xc3\xb1", "n"),
+        ("\xc3\xa1", "a"),
+        ("\xc3\xa9", "e"),
+        ("\xc3\xad", "i"),
+        ("\xc3\xb3", "o"),
+        ("\xc3\xba", "u")]
+
     for line in lines[-1:]:
-        line = line.replace(
-                    "\xc3\xb1", "n").replace(
-                    "\xc3\xa1", "a").replace(
-                    "\xc3\xa9", "e").replace(
-                    "\xc3\xad", "i").replace(
-                    "\xc3\xb3", "o").replace(
-                    "\xc3\xba", "u")
+        for search, replacement in substitutions:
+            line = line.replace(search, replacement)
+
         message += line.strip() + " "
+
     message = message.strip().decode("utf-8", "ignore")
+
     # Log query message
     USEF_FUNCT.do_login(email, "in", message.encode("utf-8"))
     message_to_send = chatbotini.action_process(message, email, msn=MSN)
+
+    # We really need to add empty string??
     extramsg = u""
     message_to_send += extramsg.encode("utf-8")
+
     MSN.sendmsg(email, message_to_send.replace(r"\n", "\n"))
+
     # Log response message
     USEF_FUNCT.do_login(email, "out", message_to_send)
 
-#classes start
-USEF_FUNCT = UsefFunct()
-SERV_DISCON = ServDiscon()
+if __name__ == "__main__":
+    # TODO: split into functions
+    # classes start
+    USEF_FUNCT = UsefFunct()
+    SERV_DISCON = ServDiscon()
 
-MSN.cb.out = SERV_DISCON.cb_disconnect
-MSN.cb.msg = SERV_DISCON.cb_messages
-MSN.cb.joi = SERV_DISCON.cb_join
-MSN.cb.err = SERV_DISCON.cb_errors
-MSN.cb.add = SERV_DISCON.cb_adding
+    MSN.cb.out = SERV_DISCON.cb_disconnect
+    MSN.cb.msg = SERV_DISCON.cb_messages
+    MSN.cb.joi = SERV_DISCON.cb_join
+    MSN.cb.err = SERV_DISCON.cb_errors
+    MSN.cb.add = SERV_DISCON.cb_adding
 
+    print "\n\n* ChatBot MSN Client *\n"
+    chatbotini.connection_log("Iniciando sesion\n", "msn")
 
-print "\n\n* ChatBot MSN Client *\n"
-chatbotini.connection_log("Iniciando sesion\n", "msn")
+    # First, the configuration
+    print "Loading config... "
 
-# First, the configuration
-print "Loading config... "
+    CONFIG = USEF_FUNCT.getconfigure()
+    CONFIG["profile"] = None
 
-CONFIG = USEF_FUNCT.getconfigure()
-CONFIG["profile"] = None
+    # Set the mandatory values
+    MSN.email = CONFIG["email"]
+    MSN.pwd = CONFIG["password"]
 
-# Set the mandatory values
-MSN.email = CONFIG["email"]
-MSN.pwd = CONFIG["password"]
-
-if not "history size" in CONFIG:
-    CONFIG["history size"] = 10
-else:
-    try:
-        CONFIG["history size"] = int(CONFIG["history size"])
-    except:
-        print "history size must be integer, using default"
+    if not "history size" in CONFIG:
         CONFIG["history size"] = 10
 
-# Input history size
-if not "input history size" in CONFIG:
-    CONFIG["input history size"] = 10
-else:
-    try:
-        CONFIG["history size"] = int(CONFIG["history size"])
-    except:
-        print "input history size must be integer, using default"
+    else:
+        try:
+            CONFIG["history size"] = int(CONFIG["history size"])
+
+        except:
+            print "history size must be integer, using default"
+            CONFIG["history size"] = 10
+
+    # Input history size
+    if not "input history size" in CONFIG:
         CONFIG["input history size"] = 10
 
-# Initial status
-CONFIG["initial status"] = "online"
+    else:
+        try:
+            CONFIG["history size"] = int(CONFIG["history size"])
+
+        except:
+            print "input history size must be integer, using default"
+            CONFIG["input history size"] = 10
 
-# Debug
-CONFIG["debug"] = 0
+    # Initial status
+    CONFIG["initial status"] = "online"
 
-# Log history
-CONFIG["log history"] = 1
+    # Debug
+    CONFIG["debug"] = 0
 
-# History directory
-CONFIG["history directory"] = chatbotini.LOGDIR + "/msn"
+    # Log history
+    CONFIG["log history"] = 1
 
-# Show realnick changes
-if not "show realnick changes" in CONFIG:
-    CONFIG["show realnick changes"] = 0
-elif CONFIG["show realnick changes"] != "yes":
-    CONFIG["show realnick changes"] = 0
+    # History directory
+    CONFIG["history directory"] = chatbotini.LOGDIR + "/msn"
 
-# Encoding
-if not "encoding" in CONFIG:
-    if "LC_ALL" in os.environ and os.environ["LC_ALL"]:
-        CONFIG["encoding"] = os.environ["LC_ALL"]
-    elif "LANG" in os.environ and os.environ["LANG"]:
-        CONFIG["encoding"] = os.environ["LANG"]
-    else:
-        CONFIG["encoding"] = "iso-8859-1"
-MSN.encoding = CONFIG["encoding"]
+    # Show realnick changes
+    if not "show realnick changes" in CONFIG:
+        CONFIG["show realnick changes"] = 0
 
-print "Done!"
+    elif CONFIG["show realnick changes"] != "yes":
+        CONFIG["show realnick changes"] = 0
 
-# Set or void the debug
-if not CONFIG["debug"]:
-    msnlib.debug = USEF_FUNCT.null
-    msncb.debug = USEF_FUNCT.null
+    # Encoding
+    if not "encoding" in CONFIG:
+        if "LC_ALL" in os.environ and os.environ["LC_ALL"]:
+            CONFIG["encoding"] = os.environ["LC_ALL"]
 
-# Login to msn
-print "Logging in... "
-chatbotini.connection_log("Autenticando\n", "msn")
-try:
-    MSN.login()
-    print "Done!"
-except KeyboardInterrupt:
-    chatbotini.connection_log("Interrupcion de teclado (Ctrl + C)\n", "msn")
-    USEF_FUNCT.quit()
-except socket.error, info:
-    print "Network error: " + str(info)
-    print "Closing"
-    chatbotini.connection_log("Error de red (%s)\n" % str(info), "msn")
-    chatbotini.connection_log("Terminando\n\n\n", "msn")
-    sys.exit(1)
-except Exception, info:
-    print "Exception logging in"
-    print "Error: %s" % str(info)
-    print "Closing"
-    chatbotini.connection_log(str(info) + "\n", "msn")
-    chatbotini.connection_log("Terminando\n\n\n", "msn")
-    sys.exit(1)
-
-
-# Call sync to get the lists and refresh
-print "Sending user list request... "
-if MSN.sync():
-    print "Done!"
-    LIST_COMPLETE = 0
-else:
-    print "Error syncing users"
+        elif "LANG" in os.environ and os.environ["LANG"]:
+            CONFIG["encoding"] = os.environ["LANG"]
 
+        else:
+            CONFIG["encoding"] = "iso-8859-1"
 
-# Global variables
-HISTORY_BUFFER = []    # History buffer
-LAST_RECEIVED = ""   # Email of the last person we received a message from
-IGNORED = []         # People being locally ignored
+    MSN.encoding = CONFIG["encoding"]
 
-# Loop
-while 1:
-    FDS = MSN.pollable()
-    INFD = FDS[0]
-    OUTFD = FDS[1]
-    INFD.append(sys.stdin)
+    print "Done!"
+
+    # Set or void the debug
+    if not CONFIG["debug"]:
+        msnlib.debug = USEF_FUNCT.null
+        msncb.debug = USEF_FUNCT.null
 
+    # Login to msn
+    print "Logging in... "
+    chatbotini.connection_log("Autenticando\n", "msn")
     try:
-        FDS = select.select(INFD, OUTFD, [], 5)
+        MSN.login()
+        print "Done!"
+
     except KeyboardInterrupt:
-        chatbotini.connection_log("Interrupcion de teclado (Ctrl + C)\n", "msn")
+        chatbotini.connection_log(
+            "Interrupcion de teclado (Ctrl + C)\n", "msn")
         USEF_FUNCT.quit()
 
-    for comp in FDS[0] + FDS[1]:        # see msnlib.msnd.pollable.__doc__
+    except socket.error, info:
+        print "Network error: %s" % str(info)
+        print "Closing"
+
+        chatbotini.connection_log("Error de red (%s)\n" % str(info), "msn")
+        chatbotini.connection_log("Terminando\n\n\n", "msn")
+        sys.exit(1)
+
+    except Exception, info:
+        print "Exception logging in"
+        print "Error: %s" % str(info)
+        print "Closing"
+
+        chatbotini.connection_log(str(info) + "\n", "msn")
+        chatbotini.connection_log("Terminando\n\n\n", "msn")
+
+        sys.exit(1)
+
+    # Call sync to get the lists and refresh
+    print "Sending user list request... "
+    if MSN.sync():
+        print "Done!"
+        LIST_COMPLETE = 0
+
+    else:
+        print "Error syncing users"
+
+    # Global variables
+    HISTORY_BUFFER = []    # History buffer
+    LAST_RECEIVED = ""   # Email of the last person we received a message from
+    IGNORED = []         # People being locally ignored
+
+    # Loop
+    while 1:
+        FDS = MSN.pollable()
+        INFD = FDS[0]
+        OUTFD = FDS[1]
+        INFD.append(sys.stdin)
+
         try:
-            MSN.read(comp)
-
-            # See if we got all the user list, so we can
-            # change our initial status
-            if not LIST_COMPLETE and MSN.lst_total == MSN.syn_total:
-                LIST_COMPLETE = 1
-                if MSN.change_status(CONFIG["initial status"]):
-                    print "\rStatus set to %s" % CONFIG["initial status"]
-                    chatbotini.connection_log("Sesion iniciada\n", "msn")
+            FDS = select.select(INFD, OUTFD, [], 5)
+
+        except KeyboardInterrupt:
+            chatbotini.connection_log(
+                "Interrupcion de teclado (Ctrl + C)\n", "msn")
+            USEF_FUNCT.quit()
+
+        for comp in FDS[0] + FDS[1]:        # see msnlib.msnd.pollable.__doc__
+            try:
+                MSN.read(comp)
+
+                # See if we got all the user list, so we can
+                # change our initial status
+                if not LIST_COMPLETE and MSN.lst_total == MSN.syn_total:
+                    LIST_COMPLETE = 1
+
+                    if MSN.change_status(CONFIG["initial status"]):
+                        print "\rStatus set to %s" % CONFIG["initial status"]
+                        chatbotini.connection_log("Sesion iniciada\n", "msn")
+
+                    else:
+                        print "\rError setting status: unknown status %s" % (
+                            CONFIG["initial status"])
+
+                    # Re-adding and Unblocking users just in case
+                    contacts = MSN.users
+                    for e_mail in contacts:
+                        MSN.useradd(e_mail)
+                        try:
+                            MSN.userunblock(e_mail)
+
+                        except KeyError:
+                            pass
+
+                # If not online then change the status
+                if MSN.status != "NLN":
+                    MSN.change_status("online")
+
+            except socket.error, err:
+                chatbotini.connection_log("Error en los sockets\n", "msn")
+
+                if comp != MSN:
+                    if comp.msgqueue:
+                        nick = USEF_FUNCT.emailtonick(comp.emails[0])
+                        print ("\rConnection with %s closed - the following" +
+                               "messages couldn't be sent:") % (nick)
+
+                        for mssage in comp.msgqueue:
+                            print "\t>>> %s" % mssage
+
+                    MSN.close(comp)
+
                 else:
-                    print "\rError setting status: unknown status %s" % CONFIG[
-                    "initial status"]
-                # Re-adding and Unblocking users just in case
-                contacts = MSN.users
-                for e_mail in contacts:
-                    MSN.useradd(e_mail)
-                    try:
-                        MSN.userunblock(e_mail)
-                    except KeyError:
-                        pass
-            # If not online then change the status
-            if MSN.status != "NLN":
-                MSN.change_status("online")
-
-        except socket.error, err:
-            chatbotini.connection_log("Error en los sockets\n", "msn")
-            if comp != MSN:
-                if comp.msgqueue:
-                    nick = USEF_FUNCT.emailtonick(comp.emails[0])
-                    print """\rConnection with %s closed - the following
-                    messages couldn't be sent:""" % (nick)
-                    for mssage in comp.msgqueue:
-                        print "\t>>> " + mssage
-                MSN.close(comp)
-            else:
-                print "\nMain socket closed (%s)" % str(err)
-                chatbotini.connection_log(
-                "Se cerro el socket principal\n", "msn")
-                USEF_FUNCT.quit(1)
+                    print "\nMain socket closed (%s)" % str(err)
+
+                    chatbotini.connection_log(
+                        "Se cerro el socket principal\n", "msn")
+
+                    USEF_FUNCT.quit(1)

primary/chatbotini.py

 """
 import os
 from datetime import datetime
+
 import aiml
 import xmlfunctions
 

primary/xmlfunctions.py

         Static method to wrap_dict a dictionary recursively as an DictionaryXml
         """
         if isinstance(elem, dict):
-            return DictionaryXml((k, DictionaryXml.wrap_dict(v))
-                for (k, v) in elem.iteritems())
+            return DictionaryXml(
+                (k, DictionaryXml.wrap_dict(v)) for (k, v) in elem.iteritems())
         elif isinstance(elem, list):
             return [DictionaryXml.wrap_dict(v) for v in elem]
         else:
         Defined function to help unwrap_dict
         """
         if isinstance(elem, dict):
-            return dict((k, DictionaryXml._unwrap_dict(v))
+            return dict(
+                (k, DictionaryXml._unwrap_dict(v))
                 for (k, v) in elem.iteritems())
         elif isinstance(elem, list):
             return [DictionaryXml._unwrap_dict(v) for v in elem]
     """
     Defined function to help dicttoxml
     """
-    assert type(elemdict) is not type([])
+    assert not isinstance(elemdict, list)
 
     if isinstance(elemdict, dict):
         for (tag, child) in elemdict.iteritems():
             if str(tag) == '_text':
                 parent.text = str(child)
-            elif type(child) is type([]):
+            elif isinstance(child, list):
                 # iterate through the array and convert
                 for listchild in child:
                     elem = ElementTree.Element(tag)
         newitem = _xmltodict(child, classdict)
         if child.tag in nodedict:
             # found duplicate tag, force a list
-            if type(nodedict[child.tag]) is type([]):
+            if isinstance(nodedict[child.tag], list):
                 # append to existing list
                 nodedict[child.tag].append(newitem)
             else:
     Converts an XML file or ElementTree Element to a dictionary
     """
     # If a string is passed in, try to open it as a file
-    if type(root) == type(''):
+    if isinstance(root, basestring):
         root = ElementTree.parse(root).getroot()
     elif not isinstance(root, ElementTree.Element):
         raise Exception('Expected ElementTree.Element or file path string')
     return classdict({root.tag: _xmltodict(root, classdict)})
-
-