Commits

Alfonso de la Guarda Reyes committed ec003b3

Code Fixes

Comments (0)

Files changed (5)

 
 ROOT_DIR = os.getcwd()
 DIR = '%s/%s.xml' % (ROOT_DIR, "ia_start")
-ARCHI = open(DIR, "r")
-ARCHI.seek(0)
-ARCHIVOS = []
-for line in ARCHI.readlines():
+ARCH = open(DIR, "r")
+ARCH.seek(0)
+ARCHIVES = []
+for line in ARCH.readlines():
     if "<learn>" in line:
         ini = line.find("<learn>") + 7
         fin = line.find("</learn>")
-        ARCHIVOS.append(line[ini:fin])
-ARCHI.close()
-PATTNERS = open(ROOT_DIR + "/questions.txt", "w")
-for archivo in ARCHIVOS:
-    DIR = '%s/%s' % (ROOT_DIR, archivo)
-    PATTNERS.write("\n-----" + archivo + "-----\n" + "\n")
-    ARCHI = open(DIR, "r")
-    ARCHI.seek(0)
-    for line in ARCHI.readlines():
+        ARCHIVES.append(line[ini:fin])
+ARCH.close()
+PARTNERS = open(ROOT_DIR + "/questions.txt", "w")
+for archive in ARCHIVES:
+    DIR = '%s/%s' % (ROOT_DIR, archive)
+    PARTNERS.write("\n-----" + archive + "-----\n" + "\n")
+    ARCH = open(DIR, "r")
+    ARCH.seek(0)
+    for line in ARCH.readlines():
         if "<pattern>" in line:
             ini = line.find("<pattern>") + 9
             fin = line.find("</pattern>")
-            PATTNERS.write(line[ini:fin] + "\n")
-    ARCHI.close()
-PATTNERS.close()
+            PARTNERS.write(line[ini:fin] + "\n")
+    ARCH.close()
+PARTNERS.close()

chatbot_gtalk_setup.py

-#! /usr/bin/env python26
+#! /usr/bin/env python
 #-*- coding: utf-8 -*-
 """
 CHATBOT en Google Talk
 import sqlite3
 
 
-def present_controller(conn, presence):
+def presence_controller(conn, presence):
     """
     Handler for automatically adding users to jabber servers (gtalk).
+    :rtype : Bool
     """
     if presence:
         try:
             chatbotini.MY_LIST.Authorize(jid)
 
 
-def registrochat(message, email):
+def chat_registrar(message, email):
     """
     Logs the chat.
+    :rtype : Bool
     """
     filename = chatbotini.LOGDIR + "/gtalk/" + email
     logfile = open(filename, "a")
 def step_on(conn):
     """
     Keeps the connection alive.
+    :rtype : Bool
     """
     try:
         conn.Process(1)
         chatbotini.connection_log(
             "Interrupcion de teclado (Ctrl+C)\n", "gtalk")
         disconnect_bot()
-    return 1
+    return True
 
 
 def loop_start(conn):
     """
     Starts the loop.
+    :rtype : Bool
     """
     while step_on(conn):
         SHOW.setShow("ax")
 def disconnect_bot():
     """
     Quit and disconnect the bot.
+    :rtype : Bool
     """
     print "Exiting."
     chatbotini.connection_log("Sesion terminada\n\n\n", "gtalk")
     sys.exit(0)
 
 
-def cache_read_rpta(email):
+def cache_read_reply(email):
     """
     Reads the cache
+    :rtype : Bool
     """
-    rpta = 0
+    reply = False
     try:
         cache = open(
             "%s%s_1.txt" % (chatbotini.CACHEDIR, str(email)), "r")
-        frace = cache.read()
+        fraze = cache.read()
     except IOError:
         pass
     else:
-        if frace.count("cuantos años tienes") > 0 or \
-                frace.count("y cual es tu edad"):
-            rpta = 1
+        if fraze.count("cuantos años tienes") > 0 or\
+           fraze.count("y cual es tu edad"):
+            reply = True
         cache.close()
-    return rpta
+    return reply
 
 
-def cache_write_rpta(message, email):
+def cache_write_reply(message, email):
     """
     Writes to the cache
