python3 function not defined even though it is

2024/7/8 7:09:57

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."""passdef 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()).headersexcept 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 retdef 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 rexcept: 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 rexcept: 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" % edef 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 rdef 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=Noneif color and len(color)==1:color=color*6if color and len(color)==3:color+=colorelif color and len(color)!=6:return Falseif transparency!=None and abs(transparency)>1:transparency = abs(transparency) / 100data=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"]=pdata["lo"]=uif color: data["bgc"] = colorif transparency!=None: data["bgalp"]=abs(transparency) * 100if image!=None: data["useimg"]=1 if bool(image) else 0data12=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()
Answer

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

https://en.xdnf.cn/q/120585.html

Related Q&A

Python maximum and minimum

Im supposed to write a function max_and_min that accepts a tuple containing integer elements as an argument and returns the largest and smallest integer within the tuple. The return value should be a t…

Get differences between two excel files

Problem SummaryGiven 2 excel files, each with 200 columns approx, and have a common index column - ie each row in both files would have a name property say, what would be the best to generate an output…

Most pythonic way to call a list of functions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 4…

Unable to get wanted output using for and range functions

For my homework assignment, I am using the for loop and the range function. I have to create a loop that printsHello 0 Hello 1 Hello 3 Hello 6 Hello 10The question says that the number corresponds to t…

i want to add a new field to an existing module odoo11 but i dont know why it didnt work

product_template.xmlthe view to add the customizing field to the product module<?xml version="1.0" encoding="utf-8"?><odoo><data><record id="product_temp…

How to check with more RegEx for one address in python using re.findall()

How to check with more RegEx for one address in python using re.findall()Ex: I want to apply the below regex rules # need to get addresstxt = "hello user 44 West 22nd Street, New York, NY 12345 fr…

Finding all roots of an equation in Python

I have a function that I want to find its roots. I could write a program to figure out its roots but the point is, each time that I want to find the other root I should give it an initial value manuall…

defining matrix class in python

Define a class that abstracts the matrix that satisfies the following examples of practice

Why do round() and math.ceil() give different values for negative numbers in Python 3? [duplicate]

This question already has an answer here:What is the algorithmic difference between math.ceil() and round() when trailing decimal points are >= 0.5 in Python 3?(1 answer)Closed 6 years ago.Why do r…

getting the value from text file after the colon or before the colon in python

I only need the last number 25 so i can change it to int(). I have this text file:{"members": [{"name": "John", "location": "QC", "age": 25}…