-4

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()
Arman Shah
  • 111
  • 1
  • 6
  • Post the full traceback please. – interjay Feb 21 '15 at 00:36
  • 3
    Stop. Stop. [Go back and read.](https://docs.python.org/3/tutorial/classes.html) You're missing several fundamentals. – Ignacio Vazquez-Abrams Feb 21 '15 at 00:39
  • Is it a instance method for the class if it is you are missing a self. Should be self.getAuthcode() also for all the methods Did you forget to add a `self` in the object methods ?https://docs.python.org/2/tutorial/classes.html this might help specifically class and instance variables. The link is for 2.7.9 – cmidi Feb 21 '15 at 00:40
  • 3
    wow your code is like a python car crash! You have violated pretty much every pep8 standard. https://www.python.org/dev/peps/pep-0008/ – Padraic Cunningham Feb 21 '15 at 00:40

2 Answers2

1

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

Blckknght
  • 100,903
  • 11
  • 120
  • 169
  • in python 3 you can just call on the class rather than an instance like that? without having to declare static? ... thats kind of neat – Joran Beasley Feb 21 '15 at 00:59
  • Yes, in Python 3 an unbound method (i.e. a function in a class that you access via the class rather than an instance) is just a normal function. In Python 2, you'd get a special kind of bound method object, which would do a type check on the first argument (other than the check it still worked just like a normal function). The `staticmethod` decorator still exists so that you can call methods on instances without the instance being passed in when it's not wanted. I suppose that's the more complete answer: if you are going to keep the `miscellaneous` class, make everything a `staticmethod`. – Blckknght Feb 21 '15 at 01:30
0

Functions within a Python class are called methods. They normally take a self parameter before their other parameters. Furthermore, methods cannot "see" each other directly; you need to call them as self.method(args) instead of just method(args).

Kevin
  • 28,963
  • 9
  • 62
  • 81