+    :rtype : object
     """
+    cache = False
     try:
         cache = open(
             chatbotini.CACHEDIR + str(email) + "_1.txt", "w")
         cache.write(message)
-
     except IOError:
-        pass
-
+        cache = False
     finally:
         cache.close()
 
 
-def rpta_gtalk(conn, mess):
+def reply_gtalk(conn, mess):
     """
     Respond to messages from gtalk contacts.
     """
-    logtime = chatbotini.now()
+    log_time = chatbotini.now()
     text = mess.getBody()
     #so you can convert to lower case
 
     #text = text.replace(u"\xbf",u"") ##u"\xbf" = ¿
     user = mess.getFrom()
     user.lang = "en"   # dup
-    senderemail = user.getStripped()
+    sender_email = user.getStripped()
 
     try:
         message = text.lower().replace("\n", " ").encode("utf-8")
         message = ""
 
     # Log query message
-    registrochat(("%s <<< %s\n" % (logtime, message)), senderemail)
+    chat_registrar(("%s <<< %s\n" % (log_time, message)), sender_email)
 
-    remsg = chatbotini.action_process(
-        message, senderemail, conn=CONN, mess=mess)
+    re_msg = chatbotini.action_process(
+        message, sender_email, conn=CONN, mess=mess)
 
     #stores the questions that have no answers
     record_questions_unanswered(
-        message, remsg, senderemail, logtime[1:11], logtime[12:20])
-
-    if remsg:
-        extramsg = u""
-
-        if cache_read_rpta(senderemail) == 1:
+        message, sender_email, log_time[1:11], log_time[12:20])
+    if re_msg:
+        extra_msg = u""
+        if cache_read_reply(sender_email):
             # try except really needed?
             try:
-                anios = int(text)
-
-            # TODO: find exception type
-            except:
+                age = int(text)
+            except Exception:
                 pass
-
             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" +
+                if age < 5:
+                    extra_msg = u"Tan joven y ya sabes escribir?"
+                if age > 95:
+                    extra_msg = (u"Vaya eres la persona más longeva que" +
                                 u"estoy conociendo!")
 
         message = xmpp.Message(
-            to=mess.getFrom(), body=extramsg.encode("utf-8") + remsg,
+            to=mess.getFrom(), body=extra_msg.encode("utf-8") + re_msg,
             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)
-
+        chat_registrar(
+            ("%s >>> %s\n" % (log_time, message.encode("utf-8"))), sender_email)
     except AttributeError:
         pass
 
-    cache_write_rpta(remsg, senderemail)
+    cache_write_reply(re_msg, sender_email)
 
 
-def record_questions_unanswered(message, answer, email, date, time):
+def record_questions_unanswered(message, email, date, time):
     """
     Records Unanswered Questions
     """
 
     # Show: dnd, away, ax
     SHOW.setShow("ax")
-    CONRES = CONN.connect(server=("talk.google.com", 5223))
+    CON_RES = 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:
+    if not CON_RES:
         print "No se puede conectar al servidor %s!" % chatbotini.SERVER
 
         chatbotini.connection_log(
 
         sys.exit(1)
 
-    if CONRES != "tls":
+    if CON_RES != "tls":
         print(
             "Advertencia: no se puede estabilizar conexion segura - TLS fallo")
 
-    AUTHRES = CONN.auth(chatbotini.LOGINGTALK.split("@")[0],
-                        chatbotini.LOGINPASSWORD,
-                        chatbotini.BOTNAME)
+    AUTHKEY = CONN.auth(chatbotini.LOGINGTALK.split("@")[0],
+        chatbotini.LOGINPASSWORD,
+        chatbotini.BOTNAME)
 
     chatbotini.connection_log("Autenticando\n", "gtalk")
 
-    if not AUTHRES:
+    if not AUTHKEY:
         print("No se puede autorizar en %s - comprobar " +
               "nombre de usuario / contrasenia.") % chatbotini.SERVER
 
 
         sys.exit(1)
 
-    if AUTHRES != "sasl":
+    if AUTHKEY != "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.RegisterHandler("message", reply_gtalk)
+    CONN.RegisterHandler("presence", presence_controller)
     CONN.sendInitPresence()
     CONN.send(SHOW)
 

chatbot_msn_setup.py

 MSN.cb = msncb.cb()
 
 
-class UsefFunct():
+class Use_Function():
     """
     Useful functions
     """
         """Start"""
         pass
 
-    def do_login(self, email, logtype, msg):
+    def do_login(self, email, log_type, msg):
         """
         Performs the chat log.
         """
         if CONFIG["log history"]:
             logfile = "%s/%s" % (CONFIG["history directory"], email)
-            if logtype == "in":
+            lines = '\n'
+            if log_type == "in":
                 lines = "%s <<< %s\n" % (chatbotini.now(), str(msg))
-            elif logtype == "out":
-                lines = chatbotini.now() + " >>> " + str(msg) + "\n"
+            elif log_type == "out":
                 lines = "%s >>> %s\n" % (chatbotini.now(), str(msg))
 
             file_dict = open(logfile, "a")
             file_dict.write(lines)
             file_dict.close()
 
-    def null(self, samp):
+    def null(self, sample):
         """
         Null function, useful to void debug ones.
         """
         pass
 
-    def emailtonick(self, email):
+    def email_to_nick(self, email):
         """
         Returns a nick using the given email, or None if nobody matches.
         """
         else:
             return None
 
-    def getconfigure(self):
+    def get_configure(self):
         """
         Parses the configuration, returns a var:value dict.
         """
         sys.exit(code)
 
 
-class ServDiscon():
+class Server_Disconnect():
     """
     Server disconnect
     """
         """Start"""
         pass
 
-    def cb_errors(self, md1, errno, params):
+    def cb_errors(self, md1, err_no, params):
         """
         Handles server errors.
         """
-        if not errno in msncb.error_table:
+        if not err_no in msncb.error_table:
             desc = "Unknown"
         else:
-            desc = msncb.error_table[errno]
+            desc = msncb.error_table[err_no]
 
-        desc = "\rServer sent error %d: %s\n" % (errno, desc)
+        desc = "\rServer sent error %d: %s\n" % (err_no, desc)
         print desc
 
-        msncb.cb_err(md1, errno, params)
+        msncb.cb_err(md1, err_no, params)
 
-    def cb_adding(self, md1, typedat, tid, params):
+    def cb_adding(self, md1, data_type, tid, params):
         """
         Handler for adding users.
         """
         plist = params.split(" ")
-        typedat = plist[0]
+        if not data_type:
+            data_type = plist[0]
+        email = ''
+        nick = ''
 
-        if typedat == "RL" or typedat == "FL":
+        if data_type == "RL" or data_type == "FL":
             email = plist[2]
             nick = urllib.unquote(plist[3])
 
-        if typedat == "RL":
+        if data_type == "RL":
             out = "\r%s (%s) has added you to his contact list" % (email, nick)
             print out
 
             except KeyError:
                 pass
 
-        elif typedat == "FL":
+        elif data_type == "FL":
             out = "\r%s (%s) has been added to your contact list" % (
                 email, nick)
             print out
 
-        msncb.cb_add(md1, typedat, tid, params)
+        msncb.cb_add(md1, data_type, tid, params)
 
-    def cb_messages(self, md1, typedat, tid, params, sbd):
+    def cb_messages(self, md1, data_type, tid, params, sbd):
         """
         Handles MSN messages.
         """
         global LAST_RECEIVED
         plist = tid.split(" ")
         email = plist[0]
-
+        if not data_type:
+            data_type = False
         # Parse
         lines = params.split("\n")
         headers = {}
                 break
 
             tvv = line.split(":", 1)
-            typedat = tvv[0]
+            data_type = tvv[0]
             value = tvv[1].strip()
-            headers[typedat] = value
+            headers[data_type] = value
             eoh += 1
 
         eoh += 1
                     continue
 
                 tvv = line.split(":", 1)
-                typedat = tvv[0]
+                data_type = tvv[0]
                 value = tvv[1].strip()
-                hotmail_info[typedat] = value
+                hotmail_info[data_type] = value
 
             msnlib.debug(params)
 
             if headers["Content-Type"] == ("text/x-msmsgsinitialemail" +
                                            "notification; charset=UTF-8"):
-                newmsgs = int(hotmail_info["Inbox-Unread"])
+                new_messages = int(hotmail_info["Inbox-Unread"])
 
-                if not newmsgs:
+                if not new_messages:
                     return
 
                 print("\rYou have %s unread email(s)" +
-                      " in your Hotmail account") % str(newmsgs)
+                      " in your Hotmail account") % str(new_messages)
 
             elif headers["Content-Type"] == ("text/" +
                                              "x-msmsgsemailnotification;" +
                                              " charset=UTF-8"):
                 from_name = hotmail_info["From"]
-                from_addr = hotmail_info["From-Addr"]
+                from_address = hotmail_info["From-Addr"]
                 subject = hotmail_info["Subject"]
 
                 print("\rYou have just received an email in your" +
                       " Hotmail account:")
-                print "\r\tFrom: %s (%s)" % (from_name, from_addr)
+                print "\r\tFrom: %s (%s)" % (from_name, from_address)
                 print "\r\tSubject: %s" % subject
             return
 
         if "Content-Type" in headers and \
                 headers["Content-Type"] == "text/x-msmsgscontrol":
-            nick = USEF_FUNCT.emailtonick(email)
-            if not nick:
-                nick = email
+            nick = USE_FUNCTION.email_to_nick(email)
+            #if not nick:
+            #    nick = email
 
             if not "typing" in MSN.users[email].priv:
                 MSN.users[email].priv["typing"] = 0
         else:
             # Messages
             MSN.users[email].priv["typing"] = 0
-            disp_message(email, lines, eoh)
+            display_message(email, lines, eoh)
 
             if len(HISTORY_BUFFER) > CONFIG["history size"]:
                 del(HISTORY_BUFFER[0])
         print("\rServer sent disconnect" +
               " (probably you logged in somewhere else)")
 
-        USEF_FUNCT.quit()
+        USE_FUNCTION.quit()
         msncb.cb_out(md1, type, tid, params)
 
     def cb_join(self, md1, type, tid, params, sbd):
         Join a conversation and send pending messages.
         """
         email = tid
