Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

python - python3 function not defined even though it is

when I try to call the changeProfile function, I keep getting the error "getAuthCode is not defined" even though it is clearly defined. Why do I keep getting this error? What am I doing wrong? It used to work from what I remember, but now all of a sudden it doesn't. Any help would be appreciated :)

import os,re,json,socket,random,select,threading,time,sys
import urllib.request as urlreq
from urllib.request import quote,unquote
import urllib.parse
class miscellanous:
    """Main class."""
    def __init__():
        """What to do on initalizing."""
        pass
    def getAuthCode(u, p):
        """Get authentification code from username and password specified."""
        try:
            data=urllib.request.urlopen('http://chatango.com/login',urllib.parse.urlencode({'user_id': u, 'password': p, 'storecookie': 'on', 'checkerrors': 'yes'}).encode()).headers
        except Exception as e: print("Error: Auth request: %s" % e)
        for x, y in data.items():
            if x.lower() == 'set-cookie':
                returned = re.compile(r"auth.chatango.com ?= ?([^;]*)", re.IGNORECASE).search(y)
                if returned:
                    ret = returned.group(1)
                    if ret == "": raise ValueError("Error: Unable to get auth: Error in username/password.")
                    return ret


    def createAccount(u, p):
        """Create an account with the username and password specified."""
        try:
            resp=urllib.request.urlopen("http://chatango.com/signupdir", urllib.parse.urlencode({"email": "accmaker"+str(random.randrange(1,1000000000000))+"@hotmail.com", "login": u, "password": p, "password_confirm": p, "storecookie": "on", "checkerrors": "yes"}).encode())
            fu=str(resp.read())
            resp.close()
            if "screen name has been" in fu: r = "Error: User could not be created: Already exists."
            else: r = "The user was created. If it didn't work, try another username."
            return r
        except: return "Error: Invalid or missing arguments."
    def createGroup(u, p, g, d="Description.", m="Owner message."):
        """Creates a group with the username, password, group name, description and owner message specified."""
        try:
            g=g.replace(" ","-")
            resp=urllib.request.urlopen("http://chatango.com/creategrouplogin",urllib.parse.urlencode({"User-Agent": "Mozilla/5.0", "uns": "0", "p": p, "lo": u, "d": d, "u": g, "n": m}).encode())
            fu=str(resp.read())
            resp.close()
            if "groupexists" in fu: r = "Error: Group could not be created: Already exists."
            else: r = "The group was created. If it didn't work, try another group name. Click <a href='http://%s.chatango.com/' target='_blank'>[[here]]<a> to get to the new group."
            return r
        except: return "Error: Invalid or missing arguments."
    def changeProfile(u, p, m="Default", e="accmaker"+str(random.randrange(1,1000000000000))+"@hotmail.com", l="Norway", g="M", a="18"):
        try:
            resp = urlreq.urlopen('http://'+u.lower()+'.chatango.com/updateprofile?&d&pic&s='+getAuthCode(u, p), urllib.parse.urlencode({"show_friends": "checked", "dir": "checked", "checkerrors": "yes", "uns": "1", "line": m, "email": e, "location": l, "gender": g, "age": a}).encode())
            return "The profile change was successful."
        except Exception as e:
            return "%s" % e
    def checkOnlineStatus(u):
        """Check if the predefined username is online or offline."""
        if "Chat with" in urlreq.urlopen("http://"+u.lower()+".chatango.com").read().decode(): return '<b><font color="#00ff00">Online</font></b>'
        else: return "<b><font color='#ff0000'>Offline</font></b>"
        resp.close()
    def checkUserGender(u):
        """Get the gender for the predefined username."""
        resp=urlreq.urlopen("http://st.chatango.com/profileimg/%s/%s/%s/mod1.xml" % (u.lower()[0], u.lower()[1], u.lower()))
        try: ru=re.compile(r'<s>(.*?)</s>', re.IGNORECASE).search(resp.read().decode()).group(1)
        except: ru="?"
        ret=unquote(ru)
        resp.close()
        if ret=="M": r="Male"
        elif ret=="F": r="Female"
        elif ret=="?": r="Not specified"        
        return r
    def changeBackGround(u, p, x, transparency=None):
        """Update the user's bg using the predefined username, password and bg color."""
        color=quote(x.split()[0])
        try: image=x.split()[1]
        except: image=None
        if color and len(color)==1:
            color=color*6
        if color and len(color)==3:
            color+=color
        elif color and len(color)!=6:
            return False
        if transparency!=None and abs(transparency)>1:
            transparency = abs(transparency) / 100
        data=urllib.request.urlopen("http://fp.chatango.com/profileimg/%s/%s/%s/msgbg.xml" % (u[0], u[1], u.lower())).read().decode()
        data=dict([x.replace('"', '').split("=") for x in re.findall('(w+=".*?")', data)[1:]])
        data["p"]=p
        data["lo"]=u
        if color: data["bgc"] = color
        if transparency!=None: data["bgalp"]=abs(transparency) * 100
        if image!=None: data["useimg"]=1 if bool(image) else 0
        data12=urllib.parse.urlencode(data)
        data13=data12.encode()
        der=urllib.request.urlopen("http://chatango.com/updatemsgbg", data13).read()
    def checkIfGroupExists(g):
        """Check if the predefined group exists."""
        i = urlreq.urlopen('http://'+g+'.chatango.com').read().decode()
        if '<table id="group_table"' in i: return True#"This chat does exist!"
        else: return False#"This chat doesn't exist."
        i.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

All of the functions you've shown are part of the miscellaneous class, so to access them, you need to prefix them with the class name. To refer to the getAuthCode function, you'd use miscellaneous.getAuthCode.

But, it doesn't seem like you should really be using a class here. You never create instances of miscellaneous, nor are the functions set up to be run as methods. So, probably the right answer is to get rid of the class miscellaneous: declaration at the top of the file, and then to unindent all the functions one level.

(Note, in Python 2 you'd have an additional issue if you kept the class: Unbound methods required that their first argument be an instance of their class (or a subclass). In that situation, you'd need to use the staticmethod decorator on any functions that did not expect to get an instance at all.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...