Commits

Anonymous committed ae76b05

pep8 compilant code + some TODO comments in the code

Comments (0)

Files changed (4)

chatbot_gtalk_setup.py

     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(
+            chatbotini.CACHEDIR + str(email) + "_1.txt", "r")
         frace = cache.read()
         cache.close()
-        if frace.count("cuantos años tienes")>0 or frace.count(
-            "y cual es tu edad"):
+        if frace.count("cuantos años tienes") > 0 or frace.count(
+                "y cual es tu edad"):
             rpta = 1
     except IOError:
         pass
     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:
     logtime = chatbotini.now()
     text = mess.getBody()
     #so you can convert to lower case
+    # TODO: find a cleaner solution
     text = text.replace(
-                    u"\xe1", u"a").replace(
-                    u"\xe9", u"e").replace(
-                    u"\xed", u"i").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 ")
+                        u"\xfa", u"u").replace(
+                            "+", " mas ")
     #text = text.replace(u"\xbf",u"") ##u"\xbf" = ¿
     user = mess.getFrom()
     user.lang = "en"   # dup
         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:
                         estoy conociendo!"""
             except:
                 pass
-        message = xmpp.Message(to=mess.getFrom(),
-                 body=extramsg.encode("utf-8") + remsg, typ="chat")
+        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
     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
 
             #print data
             conn = sqlite3.connect("show_unanswered.bd")
             conn_cursor = conn.cursor()
+            # TODO: rewrite using % to avoid sql injection
             conn_cursor.execute(
-            """insert into preguntas values(?,?,?,?,?)""", data)
+                """insert into preguntas values(?,?,?,?,?)""", data)
             conn.commit()
             conn_cursor.close()
             conn.close()
 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")
+chatbotini.connection_log(
+    "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")
+        "No ha sido posible conectar al servidor jabber (%s)\n" % (
+            chatbotini.SERVER), "gtalk")
     chatbotini.connection_log("Terminando\n\n\n", "gtalk")
     sys.exit(1)
 
 chatbotini.connection_log("Autenticando\n", "gtalk")
 
 if not AUTHRES:
-    print "No se puede autorizar en %s - comprobar " % chatbotini.SERVER + \
-    "nombre de usuario / contrasenia."
+    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)

chatbot_msn_setup.py

         """
         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)
 
     try:
         FDS = select.select(INFD, OUTFD, [], 5)
     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__

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)})
-
-