-        nick = USEF_FUNCT.emailtonick(email)
+        nick = USE_FUNCTION.email_to_nick(email)
 
         if not nick:
             nick = email
 
         if sbd.emails and email != sbd.emails[0]:
-            first_nick = USEF_FUNCT.emailtonick(sbd.emails[0])
+            first_nick = USE_FUNCTION.email_to_nick(sbd.emails[0])
 
             if not first_nick:
                 first_nick = sbd.emails[0]
         msncb.cb_joi(md1, type, tid, params, sbd)
 
 
-def disp_message(email, lines, eoh=0):
+def display_message(email, lines, eoh=0):
     """
     Prints an incoming message and an optional pointer at the
     end of your header.
+    :rtype : Bool
     """
     message = ""
 
     message = message.strip().decode("utf-8", "ignore")
 
     # Log query message
-    USEF_FUNCT.do_login(email, "in", message.encode("utf-8"))
+    USE_FUNCTION.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")
+    extra_message = u""
+    message_to_send += extra_message.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)
+    USE_FUNCTION.do_login(email, "out", message_to_send)
+
 
 if __name__ == "__main__":
     # TODO: split into functions
     # classes start
-    USEF_FUNCT = UsefFunct()
-    SERV_DISCON = ServDiscon()
+    USE_FUNCTION = Use_Function()
+    SERVER_DISCONNECT = Server_Disconnect()
 
