def initialize(): """ Initializes the global NST instance with the current NST and begins tracking """ NST.running = True pg = Page("http://www.neopets.com/") curtime = pg.find("td", {'id': 'nst'}).text NST.curTime = datetime.datetime.strptime(curtime.replace(" NST", ""), "%I:%M:%S %p") + datetime.timedelta(0,2) NST.inst = NST() NST.daemon = True # Ensures the thread is properly destroyed when the master thread terminates NST.inst.start()
def __init__(self, username, password="", pin=None): # Neopets automatically converts all capitals in a username to lowercase self.username = username.lower() self.password = password self.pin = pin # Initialize self.inventory = UserInventory(self) self.shop = UserShop(self) self.bank = Bank(self) self.SDB = SDB(self) # Each User instance needs a unique session self.session = Page.newSession() # Default hooks self.hooks = [] self.hooks.append(updateNPs) self.hooks.append(updatePet) self.hooks.append(autoLogin) # Config if not Configuration.loaded(): if Configuration.initialize(): self.__loadConfig() else: self.__loadConfig()
def getPage(self, url, postData = None, vars = None, usePin = False): """ Requests and returns a page using the user's session If useRef is set to true, automatically appends a referer using the user's last page to the request. If usePin is set to true, automatically appends the user's pin to the POST data. If browser sync is enabled, automatically retrieves and uses the browser's most up to date cookies for the request and attempts to save the updated cookies to the browser's cookie database. If useHooks is set to true, delivers the resulting Page object to each hook function for processing. Finally, returns the requested page. Parameters url (str) -- URL of remote page postData (dict) -- POST data to send with request vars (dict) -- Additional HTTP Header variables to send with request usePin (bool) -- Whether or not to send the user's pin with the request Returns Page -- Requested page Raises neopetsOfflineException """ # If using a referer is desired and one has not already been supplied, # then set the referer to the user's last visited page. if self.useRef and len(self.lastPage) > 0: if not vars: vars = {'Referer': self.lastPage} elif not "Referer" in vars: vars['Referer'] = self.lastPage self.lastPage = url if usePin: if self.pin: # All forms that require a pin share the same variable name of 'pin' postData['pin'] = str(self.pin) if bool(self.browserSync): self.__syncCookies() pg = Page(url, usr=self, postData=postData, vars=vars, proxy=self.proxy) if self.browserSync: self.__writeCookies() if "http://images.neopets.com/homepage/indexbak_oops_en.png" in pg.content: raise neopetsOfflineException if self.useHooks: for hook in self.hooks: self, pg = hook(self, pg) return pg
def autoLogin(usr, pg): if "http://www.neopets.com/login/index.phtml" in pg.resp.url: # If auto login is enabled, try to log back in, otherwise raise an exception to let higher processes know the user is logged out. if usr.autoLogin: # Clear cookies usr.session = Page.newSession() if usr.login(): # Request the page again now that the user is logged in pg = usr.getPage(pg.url, pg.postData, pg.vars) else: # Failed to login. Update status, log it, and raise an exception logging.getLogger("neolib.user").info("User was logged out. Failed to log back in.") raise logoutException else: # Auto login is not enabled. Update status and raise an exception. usr.loggedIn = False logging.getLogger("neolib.user").info("User was logged out. Auto login is disabled.") raise logoutException return [usr, pg]
def get_page(self, url, post_data='', header_values=''): """A wrapper function that returns a page using the user's session This method should be used over initializing a new page object by supplying the user's session. It performs checks to inject the user's pin number at the appropriate time as well as checks for random events and acts on them accordingly. Args: | **url**: The url of the page to request | **post_data**: Optional dictionary containing post data to POST | **header_values**: Optional dictionary to override header values Returns: A :class:`.Page` object representng the requested page """ # Inject a referer (Neopets looks for these often) if not header_values and self._last_page: header_values = {'Referer': self._last_page} elif "Referer" not in header_values and self._last_page: header_values['Referer'] = self._last_page pg = Page(url, self, post_data=post_data, header_values=header_values) # Check if this is an HTML page if type(pg.content) is bytes: return pg self._last_page = url # This image is shown if Neopets is offline if "http://images.neopets.com/homepage/indexbak_oops_en.png" in pg.content: raise NeopetsOffline # Call hooks for hook in self.hooks: h = hook() h.execute(self, pg) return pg
def autoLogin(usr, pg): if "http://www.neopets.com/login/index.phtml" in pg.resp.url: # If auto login is enabled, try to log back in, otherwise raise an exception to let higher processes know the user is logged out. if usr.autoLogin: # Clear cookies usr.session = Page.newSession() if usr.login(): # Request the page again now that the user is logged in pg = usr.getPage(pg.url, pg.postData, pg.vars) else: # Failed to login. Update status, log it, and raise an exception logging.getLogger("neolib.user").info( "User was logged out. Failed to log back in.") raise logoutException else: # Auto login is not enabled. Update status and raise an exception. usr.loggedIn = False logging.getLogger("neolib.user").info( "User was logged out. Auto login is disabled.") raise logoutException return [usr, pg]