-    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 = SERVER_DISCONNECT.cb_disconnect
+    MSN.cb.msg = SERVER_DISCONNECT.cb_messages
+    MSN.cb.joi = SERVER_DISCONNECT.cb_join
+    MSN.cb.err = SERVER_DISCONNECT.cb_errors
+    MSN.cb.add = SERVER_DISCONNECT.cb_adding
 
     print "\n\n* ChatBot MSN Client *\n"
     chatbotini.connection_log("Iniciando sesion\n", "msn")
     # First, the configuration
     print "Loading config... "
 
-    CONFIG = USEF_FUNCT.getconfigure()
+    CONFIG = USE_FUNCTION.get_configure()
     CONFIG["profile"] = None
 
     # Set the mandatory values
 
     # Set or void the debug
     if not CONFIG["debug"]:
-        msnlib.debug = USEF_FUNCT.null
-        msncb.debug = USEF_FUNCT.null
+        msnlib.debug = USE_FUNCTION.null
+        msncb.debug = USE_FUNCTION.null
 
     # Login to msn
     print "Logging in... "
     except KeyboardInterrupt:
         chatbotini.connection_log(
             "Interrupcion de teclado (Ctrl + C)\n", "msn")
-        USEF_FUNCT.quit()
+        USE_FUNCTION.quit()
 
     except socket.error, info:
         print "Network error: %s" % str(info)
         except KeyboardInterrupt:
             chatbotini.connection_log(
                 "Interrupcion de teclado (Ctrl + C)\n", "msn")
-            USEF_FUNCT.quit()
+            USE_FUNCTION.quit()
 
-        for comp in FDS[0] + FDS[1]:        # see msnlib.msnd.pollable.__doc__
+        for comp in FDS[0] + FDS[1]: # see msnlib.msnd.pollable.__doc__
             try:
                 MSN.read(comp)
 
 
                 if comp != MSN:
                     if comp.msgqueue:
-                        nick = USEF_FUNCT.emailtonick(comp.emails[0])
+                        nick = USE_FUNCTION.email_to_nick(comp.emails[0])
                         print("\rConnection with %s closed - the following" +
-                              "messages couldn't be sent:") % (nick)
+                              "messages couldn't be sent:") % nick
 
-                        for mssage in comp.msgqueue:
-                            print "\t>>> %s" % mssage
+                        for message in comp.msgqueue:
+                            print "\t>>> %s" % message
 
                     MSN.close(comp)
 
                     chatbotini.connection_log(
                         "Se cerro el socket principal\n", "msn")
 
-                    USEF_FUNCT.quit(1)
+                    USE_FUNCTION.quit(1)

primary/chatbotini.py

 import aiml
 import xmlfunctions
 
-ELEMENT = xmlfunctions.xmltodict('chatbot_settings.xml')
+ELEMENT = xmlfunctions.xml_to_dict('chatbot_settings.xml')
 
 # Main settings
 LOGINGTALK = ELEMENT['setup']['loginusergtalk']
 
 # Create empty command cache file if doesn't exist
 if not os.path.exists(CACHEDIR + 'mencache.txt'):
-    command_cachefile = open(CACHEDIR + 'mencache.txt', 'w')
-    command_cachefile.write(str({}))
-    command_cachefile.close()
+    command_cache_file = open(CACHEDIR + 'mencache.txt', 'w')
+    command_cache_file.write(str({}))
+    command_cache_file.close()
 
 # Create directories (if missing)
 os.system('mkdir -p %s' % CACHEDIR)
     Returns the current date and time.
     """
     today = datetime.now().strftime('%d/%m/%Y %H:%M:%S')
-    ret = '[%s]' % (today)
+    ret = '[%s]' % today
     return ret
 
 
     """
     Log msn/gtalk connection events.
     """
+    filename = ''
     if bot == 'msn':
         filename = LOGDIR + '/msn_events'
     elif bot == 'gtalk':
     """
     remove_cache(senderemail)
     if CHATBOT.getPredicate('name', senderemail) == '':
-        dispname = senderemail.split('@')
-        if len(dispname) == 2:
-            CHATBOT.setPredicate('name', dispname[0], senderemail)
-    remsg = CHATBOT.respond(message, senderemail)
-    remsg = getheader() + remsg + getfooter()
-    if not remsg:
-        remsg = u"Sorry, can't understand.".encode('utf-8')
-    return remsg
+        display_name = senderemail.split('@')
+        if len(display_name) == 2:
+            CHATBOT.setPredicate('name', display_name[0], senderemail)
+    re_msg = CHATBOT.respond(message, senderemail)
+    re_msg = getheader() + re_msg + getfooter()
+    if not re_msg:
+        re_msg = u"Sorry, can't understand.".encode('utf-8')
+    return re_msg
 
 
 def getheader():

primary/xmlfunctions.py

     Adds object like functionality to the standard dictionary.
     """
 
-    def __init__(self, iniciadicc=None):
+    def __init__(self, start_dic = None):
         """Starting"""
-        if iniciadicc is None:
-            iniciadicc = {}
-        dict.__init__(self, iniciadicc)
+        if start_dic is None:
+            start_dic = {}
+        dict.__init__(self, start_dic)
 
     def __getattr__(self, item):
         """Get Attributes"""
     """
     Defined function to help xmltodict
     """
-    nodedict = classdict()
+    node_dict = classdict()
     if len(node.items()) > 0:
         # if we have attributes, set them
-        nodedict.update(dict(node.items()))
+        node_dict.update(dict(node.items()))
 
     for child in node:
         # recursively add the element's children
-        newitem = _xmltodict(child, classdict)
-        if child.tag in nodedict:
+        new_item = _xmltodict(child, classdict)
+        if child.tag in node_dict:
             # found duplicate tag, force a list
-            if isinstance(nodedict[child.tag], list):
+            if isinstance(node_dict[child.tag], list):
                 # append to existing list
-                nodedict[child.tag].append(newitem)
+                node_dict[child.tag].append(new_item)
             else:
                 # convert to list
-                nodedict[child.tag] = [nodedict[child.tag], newitem]
+                node_dict[child.tag] = [node_dict[child.tag], new_item]
         else:
             # only one, directly set the dictionary
-            nodedict[child.tag] = newitem
+            node_dict[child.tag] = new_item
 
     if node.text is None:
         text = ''
     else:
         text = node.text
 
-    if len(nodedict) > 0:
+    if len(node_dict) > 0:
         # if we have a dictionary add the text as a dictionary
         # value (if there is any)
         if len(text) > 0:
-            nodedict['_text'] = text
+            node_dict['_text'] = text
     else:
         # if we don't have child nodes or attributes, just set the text
-        nodedict = text
-    return nodedict
+        node_dict = text
+    return node_dict
 
 
-def xmltodict(root, classdict=DictionaryXml):
+def xml_to_dict(root, class_dict=DictionaryXml):
     """
     Converts an XML file or ElementTree Element to a dictionary
     """
         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)})
+    return class_dict({root.tag: _xmltodict(root, class_dict)})